1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-04-29 19:45:01 +02:00

Use shared AST in Toggle Function refactoring. This change concudes

the transition to CRefactoring2, which is now called CRefactoring.
This commit is contained in:
Sergey Prigogin 2012-02-23 20:44:17 -08:00
parent 688a0e6f75
commit 2f2f09fd97
49 changed files with 551 additions and 1348 deletions

View file

@ -40,12 +40,11 @@ import org.eclipse.core.runtime.IPath;
* @noinstantiate This class is not intended to be instantiated by clients. * @noinstantiate This class is not intended to be instantiated by clients.
*/ */
public class CoreModelUtil { public class CoreModelUtil {
/**
/* * Returns whether the given path matches one of the exclusion patterns.
* Returns whether the given path matches one of the exclusion patterns.
* @param resourcePath * @param resourcePath
* @param exclusionPatterns * @param exclusionPatterns
* @return * @return <code>true</code> if the given path matches one of the exclusion patterns.
*/ */
public static boolean isExcludedPath(IPath resourcePath, IPath[] exclusionPatterns) { public static boolean isExcludedPath(IPath resourcePath, IPath[] exclusionPatterns) {
int length = exclusionPatterns.length; int length = exclusionPatterns.length;
@ -56,24 +55,19 @@ public class CoreModelUtil {
return isExcluded(resourcePath, fullCharExclusionPatterns); return isExcluded(resourcePath, fullCharExclusionPatterns);
} }
/* /**
* Returns whether the given resource matches one of the exclusion patterns. * Returns whether the given resource matches one of the exclusion patterns.
*
* @see IClasspathEntry#getExclusionPatterns
*/ */
public final static boolean isExcluded(IResource resource, char[][] exclusionPatterns) { public final static boolean isExcluded(IResource resource, char[][] exclusionPatterns) {
IPath path = resource.getFullPath(); IPath path = resource.getFullPath();
// ensure that folders are only excluded if all of their children are // Ensure that folders are only excluded if all of their children are excluded.
// excluded
if (resource.getType() == IResource.FOLDER) if (resource.getType() == IResource.FOLDER)
path = path.append("*"); //$NON-NLS-1$ path = path.append("*"); //$NON-NLS-1$
return isExcluded(path, exclusionPatterns); return isExcluded(path, exclusionPatterns);
} }
/* /**
* Returns whether the given resource path matches one of the exclusion patterns. * Returns whether the given resource path matches one of the exclusion patterns.
*
* @see IClasspathEntry#getExclusionPatterns
*/ */
public final static boolean isExcluded(IPath resourcePath, char[][] exclusionPatterns) { public final static boolean isExcluded(IPath resourcePath, char[][] exclusionPatterns) {
if (exclusionPatterns == null) if (exclusionPatterns == null)
@ -93,7 +87,7 @@ public class CoreModelUtil {
/* /*
* if b is a prefix of a return true. * if b is a prefix of a return true.
*/ */
static boolean prefixOfCharArray (char[] a, char[] b) { static boolean prefixOfCharArray(char[] a, char[] b) {
if (a == b) if (a == b)
return true; return true;
if (a == null || b == null) if (a == null || b == null)
@ -110,7 +104,6 @@ public class CoreModelUtil {
return false; return false;
} }
return true; return true;
} }
/** /**

View file

@ -49,7 +49,7 @@ import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.PreferenceConstants; import org.eclipse.cdt.ui.PreferenceConstants;
import org.eclipse.cdt.ui.testplugin.CTestPlugin; import org.eclipse.cdt.ui.testplugin.CTestPlugin;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringContext; import org.eclipse.cdt.internal.ui.refactoring.CRefactoringContext;
/** /**
@ -165,8 +165,8 @@ public abstract class RefactoringTestBase extends BaseTestCase {
Refactoring refactoring = createRefactoring(); Refactoring refactoring = createRefactoring();
RefactoringContext context; RefactoringContext context;
if (refactoring instanceof CRefactoring2) { if (refactoring instanceof CRefactoring) {
context = new CRefactoringContext((CRefactoring2) refactoring); context = new CRefactoringContext((CRefactoring) refactoring);
} else { } else {
context = new RefactoringContext(refactoring); context = new RefactoringContext(refactoring);
} }

View file

@ -49,7 +49,7 @@ public class ToggleRefactoringTest extends RefactoringTestBase {
@Override @Override
protected Refactoring createRefactoring() { protected Refactoring createRefactoring() {
refactoring = new ToggleRefactoring(getSelectedFile(), getSelection(), getCProject()); refactoring = new ToggleRefactoring(getSelectedTranslationUnit(), getSelection(), getCProject());
return refactoring; return refactoring;
} }

View file

@ -27,13 +27,13 @@ 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.tests.refactoring.RefactoringTestBase; import org.eclipse.cdt.ui.tests.refactoring.RefactoringTestBase;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringContext; import org.eclipse.cdt.internal.ui.refactoring.CRefactoringContext;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
import org.eclipse.cdt.internal.ui.refactoring.utils.DefinitionFinder; import org.eclipse.cdt.internal.ui.refactoring.utils.DefinitionFinder;
public class DefinitionFinderTest extends RefactoringTestBase { public class DefinitionFinderTest extends RefactoringTestBase {
private static class DummyRefactoring extends CRefactoring2 { private static class DummyRefactoring extends CRefactoring {
public DummyRefactoring(ICElement element, ISelection selection, ICProject project) { public DummyRefactoring(ICElement element, ISelection selection, ICProject project) {
super(element, selection, project); super(element, selection, project);
} }
@ -64,7 +64,7 @@ public class DefinitionFinderTest extends RefactoringTestBase {
} }
@Override @Override
protected CRefactoring2 createRefactoring() { protected CRefactoring createRefactoring() {
return new DummyRefactoring(getSelectedTranslationUnit(), getSelection(), getCProject()); return new DummyRefactoring(getSelectedTranslationUnit(), getSelection(), getCProject());
} }

View file

@ -1,101 +0,0 @@
/*******************************************************************************
* Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* Sergey Prigogin (Google)
*******************************************************************************/
package org.eclipse.cdt.ui.tests.refactoring.utils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.ui.tests.refactoring.RefactoringTestBase;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
import org.eclipse.cdt.internal.ui.refactoring.utils.TranslationUnitHelper;
public class TranslationUnitHelperTest extends RefactoringTestBase {
private static class DummyRefactoring extends CRefactoring {
public DummyRefactoring(IFile file, ISelection selection, ICElement element, ICProject proj) {
super(file, selection, element, proj);
}
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor progressMonitor) throws CoreException, OperationCanceledException {
return null;
}
@Override
protected RefactoringDescriptor getRefactoringDescriptor() {
return null;
}
@Override
protected void collectModifications(IProgressMonitor pm, ModificationCollector collector)
throws CoreException, OperationCanceledException {
}
}
public TranslationUnitHelperTest() {
super();
}
public TranslationUnitHelperTest(String name) {
super(name);
}
@Override
protected Refactoring createRefactoring() {
return new DummyRefactoring(getSelectedFile(), getSelection(), null, getCProject());
}
private void assertFirstNodeIsAtOffset(int offset) throws Exception {
IASTTranslationUnit ast = TranslationUnitHelper.loadTranslationUnit(getSelectedFile(), false);
IASTNode firstNode = TranslationUnitHelper.getFirstNode(ast);
assertEquals(offset, firstNode.getNodeLocations()[0].getNodeOffset());
}
//A.h
//#ifndef A_H_
//#define A_H_
//
//class A {
//public:
// A();
// void foo();
//};
//
//#endif /*A_H_*/
public void testBeforeClass() throws Exception {
assertFirstNodeIsAtOffset(27);
}
//A.h
//typedef int nummere;
//
//class A {
//public:
// A();
//};
public void testBeforeTypedef() throws Exception {
assertFirstNodeIsAtOffset(0);
}
}

View file

@ -23,7 +23,6 @@ public class UtilTestSuite extends TestSuite {
public static Test suite() throws Exception { public static Test suite() throws Exception {
UtilTestSuite suite = new UtilTestSuite(); UtilTestSuite suite = new UtilTestSuite();
suite.addTest(IdentifierHelperTest.suite()); suite.addTest(IdentifierHelperTest.suite());
suite.addTestSuite(TranslationUnitHelperTest.class);
suite.addTestSuite(DefinitionFinderTest.class); suite.addTestSuite(DefinitionFinderTest.class);
suite.addTestSuite(PseudoNameGeneratorTest.class); suite.addTestSuite(PseudoNameGeneratorTest.class);
suite.addTestSuite(NameComposerTest.class); suite.addTestSuite(NameComposerTest.class);

View file

@ -330,13 +330,13 @@ public final class SourceHeaderPartnerFinder {
} }
public static ITranslationUnit getPartnerTranslationUnit(ITranslationUnit tu, public static ITranslationUnit getPartnerTranslationUnit(ITranslationUnit tu,
CRefactoringContext astCache) throws CoreException { CRefactoringContext refactoringContext) throws CoreException {
ITranslationUnit partnerUnit= getPartnerFileFromFilename(tu); ITranslationUnit partnerUnit= getPartnerFileFromFilename(tu);
if (partnerUnit == null) { if (partnerUnit == null) {
// Search partner file based on definition/declaration association // Search partner file based on definition/declaration association
IProgressMonitor monitor= new NullProgressMonitor(); IProgressMonitor monitor= new NullProgressMonitor();
IASTTranslationUnit ast = astCache.getAST(tu, monitor); IASTTranslationUnit ast = refactoringContext.getAST(tu, monitor);
PartnerFileVisitor visitor = new PartnerFileVisitor(); PartnerFileVisitor visitor = new PartnerFileVisitor();
ast.accept(visitor); ast.accept(visitor);
partnerUnit = createTranslationUnit(visitor.getPartnerFileLocation(), tu.getCProject()); partnerUnit = createTranslationUnit(visitor.getPartnerFileLocation(), tu.getCProject());
@ -344,12 +344,12 @@ public final class SourceHeaderPartnerFinder {
return partnerUnit; return partnerUnit;
} }
private static ITranslationUnit createTranslationUnit(IPath partnerFileLoation, ICProject cProject) { private static ITranslationUnit createTranslationUnit(IPath partnerFileLoation, ICProject project) {
ITranslationUnit partnerUnit = null; ITranslationUnit partnerUnit = null;
if (partnerFileLoation != null) { if (partnerFileLoation != null) {
partnerUnit= (ITranslationUnit) CoreModel.getDefault().create(partnerFileLoation); partnerUnit= (ITranslationUnit) CoreModel.getDefault().create(partnerFileLoation);
if (partnerUnit == null) { if (partnerUnit == null) {
partnerUnit= CoreModel.getDefault().createTranslationUnitFrom(cProject.getCProject(), partnerUnit= CoreModel.getDefault().createTranslationUnitFrom(project,
partnerFileLoation); partnerFileLoation);
} }
} }

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
@ -7,16 +7,22 @@
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* 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; package org.eclipse.cdt.internal.ui.refactoring;
import org.eclipse.core.resources.IFile; import java.util.ArrayList;
import org.eclipse.core.resources.IResource; import java.util.List;
import org.eclipse.core.runtime.Assert;
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.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
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;
import org.eclipse.ltk.core.refactoring.Change; import org.eclipse.ltk.core.refactoring.Change;
@ -24,12 +30,15 @@ import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor; import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
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.ResourceChangeChecker;
import org.eclipse.ltk.core.refactoring.participants.ValidateEditChecker;
import org.eclipse.osgi.util.NLS; import org.eclipse.osgi.util.NLS;
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;
@ -38,9 +47,9 @@ 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.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.ISourceRange; import org.eclipse.cdt.core.model.ISourceRange;
@ -48,51 +57,176 @@ import org.eclipse.cdt.core.model.ISourceReference;
import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.corext.util.CModelUtil;
import org.eclipse.cdt.internal.ui.refactoring.utils.SelectionHelper; import org.eclipse.cdt.internal.ui.refactoring.utils.SelectionHelper;
/** /**
* The base class for all other refactorings, provides some common implementations for * The base class for all AST based refactorings, provides some common implementations for
* condition checking, change generating, selection handling and translation unit loading. * AST creation, condition checking, change generating, and selection handling.
* @deprecated Use CRefactoring2.
*/ */
@Deprecated
public abstract class CRefactoring extends Refactoring { public abstract class CRefactoring extends Refactoring {
private static final int AST_STYLE =
ITranslationUnit.AST_CONFIGURE_USING_SOURCE_CONTEXT | ITranslationUnit.AST_SKIP_INDEXED_HEADERS;
protected String name = Messages.Refactoring_name; protected String name = Messages.Refactoring_name;
protected IFile file; protected final ICProject project;
protected final ITranslationUnit tu; protected final ITranslationUnit tu;
protected Region region; protected Region selectedRegion;
protected RefactoringStatus initStatus; protected final RefactoringStatus initStatus;
protected IASTTranslationUnit ast; protected CRefactoringContext refactoringContext;
protected ICProject project;
private IIndex fIndex;
public CRefactoring(IFile file, ISelection selection, ICElement element, ICProject proj) { public CRefactoring(ICElement element, ISelection selection, ICProject project) {
project = proj; this.project = project;
if (element instanceof ISourceReference) { this.initStatus= new RefactoringStatus();
ISourceReference sourceRef= (ISourceReference) element; if (!(element instanceof ISourceReference)) {
this.tu = sourceRef.getTranslationUnit(); this.tu = null;
IResource res= tu.getResource(); initStatus.addFatalError(Messages.Refactoring_SelectionNotValid);
if (res instanceof IFile) return;
this.file= (IFile) res; }
ISourceReference sourceRef= (ISourceReference) element;
tu = CModelUtil.toWorkingCopy(sourceRef.getTranslationUnit());
if (selection instanceof ITextSelection) {
this.selectedRegion = SelectionHelper.getRegion(selection);
} else {
try { try {
final ISourceRange sourceRange = sourceRef.getSourceRange(); ISourceRange sourceRange = sourceRef.getSourceRange();
this.region = new Region(sourceRange.getIdStartPos(), sourceRange.getIdLength()); this.selectedRegion = new Region(sourceRange.getIdStartPos(), sourceRange.getIdLength());
} catch (CModelException e) { } catch (CModelException e) {
CUIPlugin.log(e); CUIPlugin.log(e);
} }
} else {
this.file = file;
this.tu = (ITranslationUnit) CCorePlugin.getDefault().getCoreModel().create(file);
this.region = SelectionHelper.getRegion(selection);
} }
}
this.initStatus= new RefactoringStatus(); public void setContext(CRefactoringContext refactoringContext) {
if (this.file == null || region == null) { Assert.isNotNull(refactoringContext);
initStatus.addFatalError(Messages.Refactoring_SelectionNotValid); this.refactoringContext = refactoringContext;
}
@Override
public final RefactoringStatus checkFinalConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
if (pm == null)
pm = new NullProgressMonitor();
pm.beginTask(Messages.CRefactoring_checking_final_conditions, 6);
CheckConditionsContext context = createCheckConditionsContext();
RefactoringStatus result = checkFinalConditions(new SubProgressMonitor(pm, 5), context);
if (result.hasFatalError()) {
pm.done();
return result;
} }
if (pm.isCanceled())
throw new OperationCanceledException();
result.merge(context.check(new SubProgressMonitor(pm, 1)));
pm.done();
return result;
}
protected RefactoringStatus checkFinalConditions(IProgressMonitor subProgressMonitor,
CheckConditionsContext checkContext) throws CoreException, OperationCanceledException {
return new RefactoringStatus();
}
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
SubMonitor sm = SubMonitor.convert(pm, 10);
sm.subTask(Messages.Refactoring_PM_LoadTU);
if (isProgressMonitorCanceld(sm, initStatus)) {
return initStatus;
}
IASTTranslationUnit ast = getAST(tu, sm);
if (ast == null) {
initStatus.addError(NLS.bind(Messages.Refactoring_ParsingError, tu.getPath()));
return initStatus;
}
if (isProgressMonitorCanceld(sm, initStatus)) {
return initStatus;
}
sm.subTask(Messages.Refactoring_PM_CheckTU);
checkAST(ast);
sm.worked(2);
sm.subTask(Messages.Refactoring_PM_InitRef);
sm.done();
return initStatus;
}
protected static boolean isProgressMonitorCanceld(IProgressMonitor sm, RefactoringStatus status) {
if (sm.isCanceled()) {
status.addFatalError(Messages.Refactoring_CanceledByUser);
return true;
}
return false;
}
@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
ModificationCollector collector = new ModificationCollector();
collectModifications(pm, collector);
CCompositeChange finalChange = collector.createFinalChange();
finalChange.setDescription(new RefactoringChangeDescriptor(getRefactoringDescriptor()));
return finalChange;
}
abstract protected RefactoringDescriptor getRefactoringDescriptor();
abstract protected void collectModifications(IProgressMonitor pm, ModificationCollector collector)
throws CoreException, OperationCanceledException;
@Override
public String getName() {
return name;
}
/**
* Returns the translation unit where the refactoring started.
*/
public ITranslationUnit getTranslationUnit() {
return tu;
}
protected IASTTranslationUnit getAST(ITranslationUnit tu, IProgressMonitor pm)
throws CoreException, OperationCanceledException {
return refactoringContext.getAST(tu, pm);
}
protected IIndex getIndex() throws OperationCanceledException, CoreException {
return refactoringContext.getIndex();
}
protected boolean checkAST(IASTTranslationUnit ast) {
ProblemFinder problemFinder = new ProblemFinder(initStatus);
ast.accept(problemFinder);
return problemFinder.hasProblem();
}
protected List<IASTName> findAllMarkedNames(IASTTranslationUnit ast) {
final List<IASTName> names = new ArrayList<IASTName>();
ast.accept(new ASTVisitor() {
{
shouldVisitNames = true;
}
@Override
public int visit(IASTName name) {
if (name.isPartOfTranslationUnitFile() &&
SelectionHelper.doesNodeOverlapWithRegion(name, selectedRegion) &&
!(name instanceof ICPPASTQualifiedName)) {
names.add(name);
}
return super.visit(name);
}
});
return names;
}
private CheckConditionsContext createCheckConditionsContext() throws CoreException {
CheckConditionsContext result= new CheckConditionsContext();
result.add(new ValidateEditChecker(getValidationContext()));
result.add(new ResourceChangeChecker());
return result;
} }
private class ProblemFinder extends ASTVisitor { private class ProblemFinder extends ASTVisitor {
@ -102,7 +236,7 @@ public abstract class CRefactoring extends Refactoring {
public ProblemFinder(RefactoringStatus status) { public ProblemFinder(RefactoringStatus status) {
this.status = status; this.status = status;
} }
{ {
shouldVisitProblems = true; shouldVisitProblems = true;
shouldVisitDeclarations = true; shouldVisitDeclarations = true;
@ -116,7 +250,7 @@ public abstract class CRefactoring extends Refactoring {
addWarningToState(); addWarningToState();
return ASTVisitor.PROCESS_CONTINUE; return ASTVisitor.PROCESS_CONTINUE;
} }
@Override @Override
public int visit(IASTDeclaration declaration) { public int visit(IASTDeclaration declaration) {
if (declaration instanceof IASTProblemDeclaration) { if (declaration instanceof IASTProblemDeclaration) {
@ -124,7 +258,7 @@ public abstract class CRefactoring extends Refactoring {
} }
return ASTVisitor.PROCESS_CONTINUE; return ASTVisitor.PROCESS_CONTINUE;
} }
@Override @Override
public int visit(IASTExpression expression) { public int visit(IASTExpression expression) {
if (expression instanceof IASTProblemExpression) { if (expression instanceof IASTProblemExpression) {
@ -152,7 +286,7 @@ public abstract class CRefactoring extends Refactoring {
public boolean hasProblem() { public boolean hasProblem() {
return problemFound; return problemFound;
} }
private void addWarningToState() { private void addWarningToState() {
if (!problemFound) { if (!problemFound) {
status.addWarning(Messages.Refactoring_CompileErrorInTU); status.addWarning(Messages.Refactoring_CompileErrorInTU);
@ -160,147 +294,4 @@ public abstract class CRefactoring extends Refactoring {
} }
} }
} }
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
RefactoringStatus status = new RefactoringStatus();
return status;
}
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
SubMonitor sm = SubMonitor.convert(pm, 10);
sm.subTask(Messages.Refactoring_PM_LoadTU);
if (isProgressMonitorCanceld(sm, initStatus)) {
return initStatus;
}
if (!loadTranslationUnit(initStatus, sm.newChild(8))) {
initStatus.addError(Messages.Refactoring_CantLoadTU);
return initStatus;
}
if (isProgressMonitorCanceld(sm, initStatus)) {
return initStatus;
}
sm.subTask(Messages.Refactoring_PM_CheckTU);
translationUnitHasProblem();
if (translationUnitIsAmbiguous()) {
initStatus.addError(Messages.Refactoring_Ambiguity);
}
sm.worked(2);
sm.subTask(Messages.Refactoring_PM_InitRef);
sm.done();
return initStatus;
}
protected static boolean isProgressMonitorCanceld(IProgressMonitor sm, RefactoringStatus status) {
if (sm.isCanceled()) {
status.addFatalError(Messages.Refactoring_CanceledByUser);
return true;
}
return false;
}
@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
ModificationCollector collector = new ModificationCollector();
collectModifications(pm, collector);
CCompositeChange finalChange = null;
try {
lockIndex();
finalChange = collector.createFinalChange();
} catch (InterruptedException e) {
throw new OperationCanceledException();
} finally {
unlockIndex();
}
finalChange.setDescription(new RefactoringChangeDescriptor(getRefactoringDescriptor()));
return finalChange;
}
abstract protected RefactoringDescriptor getRefactoringDescriptor();
abstract protected void collectModifications(IProgressMonitor pm, ModificationCollector collector)
throws CoreException, OperationCanceledException;
@Override
public String getName() {
return name;
}
protected boolean loadTranslationUnit(RefactoringStatus status, IProgressMonitor mon) {
SubMonitor subMonitor = SubMonitor.convert(mon, 10);
if (tu != null) {
try {
subMonitor.subTask(Messages.Refactoring_PM_ParseTU);
ast = tu.getAST(fIndex, AST_STYLE);
if (ast == null) {
subMonitor.done();
return false;
}
subMonitor.worked(2);
if (isProgressMonitorCanceld(subMonitor, initStatus)) {
return true;
}
subMonitor.subTask(Messages.Refactoring_PM_MergeComments);
subMonitor.worked(8);
} catch (CoreException e) {
status.addFatalError(e.getMessage());
subMonitor.done();
return false;
}
} else {
status.addFatalError(NLS.bind(Messages.CRefactoring_FileNotFound, tu.getPath().toString()));
subMonitor.done();
return false;
}
subMonitor.done();
return true;
}
protected boolean translationUnitHasProblem() {
ProblemFinder pf = new ProblemFinder(initStatus);
ast.accept(pf);
return pf.hasProblem();
}
protected boolean translationUnitIsAmbiguous() {
// ambiguities are resolved before the tu is passed to the refactoring.
return false;
}
public void lockIndex() throws CoreException, InterruptedException {
if (fIndex == null) {
ICProject[] projects= CoreModel.getDefault().getCModel().getCProjects();
fIndex= CCorePlugin.getIndexManager().getIndex(projects);
}
fIndex.acquireReadLock();
}
public void unlockIndex() {
if (fIndex != null) {
fIndex.releaseReadLock();
}
// Marc-Andre Laperle : I don't think we want to null this out,
// if the lock is acquired twice then the lock can only be released once
//fIndex= null;
}
public IIndex getIndex() {
return fIndex;
}
/**
* Returns the translation unit where the refactoring started.
*/
public ITranslationUnit getTranslationUnit() {
return tu;
}
public IASTTranslationUnit getUnit() {
return ast;
}
} }

View file

@ -1,299 +0,0 @@
/*******************************************************************************
* Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* Sergey Prigogin (Google)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
import org.eclipse.ltk.core.refactoring.participants.ResourceChangeChecker;
import org.eclipse.ltk.core.refactoring.participants.ValidateEditChecker;
import org.eclipse.osgi.util.NLS;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
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.IASTProblemDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTProblemExpression;
import org.eclipse.cdt.core.dom.ast.IASTProblemStatement;
import org.eclipse.cdt.core.dom.ast.IASTProblemTypeId;
import org.eclipse.cdt.core.dom.ast.IASTStatement;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
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.model.CModelException;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ISourceRange;
import org.eclipse.cdt.core.model.ISourceReference;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.corext.util.CModelUtil;
import org.eclipse.cdt.internal.ui.refactoring.utils.SelectionHelper;
/**
* The base class for all AST based refactorings, provides some common implementations for
* AST creation, condition checking, change generating, and selection handling.
* This class is intended as a replacement for CRefactoring.
*/
public abstract class CRefactoring2 extends Refactoring {
protected String name = Messages.Refactoring_name;
protected final ICProject project;
protected final ITranslationUnit tu;
protected Region selectedRegion;
protected final RefactoringStatus initStatus;
protected CRefactoringContext refactoringContext;
public CRefactoring2(ICElement element, ISelection selection, ICProject project) {
this.project = project;
this.initStatus= new RefactoringStatus();
if (!(element instanceof ISourceReference)) {
this.tu = null;
initStatus.addFatalError(Messages.Refactoring_SelectionNotValid);
return;
}
ISourceReference sourceRef= (ISourceReference) element;
tu = CModelUtil.toWorkingCopy(sourceRef.getTranslationUnit());
if (selection instanceof ITextSelection) {
this.selectedRegion = SelectionHelper.getRegion(selection);
} else {
try {
ISourceRange sourceRange = sourceRef.getSourceRange();
this.selectedRegion = new Region(sourceRange.getIdStartPos(), sourceRange.getIdLength());
} catch (CModelException e) {
CUIPlugin.log(e);
}
}
}
public void setContext(CRefactoringContext refactoringContext) {
Assert.isNotNull(refactoringContext);
this.refactoringContext = refactoringContext;
}
@Override
public final RefactoringStatus checkFinalConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
if (pm == null)
pm = new NullProgressMonitor();
pm.beginTask(Messages.CRefactoring_checking_final_conditions, 6);
CheckConditionsContext context = createCheckConditionsContext();
RefactoringStatus result = checkFinalConditions(new SubProgressMonitor(pm, 5), context);
if (result.hasFatalError()) {
pm.done();
return result;
}
if (pm.isCanceled())
throw new OperationCanceledException();
result.merge(context.check(new SubProgressMonitor(pm, 1)));
pm.done();
return result;
}
protected RefactoringStatus checkFinalConditions(IProgressMonitor subProgressMonitor,
CheckConditionsContext checkContext) throws CoreException, OperationCanceledException {
return new RefactoringStatus();
}
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
SubMonitor sm = SubMonitor.convert(pm, 10);
sm.subTask(Messages.Refactoring_PM_LoadTU);
if (isProgressMonitorCanceld(sm, initStatus)) {
return initStatus;
}
IASTTranslationUnit ast = getAST(tu, sm);
if (ast == null) {
initStatus.addError(NLS.bind(Messages.Refactoring_ParsingError, tu.getPath()));
return initStatus;
}
if (isProgressMonitorCanceld(sm, initStatus)) {
return initStatus;
}
sm.subTask(Messages.Refactoring_PM_CheckTU);
checkAST(ast);
sm.worked(2);
sm.subTask(Messages.Refactoring_PM_InitRef);
sm.done();
return initStatus;
}
protected static boolean isProgressMonitorCanceld(IProgressMonitor sm, RefactoringStatus status) {
if (sm.isCanceled()) {
status.addFatalError(Messages.Refactoring_CanceledByUser);
return true;
}
return false;
}
@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
ModificationCollector collector = new ModificationCollector();
collectModifications(pm, collector);
CCompositeChange finalChange = collector.createFinalChange();
finalChange.setDescription(new RefactoringChangeDescriptor(getRefactoringDescriptor()));
return finalChange;
}
abstract protected RefactoringDescriptor getRefactoringDescriptor();
abstract protected void collectModifications(IProgressMonitor pm, ModificationCollector collector)
throws CoreException, OperationCanceledException;
@Override
public String getName() {
return name;
}
/**
* Returns the translation unit where the refactoring started.
*/
public ITranslationUnit getTranslationUnit() {
return tu;
}
protected IASTTranslationUnit getAST(ITranslationUnit tu, IProgressMonitor pm)
throws CoreException, OperationCanceledException {
return refactoringContext.getAST(tu, pm);
}
protected IIndex getIndex() throws OperationCanceledException, CoreException {
return refactoringContext.getIndex();
}
protected boolean checkAST(IASTTranslationUnit ast) {
ProblemFinder problemFinder = new ProblemFinder(initStatus);
ast.accept(problemFinder);
return problemFinder.hasProblem();
}
protected List<IASTName> findAllMarkedNames(IASTTranslationUnit ast) {
final List<IASTName> names = new ArrayList<IASTName>();
ast.accept(new ASTVisitor() {
{
shouldVisitNames = true;
}
@Override
public int visit(IASTName name) {
if (name.isPartOfTranslationUnitFile() &&
SelectionHelper.doesNodeOverlapWithRegion(name, selectedRegion) &&
!(name instanceof ICPPASTQualifiedName)) {
names.add(name);
}
return super.visit(name);
}
});
return names;
}
private CheckConditionsContext createCheckConditionsContext() throws CoreException {
CheckConditionsContext result= new CheckConditionsContext();
result.add(new ValidateEditChecker(getValidationContext()));
result.add(new ResourceChangeChecker());
return result;
}
private class ProblemFinder extends ASTVisitor {
private boolean problemFound = false;
private final RefactoringStatus status;
public ProblemFinder(RefactoringStatus status) {
this.status = status;
}
{
shouldVisitProblems = true;
shouldVisitDeclarations = true;
shouldVisitExpressions = true;
shouldVisitStatements = true;
shouldVisitTypeIds = true;
}
@Override
public int visit(IASTProblem problem) {
addWarningToState();
return ASTVisitor.PROCESS_CONTINUE;
}
@Override
public int visit(IASTDeclaration declaration) {
if (declaration instanceof IASTProblemDeclaration) {
addWarningToState();
}
return ASTVisitor.PROCESS_CONTINUE;
}
@Override
public int visit(IASTExpression expression) {
if (expression instanceof IASTProblemExpression) {
addWarningToState();
}
return ASTVisitor.PROCESS_CONTINUE;
}
@Override
public int visit(IASTStatement statement) {
if (statement instanceof IASTProblemStatement) {
addWarningToState();
}
return ASTVisitor.PROCESS_CONTINUE;
}
@Override
public int visit(IASTTypeId typeId) {
if (typeId instanceof IASTProblemTypeId) {
addWarningToState();
}
return ASTVisitor.PROCESS_CONTINUE;
}
public boolean hasProblem() {
return problemFound;
}
private void addWarningToState() {
if (!problemFound) {
status.addWarning(Messages.Refactoring_CompileErrorInTU);
problemFound = true;
}
}
}
}

View file

@ -47,7 +47,7 @@ public class CRefactoringContext extends RefactoringContext {
private IIndex fIndex; private IIndex fIndex;
private IASTTranslationUnit fSharedAST; private IASTTranslationUnit fSharedAST;
public CRefactoringContext(CRefactoring2 refactoring) { public CRefactoringContext(CRefactoring refactoring) {
super(refactoring); super(refactoring);
refactoring.setContext(this); refactoring.setContext(this);
fASTCache = new ConcurrentHashMap<ITranslationUnit, IASTTranslationUnit>(); fASTCache = new ConcurrentHashMap<ITranslationUnit, IASTTranslationUnit>();

View file

@ -32,11 +32,7 @@ public abstract class CRefactoringContribution extends RefactoringContribution {
if (descriptor instanceof CRefactoringDescriptor) { if (descriptor instanceof CRefactoringDescriptor) {
CRefactoringDescriptor refDesc = (CRefactoringDescriptor) descriptor; CRefactoringDescriptor refDesc = (CRefactoringDescriptor) descriptor;
return refDesc.getParameterMap(); return refDesc.getParameterMap();
} if (descriptor instanceof CRefactoringDescription) {
CRefactoringDescription refDesc = (CRefactoringDescription) descriptor;
return refDesc.getParameterMap();
} else {
return super.retrieveArgumentMap(descriptor);
} }
return super.retrieveArgumentMap(descriptor);
} }
} }

View file

@ -1,82 +0,0 @@
/*******************************************************************************
* Copyright (c) 2009 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 (IFS)- initial API and implementation
******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.core.resources.ResourceLookup;
/**
* @author Emanuel Graf IFS
* @deprecated Use {@link CRefactoringDescriptor} instead.
*/
@Deprecated
public abstract class CRefactoringDescription extends RefactoringDescriptor {
public static final String FILE_NAME = "fileName"; //$NON-NLS-1$
public static final String SELECTION = "selection"; //$NON-NLS-1$
protected Map<String, String> arguments;
public CRefactoringDescription(String id, String project, String description, String comment,
int flags, Map<String, String> arguments) {
super(id, project, description, comment, flags);
this.arguments = arguments;
}
public Map<String, String> getParameterMap() {
return arguments;
}
protected ISelection getSelection() throws CoreException {
String selectStrings[] = arguments.get(SELECTION).split(","); //$NON-NLS-1$
if (selectStrings.length < 2) {
throw new CoreException(new Status(IStatus.ERROR, CUIPlugin.PLUGIN_ID, "Illegal selection")); //$NON-NLS-1$
}
int offset = Integer.parseInt(selectStrings[0]);
int length = Integer.parseInt(selectStrings[1]);
return new TextSelection(offset, length);
}
protected ICProject getCProject() throws CoreException {
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(getProject());
ICProject cProject = CoreModel.getDefault().create(project);
if (cProject == null) {
throw new CoreException(new Status(IStatus.ERROR, CUIPlugin.PLUGIN_ID, "Unknown Project")); //$NON-NLS-1$
}
return cProject;
}
protected IFile getFile() throws CoreException {
try {
String filename = arguments.get(FILE_NAME);
return ResourceLookup.selectFileForLocationURI(new URI(filename),
ResourcesPlugin.getWorkspace().getRoot().getProject(getProject()));
} catch (URISyntaxException e) {
throw new CoreException(new Status(IStatus.ERROR, CUIPlugin.PLUGIN_ID, e.getMessage(), e));
}
}
}

View file

@ -55,11 +55,11 @@ public abstract class CRefactoringDescriptor extends RefactoringDescriptor {
} }
@Override @Override
public abstract CRefactoring2 createRefactoring(RefactoringStatus status) throws CoreException; public abstract CRefactoring createRefactoring(RefactoringStatus status) throws CoreException;
@Override @Override
public CRefactoringContext createRefactoringContext(RefactoringStatus status) throws CoreException { public CRefactoringContext createRefactoringContext(RefactoringStatus status) throws CoreException {
CRefactoring2 refactoring= createRefactoring(status); CRefactoring refactoring= createRefactoring(status);
if (refactoring == null) if (refactoring == null)
return null; return null;
return new CRefactoringContext(refactoring); return new CRefactoringContext(refactoring);

View file

@ -1,46 +1,48 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2008, 2009 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2011, 2012 Google, Inc 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 * which accompanies this distribution, and is available at
* which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html
* http://www.eclipse.org/legal/epl-v10.html *
* * Contributors:
* Contributors: * Sergey Prigogin (Google) - initial API and implementation
* Institute for Software - initial API and implementation *******************************************************************************/
*******************************************************************************/ package org.eclipse.cdt.internal.ui.refactoring;
package org.eclipse.cdt.internal.ui.refactoring;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.core.resources.IFile; import org.eclipse.jface.window.IShellProvider;
import org.eclipse.jface.viewers.ISelection; import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
import org.eclipse.jface.window.IShellProvider;
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;
/**
/** * Base class for all refactoring runners.
* Base class for all refactoring runners. */
* public abstract class RefactoringRunner {
* @deprecated Use RefactoringRunner2. protected final ISelection selection;
* protected final ICElement element;
* @author Emanuel Graf protected final ICProject project;
*/ protected final IShellProvider shellProvider;
@Deprecated
public abstract class RefactoringRunner { public RefactoringRunner(ICElement element, ISelection selection, IShellProvider shellProvider,
protected IFile file; ICProject cProject) {
protected ISelection selection; this.selection = selection;
protected ICElement celement; this.element= element;
protected IShellProvider shellProvider; this.project = cProject;
protected ICProject project; this.shellProvider= shellProvider;
}
public RefactoringRunner(IFile file, ISelection selection, ICElement element,
IShellProvider shellProvider, ICProject cProject) { public abstract void run();
this.file = file;
this.selection = selection; protected final void run(RefactoringWizard wizard, CRefactoring refactoring, int saveMode) {
this.celement= element; CRefactoringContext context = new CRefactoringContext(refactoring);
this.shellProvider= shellProvider; try {
this.project = cProject; RefactoringStarter starter = new RefactoringStarter();
} starter.activate(wizard, shellProvider.getShell(), refactoring.getName(), saveMode);
} finally {
public abstract void run(); context.dispose();
} }
}
}

View file

@ -1,49 +0,0 @@
/*******************************************************************************
* Copyright (c) 2011, 2012 Google, Inc 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:
* Sergey Prigogin (Google) - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
/**
* Base class for all refactoring runners. This class is intended as a replacement
* for RefactoringRunner.
*/
public abstract class RefactoringRunner2 {
protected final ISelection selection;
protected final ICElement element;
protected final ICProject project;
private final IShellProvider shellProvider;
public RefactoringRunner2(ICElement element, ISelection selection, IShellProvider shellProvider,
ICProject cProject) {
this.selection = selection;
this.element= element;
this.project = cProject;
this.shellProvider= shellProvider;
}
public abstract void run();
protected final void run(RefactoringWizard wizard, CRefactoring2 refactoring, int saveMode) {
CRefactoringContext context = new CRefactoringContext(refactoring);
try {
RefactoringStarter starter = new RefactoringStarter();
starter.activate(wizard, shellProvider.getShell(), refactoring.getName(), saveMode);
} finally {
context.dispose();
}
}
}

View file

@ -25,7 +25,7 @@ public class RefactoringStarter {
public boolean activate(RefactoringWizard wizard, Shell parent, String dialogTitle, int saveMode) { public boolean activate(RefactoringWizard wizard, Shell parent, String dialogTitle, int saveMode) {
RefactoringSaveHelper saveHelper= new RefactoringSaveHelper(saveMode); RefactoringSaveHelper saveHelper= new RefactoringSaveHelper(saveMode);
if (!canActivate(saveHelper, parent)) if (!saveHelper.saveEditors(parent))
return false; return false;
try { try {
@ -46,8 +46,4 @@ public class RefactoringStarter {
public RefactoringStatus getInitialConditionCheckingStatus() { public RefactoringStatus getInitialConditionCheckingStatus() {
return fStatus; return fStatus;
} }
private boolean canActivate(RefactoringSaveHelper saveHelper, Shell shell) {
return saveHelper.saveEditors(shell);
}
} }

View file

@ -66,13 +66,12 @@ 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.core.dom.parser.cpp.semantics.CPPVisitor;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor; 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.MethodContext; import org.eclipse.cdt.internal.ui.refactoring.MethodContext;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
import org.eclipse.cdt.internal.ui.refactoring.utils.NodeHelper; import org.eclipse.cdt.internal.ui.refactoring.utils.NodeHelper;
import org.eclipse.cdt.internal.ui.refactoring.utils.TranslationUnitHelper;
import org.eclipse.cdt.internal.ui.util.NameComposer; import org.eclipse.cdt.internal.ui.util.NameComposer;
/** /**
@ -80,7 +79,7 @@ import org.eclipse.cdt.internal.ui.util.NameComposer;
* *
* @author Mirko Stocker * @author Mirko Stocker
*/ */
public class ExtractConstantRefactoring extends CRefactoring2 { public class ExtractConstantRefactoring extends CRefactoring {
public static final String ID = public static final String ID =
"org.eclipse.cdt.ui.refactoring.extractconstant.ExtractConstantRefactoring"; //$NON-NLS-1$ "org.eclipse.cdt.ui.refactoring.extractconstant.ExtractConstantRefactoring"; //$NON-NLS-1$
@ -344,11 +343,27 @@ public class ExtractConstantRefactoring extends CRefactoring2 {
} else { } else {
IASTDeclaration nodes = getConstNodesGlobal(constName, ast.getASTNodeFactory()); IASTDeclaration nodes = getConstNodesGlobal(constName, ast.getASTNodeFactory());
ASTRewrite rewriter = collector.rewriterForTranslationUnit(ast); ASTRewrite rewriter = collector.rewriterForTranslationUnit(ast);
rewriter.insertBefore(ast, TranslationUnitHelper.getFirstNode(ast), nodes, rewriter.insertBefore(ast, getFirstNode(ast), nodes,
new TextEditGroup(Messages.ExtractConstantRefactoring_CreateConstant)); new TextEditGroup(Messages.ExtractConstantRefactoring_CreateConstant));
} }
} }
/**
* @return the first node in the translation unit or null
*/
private static IASTNode getFirstNode(IASTTranslationUnit ast) {
IASTDeclaration firstNode = null;
for (IASTDeclaration each : ast.getDeclarations()) {
if (firstNode == null) {
firstNode = each;
} else if (each.getNodeLocations() != null &&
each.getNodeLocations()[0].getNodeOffset() < firstNode.getNodeLocations()[0].getNodeOffset()) {
firstNode = each;
}
}
return firstNode;
}
@Override @Override
protected RefactoringDescriptor getRefactoringDescriptor() { protected RefactoringDescriptor getRefactoringDescriptor() {
Map<String, String> arguments = getArgumentMap(); Map<String, String> arguments = getArgumentMap();

View file

@ -21,7 +21,7 @@ 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.CRefactoring2; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor; import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor;
import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum; import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum;
@ -39,7 +39,7 @@ public class ExtractConstantRefactoringDescriptor extends CRefactoringDescriptor
} }
@Override @Override
public CRefactoring2 createRefactoring(RefactoringStatus status) public CRefactoring createRefactoring(RefactoringStatus status)
throws CoreException { throws CoreException {
ISelection selection = getSelection(); ISelection selection = getSelection();
ICProject project = getCProject(); ICProject project = getCProject();

View file

@ -18,13 +18,13 @@ import org.eclipse.jface.window.IShellProvider;
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.RefactoringRunner2; import org.eclipse.cdt.internal.ui.refactoring.RefactoringRunner;
import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper; import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper;
/** /**
* @author Emanuel Graf * @author Emanuel Graf
*/ */
public class ExtractConstantRefactoringRunner extends RefactoringRunner2 { public class ExtractConstantRefactoringRunner extends RefactoringRunner {
public ExtractConstantRefactoringRunner(ICElement element, ISelection selection, public ExtractConstantRefactoringRunner(ICElement element, ISelection selection,
IShellProvider shellProvider, ICProject cProject) { IShellProvider shellProvider, ICProject cProject) {

View file

@ -105,7 +105,7 @@ 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;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor; 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.Container; import org.eclipse.cdt.internal.ui.refactoring.Container;
@ -122,7 +122,7 @@ import org.eclipse.cdt.internal.ui.refactoring.utils.NodeHelper;
import org.eclipse.cdt.internal.ui.refactoring.utils.SelectionHelper; import org.eclipse.cdt.internal.ui.refactoring.utils.SelectionHelper;
import org.eclipse.cdt.internal.ui.viewsupport.BasicElementLabels; import org.eclipse.cdt.internal.ui.viewsupport.BasicElementLabels;
public class ExtractFunctionRefactoring extends CRefactoring2 { public class ExtractFunctionRefactoring extends CRefactoring {
public static final String ID = public static final String ID =
"org.eclipse.cdt.internal.ui.refactoring.extractfunction.ExtractFunctionRefactoring"; //$NON-NLS-1$ "org.eclipse.cdt.internal.ui.refactoring.extractfunction.ExtractFunctionRefactoring"; //$NON-NLS-1$

View file

@ -21,7 +21,7 @@ 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.CRefactoring2; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor; import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor;
import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum; import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum;
@ -40,7 +40,7 @@ public class ExtractFunctionRefactoringDescriptor extends CRefactoringDescriptor
} }
@Override @Override
public CRefactoring2 createRefactoring(RefactoringStatus status) throws CoreException { public CRefactoring createRefactoring(RefactoringStatus status) throws CoreException {
ISelection selection = getSelection(); ISelection selection = getSelection();
ICProject project = getCProject(); ICProject project = getCProject();
ExtractFunctionRefactoring refactoring = ExtractFunctionRefactoring refactoring =

View file

@ -18,13 +18,13 @@ import org.eclipse.jface.window.IShellProvider;
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.RefactoringRunner2; import org.eclipse.cdt.internal.ui.refactoring.RefactoringRunner;
import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper; import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper;
/** /**
* @author Emanuel Graf * @author Emanuel Graf
*/ */
public class ExtractFunctionRefactoringRunner extends RefactoringRunner2 { public class ExtractFunctionRefactoringRunner extends RefactoringRunner {
public ExtractFunctionRefactoringRunner(ICElement element, ISelection selection, public ExtractFunctionRefactoringRunner(ICElement element, ISelection selection,
IShellProvider shellProvider, ICProject cProject) { IShellProvider shellProvider, ICProject cProject) {

View file

@ -67,7 +67,7 @@ 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.core.dom.parser.cpp.semantics.CPPVisitor;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor; import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
import org.eclipse.cdt.internal.ui.refactoring.NodeContainer; import org.eclipse.cdt.internal.ui.refactoring.NodeContainer;
@ -83,7 +83,7 @@ import org.eclipse.cdt.internal.ui.util.NameComposer;
* *
* @author Tom Ball * @author Tom Ball
*/ */
public class ExtractLocalVariableRefactoring extends CRefactoring2 { public class ExtractLocalVariableRefactoring extends CRefactoring {
public static final String ID = public static final String ID =
"org.eclipse.cdt.internal.ui.refactoring.extractlocalvariable.ExtractLocalVariableRefactoring"; //$NON-NLS-1$ "org.eclipse.cdt.internal.ui.refactoring.extractlocalvariable.ExtractLocalVariableRefactoring"; //$NON-NLS-1$

View file

@ -21,7 +21,7 @@ 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.CRefactoring2; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor; import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor;
/** /**
@ -37,7 +37,7 @@ public class ExtractLocalVariableRefactoringDescriptor extends CRefactoringDescr
} }
@Override @Override
public CRefactoring2 createRefactoring(RefactoringStatus status) throws CoreException { public CRefactoring createRefactoring(RefactoringStatus status) throws CoreException {
ISelection selection = getSelection(); ISelection selection = getSelection();
ICProject proj = getCProject(); ICProject proj = getCProject();
ExtractLocalVariableRefactoring refactoring = ExtractLocalVariableRefactoring refactoring =

View file

@ -18,7 +18,7 @@ import org.eclipse.jface.window.IShellProvider;
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.RefactoringRunner2; import org.eclipse.cdt.internal.ui.refactoring.RefactoringRunner;
import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper; import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper;
/** /**
@ -26,7 +26,7 @@ import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper;
* *
* @author Tom Ball * @author Tom Ball
*/ */
public class ExtractLocalVariableRefactoringRunner extends RefactoringRunner2 { public class ExtractLocalVariableRefactoringRunner extends RefactoringRunner {
public ExtractLocalVariableRefactoringRunner(ICElement element, ISelection selection, public ExtractLocalVariableRefactoringRunner(ICElement element, ISelection selection,
IShellProvider shellProvider, ICProject cProject) { IShellProvider shellProvider, ICProject cProject) {

View file

@ -46,7 +46,7 @@ import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.internal.core.dom.rewrite.astwriter.ContainerNode; import org.eclipse.cdt.internal.core.dom.rewrite.astwriter.ContainerNode;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.ClassMemberInserter; import org.eclipse.cdt.internal.ui.refactoring.ClassMemberInserter;
import org.eclipse.cdt.internal.ui.refactoring.Container; import org.eclipse.cdt.internal.ui.refactoring.Container;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
@ -59,7 +59,7 @@ import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum;
/** /**
* @author Thomas Corbat * @author Thomas Corbat
*/ */
public class GenerateGettersAndSettersRefactoring extends CRefactoring2 { public class GenerateGettersAndSettersRefactoring extends CRefactoring {
private final class CompositeTypeSpecFinder extends ASTVisitor { private final class CompositeTypeSpecFinder extends ASTVisitor {
private final int start; private final int start;

View file

@ -22,13 +22,13 @@ import org.eclipse.ui.texteditor.ITextEditor;
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.RefactoringRunner2; import org.eclipse.cdt.internal.ui.refactoring.RefactoringRunner;
import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper; import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper;
/** /**
* @author Thomas Corbat * @author Thomas Corbat
*/ */
public class GenerateGettersAndSettersRefactoringRunner extends RefactoringRunner2 { public class GenerateGettersAndSettersRefactoringRunner extends RefactoringRunner {
public GenerateGettersAndSettersRefactoringRunner(ICElement element, ISelection selection, public GenerateGettersAndSettersRefactoringRunner(ICElement element, ISelection selection,
IShellProvider shellProvider, ICProject cProject) { IShellProvider shellProvider, ICProject cProject) {

View file

@ -60,7 +60,7 @@ 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;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor; 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.ModificationCollector; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
@ -72,7 +72,7 @@ import org.eclipse.cdt.internal.ui.util.EditorUtility;
/** /**
* @author Guido Zgraggen IFS * @author Guido Zgraggen IFS
*/ */
public class HideMethodRefactoring extends CRefactoring2 { public class HideMethodRefactoring extends CRefactoring {
public static final String ID = "org.eclipse.cdt.internal.ui.refactoring.hidemethod.HideMethodRefactoring"; //$NON-NLS-1$ public static final String ID = "org.eclipse.cdt.internal.ui.refactoring.hidemethod.HideMethodRefactoring"; //$NON-NLS-1$
private IASTName methodName; private IASTName methodName;

View file

@ -21,7 +21,7 @@ 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.CRefactoring2; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor; import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor;
/** /**
@ -35,7 +35,7 @@ public class HideMethodRefactoringDescriptor extends CRefactoringDescriptor {
} }
@Override @Override
public CRefactoring2 createRefactoring(RefactoringStatus status) throws CoreException { public CRefactoring createRefactoring(RefactoringStatus status) throws CoreException {
ISelection selection = getSelection(); ISelection selection = getSelection();
ICProject proj = getCProject(); ICProject proj = getCProject();
return new HideMethodRefactoring(getTranslationUnit(), selection, proj); return new HideMethodRefactoring(getTranslationUnit(), selection, proj);

View file

@ -18,13 +18,13 @@ import org.eclipse.jface.window.IShellProvider;
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.RefactoringRunner2; import org.eclipse.cdt.internal.ui.refactoring.RefactoringRunner;
import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper; import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper;
/** /**
* @author Guido Zgraggen IFS * @author Guido Zgraggen IFS
*/ */
public class HideMethodRefactoringRunner extends RefactoringRunner2 { public class HideMethodRefactoringRunner extends RefactoringRunner {
public HideMethodRefactoringRunner(ICElement element, ISelection selection, public HideMethodRefactoringRunner(ICElement element, ISelection selection,
IShellProvider shellProvider, ICProject cProject) { IShellProvider shellProvider, ICProject cProject) {

View file

@ -60,7 +60,7 @@ import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor; import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
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;
import org.eclipse.cdt.internal.ui.refactoring.utils.NameHelper; import org.eclipse.cdt.internal.ui.refactoring.utils.NameHelper;
@ -73,7 +73,7 @@ import org.eclipse.cdt.internal.ui.refactoring.utils.SelectionHelper;
* *
* @author Mirko Stocker, Lukas Felber, Emanuel Graf * @author Mirko Stocker, Lukas Felber, Emanuel Graf
*/ */
public class ImplementMethodRefactoring extends CRefactoring2 { public class ImplementMethodRefactoring extends CRefactoring {
private ICPPASTFunctionDeclarator createdMethodDeclarator; private ICPPASTFunctionDeclarator createdMethodDeclarator;
private ImplementMethodData data; private ImplementMethodData data;
private MethodDefinitionInsertLocationFinder methodDefinitionInsertLocationFinder; private MethodDefinitionInsertLocationFinder methodDefinitionInsertLocationFinder;

View file

@ -19,13 +19,13 @@ import org.eclipse.jface.window.IShellProvider;
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.RefactoringRunner2; import org.eclipse.cdt.internal.ui.refactoring.RefactoringRunner;
import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper; import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper;
/** /**
* @author Lukas Felber * @author Lukas Felber
*/ */
public class ImplementMethodRefactoringRunner extends RefactoringRunner2 { public class ImplementMethodRefactoringRunner extends RefactoringRunner {
public ImplementMethodRefactoringRunner(ICElement element, ISelection selection, public ImplementMethodRefactoringRunner(ICElement element, ISelection selection,
IShellProvider shellProvider, ICProject cProject) { IShellProvider shellProvider, ICProject cProject) {

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2011 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2011, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others. * Rapperswil, University of applied sciences and others.
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -7,12 +7,15 @@
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* Contributors: * Contributors:
* Martin Schwab & Thomas Kallenberg - initial API and implementation * Martin Schwab & Thomas Kallenberg - initial API and implementation
* Sergey Prigogin (Google)
******************************************************************************/ ******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.togglefunction; package org.eclipse.cdt.internal.ui.refactoring.togglefunction;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
public interface IToggleRefactoringStrategy { public interface IToggleRefactoringStrategy {
public void run(ModificationCollector modifications); public void run(ModificationCollector modifications) throws CoreException;
} }

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2011 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2011, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others. * Rapperswil, University of applied sciences and others.
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -7,7 +7,8 @@
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* Contributors: * Contributors:
* Emanuel Graf IFS - initial API and implementation * Emanuel Graf IFS - initial API and implementation
* Sergey Prigogin (Google)
******************************************************************************/ ******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.togglefunction; package org.eclipse.cdt.internal.ui.refactoring.togglefunction;
@ -18,12 +19,10 @@ public class Messages extends NLS {
public static String DeclaratorFinder_NoDeclarator; public static String DeclaratorFinder_NoDeclarator;
public static String DeclaratorFinder_MultipleDeclarators; public static String DeclaratorFinder_MultipleDeclarators;
public static String RefactoringJob_UndoName; public static String RefactoringJob_UndoName;
public static String ToggleFileCreator_andMove;
public static String ToggleFileCreator_CanNotCreateNewFile; public static String ToggleFileCreator_CanNotCreateNewFile;
public static String ToggleFileCreator_CreateNewFile; public static String ToggleFileCreator_CreateNewFilePrompt;
public static String ToggleFileCreator_NewImplFile; public static String ToggleFileCreator_NewImplFile;
public static String ToggleFileCreator_NoTuForSibling; public static String ToggleFileCreator_NoTuForSibling;
public static String ToggleFileCreator_QMark;
public static String ToggleFromClassToInHeaderStrategy_DefAndDecInsideClass; public static String ToggleFromClassToInHeaderStrategy_DefAndDecInsideClass;
public static String EditGroupName; public static String EditGroupName;
public static String ToggleFromImplementationToHeaderOrClassStrategy_CanNotCreateNewFile; public static String ToggleFromImplementationToHeaderOrClassStrategy_CanNotCreateNewFile;

View file

@ -7,18 +7,17 @@
# http://www.eclipse.org/legal/epl-v10.html # http://www.eclipse.org/legal/epl-v10.html
# #
# Contributors: # Contributors:
# Martin Schwab & Thomas Kallenberg - initial API and implementation # Martin Schwab & Thomas Kallenberg - initial API and implementation
# Sergey Prigogin (Google)
############################################################################### ###############################################################################
DeclaratorFinder_NestedFunction=Nested function declarations not supported DeclaratorFinder_NestedFunction=Nested function declarations not supported
DeclaratorFinder_NoDeclarator=Cannot work without declarator DeclaratorFinder_NoDeclarator=Cannot work without declarator
DeclaratorFinder_MultipleDeclarators=Cannot work with multiple declarators DeclaratorFinder_MultipleDeclarators=Cannot work with multiple declarators
RefactoringJob_UndoName=Toggle function definition RefactoringJob_UndoName=Toggle function definition
ToggleFileCreator_andMove=\ and move ToggleFileCreator_CanNotCreateNewFile=Cannot create new file ''{0}''
ToggleFileCreator_CanNotCreateNewFile=Cannot create new file change ToggleFileCreator_CreateNewFilePrompt=Create a new file ''{0}'' and move {1}?
ToggleFileCreator_CreateNewFile=Create a new file named:
ToggleFileCreator_NewImplFile=New Implementation file? ToggleFileCreator_NewImplFile=New Implementation file?
ToggleFileCreator_NoTuForSibling=Cannot find translation unit for sibling file ToggleFileCreator_NoTuForSibling=Cannot find translation unit for sibling file
ToggleFileCreator_QMark=?
ToggleFromClassToInHeaderStrategy_DefAndDecInsideClass=Definition and Declaration both inside class. Behavior is undefined. ToggleFromClassToInHeaderStrategy_DefAndDecInsideClass=Definition and Declaration both inside class. Behavior is undefined.
ToggleFromImplementationToHeaderOrClassStrategy_CanNotCreateNewFile=Cannot create new File ToggleFromImplementationToHeaderOrClassStrategy_CanNotCreateNewFile=Cannot create new File
ToggleFromImplementationToHeaderOrClassStrategy_CanNotToggle=Not a free function. Cannot decide where to toggle ToggleFromImplementationToHeaderOrClassStrategy_CanNotToggle=Not a free function. Cannot decide where to toggle

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2011 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2011, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others * Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -7,7 +7,8 @@
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* 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.togglefunction; package org.eclipse.cdt.internal.ui.refactoring.togglefunction;
@ -20,18 +21,19 @@ import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.ltk.core.refactoring.Change; import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.IUndoManager; import org.eclipse.ltk.core.refactoring.IUndoManager;
import org.eclipse.ltk.core.refactoring.NullChange; import org.eclipse.ltk.core.refactoring.NullChange;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.core.refactoring.RefactoringCore; import org.eclipse.ltk.core.refactoring.RefactoringCore;
import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringContext;
class RefactoringJob extends Job { class RefactoringJob extends Job {
public final static Object FAMILY_TOGGLE_DEFINITION = new Object(); public final static Object FAMILY_TOGGLE_DEFINITION = new Object();
private final Refactoring refactoring; private final ToggleRefactoring refactoring;
RefactoringJob(Refactoring refactoring) { RefactoringJob(ToggleRefactoring refactoring) {
super("'toggle function definition' code automation"); //$NON-NLS-1$ super("Toggle Function Definition code automation"); //$NON-NLS-1$
this.refactoring = refactoring; this.refactoring = refactoring;
setPriority(Job.SHORT); setPriority(Job.SHORT);
} }
@ -43,6 +45,7 @@ class RefactoringJob extends Job {
@Override @Override
protected IStatus run(IProgressMonitor monitor) { protected IStatus run(IProgressMonitor monitor) {
CRefactoringContext context = new CRefactoringContext(refactoring);
IUndoManager undoManager = RefactoringCore.getUndoManager(); IUndoManager undoManager = RefactoringCore.getUndoManager();
Change change = new NullChange(); Change change = new NullChange();
Change undoChange = new NullChange(); Change undoChange = new NullChange();
@ -64,6 +67,7 @@ class RefactoringJob extends Job {
} catch (CoreException e) { } catch (CoreException e) {
CUIPlugin.log("Failure during generation of changes.", e); //$NON-NLS-1$ CUIPlugin.log("Failure during generation of changes.", e); //$NON-NLS-1$
} finally { } finally {
context.dispose();
undoChange.initializeValidationData(monitor); undoChange.initializeValidationData(monitor);
undoManager.changePerformed(change, success); undoManager.changePerformed(change, success);
try { try {

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2011 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2011, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others. * Rapperswil, University of applied sciences and others.
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -7,25 +7,27 @@
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* Contributors: * Contributors:
* Martin Schwab & Thomas Kallenberg - initial API and implementation * Martin Schwab & Thomas Kallenberg - initial API and implementation
* Sergey Prigogin (Google)
******************************************************************************/ ******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.togglefunction; package org.eclipse.cdt.internal.ui.refactoring.togglefunction;
import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI; import org.eclipse.ui.PlatformUI;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.model.CModelException; import org.eclipse.cdt.core.model.CModelException;
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.ui.CUIPlugin; import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.refactoring.Container;
import org.eclipse.cdt.internal.ui.refactoring.CreateFileChange; import org.eclipse.cdt.internal.ui.refactoring.CreateFileChange;
public class ToggleFileCreator { public class ToggleFileCreator {
@ -38,8 +40,8 @@ public class ToggleFileCreator {
this.context = context; this.context = context;
this.ending = ending; this.ending = ending;
} }
public IASTTranslationUnit loadTranslationUnit() { public ITranslationUnit getTranslationUnit() {
String filename; String filename;
if (context.getDeclaration() != null) { if (context.getDeclaration() != null) {
filename = context.getDeclaration().getContainingFilename(); filename = context.getDeclaration().getContainingFilename();
@ -54,11 +56,10 @@ public class ToggleFileCreator {
} }
filename = filename.replaceAll("\\w*" + other + "$", EMPTY_STRING) + getNewFileName(); //$NON-NLS-1$//$NON-NLS-2$ filename = filename.replaceAll("\\w*" + other + "$", EMPTY_STRING) + getNewFileName(); //$NON-NLS-1$//$NON-NLS-2$
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(filename)); IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(filename));
IASTTranslationUnit result = null; ITranslationUnit result = null;
try { try {
result = CoreModelUtil.findTranslationUnitForLocation(file.getFullPath(), null).getAST(); result = CoreModelUtil.findTranslationUnitForLocation(file.getFullPath(), null);
} catch (CModelException e) { } catch (CModelException e) {
} catch (CoreException e) {
} }
if (result == null) { if (result == null) {
throw new NotSupportedException(Messages.ToggleFileCreator_NoTuForSibling); throw new NotSupportedException(Messages.ToggleFileCreator_NoTuForSibling);
@ -66,14 +67,17 @@ public class ToggleFileCreator {
return result; return result;
} }
public void createNewFile() { public IFile createNewFile() {
String filename = getNewFileName(); String filename = getNewFileName();
IPath path = new Path(getPath() + filename);
try { try {
CreateFileChange change = new CreateFileChange(filename, new Path(getPath() + filename), CreateFileChange change = new CreateFileChange(filename, path, EMPTY_STRING,
EMPTY_STRING, context.getSelectionFile().getCharset()); context.getSelectionFile().getCharset());
change.perform(new NullProgressMonitor()); change.perform(new NullProgressMonitor());
return (IFile) change.getModifiedElement();
} catch (CoreException e) { } catch (CoreException e) {
throw new NotSupportedException(Messages.ToggleFileCreator_CanNotCreateNewFile); throw new NotSupportedException(NLS.bind(Messages.ToggleFileCreator_CanNotCreateNewFile,
path.toString()));
} }
} }
@ -81,24 +85,23 @@ public class ToggleFileCreator {
if (context.isSettedDefaultAnswer()) { if (context.isSettedDefaultAnswer()) {
return context.getDefaultAnswer(); return context.getDefaultAnswer();
} }
final Container<Boolean> answer = new Container<Boolean>(); final boolean[] answer = new boolean[1];
Runnable r = new Runnable() { Runnable r = new Runnable() {
@Override @Override
public void run() { public void run() {
Shell shell = CUIPlugin.getDefault().getWorkbench().getWorkbenchWindows()[0].getShell(); Shell shell = CUIPlugin.getDefault().getWorkbench().getWorkbenchWindows()[0].getShell();
String functionname; String functionName;
if (context.getDeclaration() != null) { if (context.getDeclaration() != null) {
functionname = context.getDeclaration().getRawSignature(); functionName = context.getDeclaration().getRawSignature();
} else { } else {
functionname = context.getDefinition().getDeclarator().getRawSignature(); functionName = context.getDefinition().getDeclarator().getRawSignature();
} }
boolean createnew = MessageDialog.openQuestion(shell, Messages.ToggleFileCreator_NewImplFile, answer[0] = MessageDialog.openQuestion(shell, Messages.ToggleFileCreator_NewImplFile,
Messages.ToggleFileCreator_CreateNewFile + getNewFileName() + Messages.ToggleFileCreator_andMove + functionname + Messages.ToggleFileCreator_QMark); NLS.bind(Messages.ToggleFileCreator_CreateNewFilePrompt, getNewFileName(), functionName));
answer.setObject(createnew);
} }
}; };
PlatformUI.getWorkbench().getDisplay().syncExec(r); PlatformUI.getWorkbench().getDisplay().syncExec(r);
return answer.getObject(); return answer[0];
} }
public String getIncludeStatement() { public String getIncludeStatement() {

View file

@ -7,7 +7,7 @@
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* Contributors: * Contributors:
* Martin Schwab & Thomas Kallenberg - initial API and implementation * Martin Schwab & Thomas Kallenberg - initial API and implementation
******************************************************************************/ ******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.togglefunction; package org.eclipse.cdt.internal.ui.refactoring.togglefunction;
@ -33,7 +33,6 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
public class ToggleFromClassToInHeaderStrategy implements IToggleRefactoringStrategy { public class ToggleFromClassToInHeaderStrategy implements IToggleRefactoringStrategy {
protected TextEditGroup infoText = new TextEditGroup(Messages.EditGroupName); protected TextEditGroup infoText = new TextEditGroup(Messages.EditGroupName);
private ToggleRefactoringContext context; private ToggleRefactoringContext context;
@ -61,7 +60,7 @@ public class ToggleFromClassToInHeaderStrategy implements IToggleRefactoringStra
private IASTNode getNewDefinition(IASTNode parentNamespace) { private IASTNode getNewDefinition(IASTNode parentNamespace) {
IASTNode newDefinition = ToggleNodeHelper.getQualifiedNameDefinition( IASTNode newDefinition = ToggleNodeHelper.getQualifiedNameDefinition(
context.getDefinition(), context.getDefinitionUnit(), parentNamespace); context.getDefinition(), context.getDefinitionAST(), parentNamespace);
((IASTFunctionDefinition) newDefinition).setBody( ((IASTFunctionDefinition) newDefinition).setBody(
context.getDefinition().getBody().copy(CopyStyle.withLocations)); context.getDefinition().getBody().copy(CopyStyle.withLocations));
if (newDefinition instanceof ICPPASTFunctionWithTryBlock) { if (newDefinition instanceof ICPPASTFunctionWithTryBlock) {
@ -76,7 +75,7 @@ public class ToggleFromClassToInHeaderStrategy implements IToggleRefactoringStra
if (templdecl != null) { if (templdecl != null) {
newDefinition = templdecl; newDefinition = templdecl;
} }
newDefinition.setParent(context.getDefinitionUnit()); newDefinition.setParent(context.getDefinitionAST());
return newDefinition; return newDefinition;
} }
@ -84,7 +83,7 @@ public class ToggleFromClassToInHeaderStrategy implements IToggleRefactoringStra
IASTNode parentNamespace = IASTNode parentNamespace =
CPPVisitor.findAncestorWithType(context.getDefinition(), ICPPASTNamespaceDefinition.class); CPPVisitor.findAncestorWithType(context.getDefinition(), ICPPASTNamespaceDefinition.class);
if (parentNamespace == null) if (parentNamespace == null)
parentNamespace = context.getDefinitionUnit(); parentNamespace = context.getDefinitionAST();
return parentNamespace; return parentNamespace;
} }
@ -99,13 +98,13 @@ public class ToggleFromClassToInHeaderStrategy implements IToggleRefactoringStra
ModificationCollector modifications, ModificationCollector modifications,
IASTSimpleDeclaration newDeclaration) { IASTSimpleDeclaration newDeclaration) {
ASTRewrite rewriter = modifications.rewriterForTranslationUnit( ASTRewrite rewriter = modifications.rewriterForTranslationUnit(
context.getDefinitionUnit()); context.getDefinitionAST());
rewriter.replace(context.getDefinition(), newDeclaration, infoText); rewriter.replace(context.getDefinition(), newDeclaration, infoText);
return rewriter; return rewriter;
} }
private IASTSimpleDeclaration getNewDeclaration() { private IASTSimpleDeclaration getNewDeclaration() {
INodeFactory factory = context.getDefinitionUnit().getASTNodeFactory(); INodeFactory factory = context.getDefinitionAST().getASTNodeFactory();
IASTDeclSpecifier newDeclSpecifier = IASTDeclSpecifier newDeclSpecifier =
context.getDefinition().getDeclSpecifier().copy(CopyStyle.withLocations); context.getDefinition().getDeclSpecifier().copy(CopyStyle.withLocations);
newDeclSpecifier.setInline(false); newDeclSpecifier.setInline(false);

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2011 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2011, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others. * Rapperswil, University of applied sciences and others.
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -7,12 +7,15 @@
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* Contributors: * Contributors:
* Martin Schwab & Thomas Kallenberg - initial API and implementation * Martin Schwab & Thomas Kallenberg - initial API and implementation
* Sergey Prigogin (Google)
******************************************************************************/ ******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.togglefunction; package org.eclipse.cdt.internal.ui.refactoring.togglefunction;
import java.util.List; import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.text.edits.TextEditGroup; import org.eclipse.text.edits.TextEditGroup;
import org.eclipse.cdt.core.dom.ast.IASTComment; import org.eclipse.cdt.core.dom.ast.IASTComment;
@ -37,8 +40,8 @@ import org.eclipse.cdt.internal.ui.refactoring.utils.CPPASTAllVisitor;
public class ToggleFromImplementationToHeaderOrClassStrategy implements IToggleRefactoringStrategy { public class ToggleFromImplementationToHeaderOrClassStrategy implements IToggleRefactoringStrategy {
private ToggleRefactoringContext context; private ToggleRefactoringContext context;
private TextEditGroup infoText; private TextEditGroup infoText;
private IASTTranslationUnit other_tu; private IASTTranslationUnit otherAst;
private ASTLiteralNode includenode; private ASTLiteralNode includeNode;
public ToggleFromImplementationToHeaderOrClassStrategy(ToggleRefactoringContext context) { public ToggleFromImplementationToHeaderOrClassStrategy(ToggleRefactoringContext context) {
this.context = context; this.context = context;
@ -50,34 +53,34 @@ public class ToggleFromImplementationToHeaderOrClassStrategy implements IToggleR
} }
@Override @Override
public void run(ModificationCollector modifications) { public void run(ModificationCollector modifications) throws CoreException {
newFileCheck(); newFileCheck();
ASTRewrite implast = modifications.rewriterForTranslationUnit(context.getDefinitionUnit()); ASTRewrite implAst = modifications.rewriterForTranslationUnit(context.getDefinitionAST());
List<IASTComment>leadingComments = implast.getComments(context.getDefinition(), CommentPosition.leading); List<IASTComment>leadingComments = implAst.getComments(context.getDefinition(), CommentPosition.leading);
removeDefinitionFromImplementation(implast); removeDefinitionFromImplementation(implAst);
if (includenode != null) { if (includeNode != null) {
implast.insertBefore(context.getDefinitionUnit(), implAst.insertBefore(context.getDefinitionAST(),
context.getDefinitionUnit().getChildren()[0], includenode, infoText); context.getDefinitionAST().getChildren()[0], includeNode, infoText);
} }
if (context.getDeclarationUnit() != null) { if (context.getDeclarationAST() != null) {
addDefinitionToClass(modifications, leadingComments); addDefinitionToClass(modifications, leadingComments);
} else { } else {
addDefinitionToHeader(modifications, leadingComments); addDefinitionToHeader(modifications, leadingComments);
} }
} }
private void newFileCheck() { private void newFileCheck() throws CoreException {
if (context.getDeclarationUnit() == null) { if (context.getDeclarationAST() == null) {
if (isFreeFunction(context.getDefinition())) { if (isFreeFunction(context.getDefinition())) {
throw new NotSupportedException(Messages.ToggleFromImplementationToHeaderOrClassStrategy_CanNotToggle); throw new NotSupportedException(Messages.ToggleFromImplementationToHeaderOrClassStrategy_CanNotToggle);
} }
other_tu = context.getTUForSiblingFile(); otherAst = context.getASTForPartnerFile();
if (other_tu == null) { if (otherAst == null) {
ToggleFileCreator filecreator = new ToggleFileCreator(context, ".h"); //$NON-NLS-1$ ToggleFileCreator fileCreator = new ToggleFileCreator(context, ".h"); //$NON-NLS-1$
if (filecreator.askUserForFileCreation(context)) { if (fileCreator.askUserForFileCreation(context)) {
filecreator.createNewFile(); IFile file = fileCreator.createNewFile();
other_tu = filecreator.loadTranslationUnit(); otherAst = context.getAST(file, null);
includenode = new ASTLiteralNode(filecreator.getIncludeStatement() + "\n\n"); //$NON-NLS-1$ includeNode = new ASTLiteralNode(fileCreator.getIncludeStatement() + "\n\n"); //$NON-NLS-1$
} else { } else {
throw new NotSupportedException(Messages.ToggleFromImplementationToHeaderOrClassStrategy_CanNotCreateNewFile); throw new NotSupportedException(Messages.ToggleFromImplementationToHeaderOrClassStrategy_CanNotCreateNewFile);
} }
@ -86,13 +89,13 @@ public class ToggleFromImplementationToHeaderOrClassStrategy implements IToggleR
} }
private void addDefinitionToHeader(ModificationCollector modifications, List<IASTComment> leadingComments) { private void addDefinitionToHeader(ModificationCollector modifications, List<IASTComment> leadingComments) {
ASTRewrite headerRewrite = modifications.rewriterForTranslationUnit(other_tu); ASTRewrite headerRewrite = modifications.rewriterForTranslationUnit(otherAst);
IASTFunctionDefinition newDefinition = ToggleNodeHelper.createFunctionSignatureWithEmptyBody( IASTFunctionDefinition newDefinition = ToggleNodeHelper.createFunctionSignatureWithEmptyBody(
context.getDefinition().getDeclSpecifier().copy(CopyStyle.withLocations), context.getDefinition().getDeclSpecifier().copy(CopyStyle.withLocations),
context.getDefinition().getDeclarator().copy(CopyStyle.withLocations), context.getDefinition().getDeclarator().copy(CopyStyle.withLocations),
context.getDefinition().copy(CopyStyle.withLocations)); context.getDefinition().copy(CopyStyle.withLocations));
newDefinition.setParent(other_tu); newDefinition.setParent(otherAst);
headerRewrite.insertBefore(other_tu.getTranslationUnit(), null, newDefinition, infoText); headerRewrite.insertBefore(otherAst.getTranslationUnit(), null, newDefinition, infoText);
restoreBody(headerRewrite, newDefinition, modifications); restoreBody(headerRewrite, newDefinition, modifications);
for (IASTComment comment : leadingComments) { for (IASTComment comment : leadingComments) {
headerRewrite.addComment(newDefinition, comment, CommentPosition.leading); headerRewrite.addComment(newDefinition, comment, CommentPosition.leading);
@ -101,9 +104,9 @@ public class ToggleFromImplementationToHeaderOrClassStrategy implements IToggleR
private void addDefinitionToClass(ModificationCollector modifications, List<IASTComment> leadingComments) { private void addDefinitionToClass(ModificationCollector modifications, List<IASTComment> leadingComments) {
ASTRewrite headerRewrite = modifications.rewriterForTranslationUnit( ASTRewrite headerRewrite = modifications.rewriterForTranslationUnit(
context.getDeclarationUnit()); context.getDeclarationAST());
IASTFunctionDefinition newDefinition = ToggleNodeHelper.createInClassDefinition( IASTFunctionDefinition newDefinition = ToggleNodeHelper.createInClassDefinition(
context.getDeclaration(), context.getDefinition(), context.getDeclarationUnit()); context.getDeclaration(), context.getDefinition(), context.getDeclarationAST());
newDefinition.setParent(getParent()); newDefinition.setParent(getParent());
restoreBody(headerRewrite, newDefinition, modifications); restoreBody(headerRewrite, newDefinition, modifications);
headerRewrite.replace(context.getDeclaration().getParent(), newDefinition, infoText); headerRewrite.replace(context.getDeclaration().getParent(), newDefinition, infoText);
@ -119,7 +122,7 @@ public class ToggleFromImplementationToHeaderOrClassStrategy implements IToggleR
if (parent != null) { if (parent != null) {
parentnode = parent; parentnode = parent;
} else { } else {
parentnode =context.getDeclarationUnit(); parentnode =context.getDeclarationAST();
} }
return parentnode; return parentnode;
} }

View file

@ -36,7 +36,6 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
public class ToggleFromInHeaderToClassStrategy implements IToggleRefactoringStrategy { public class ToggleFromInHeaderToClassStrategy implements IToggleRefactoringStrategy {
private TextEditGroup infoText; private TextEditGroup infoText;
private ToggleRefactoringContext context; private ToggleRefactoringContext context;
@ -67,8 +66,7 @@ public class ToggleFromInHeaderToClassStrategy implements IToggleRefactoringStra
IASTNode parentTemplateDeclaration = IASTNode parentTemplateDeclaration =
ToggleNodeHelper.getParentTemplateDeclaration(context.getDeclaration()); ToggleNodeHelper.getParentTemplateDeclaration(context.getDeclaration());
if (parentTemplateDeclaration instanceof ICPPASTTemplateDeclaration) { if (!(parentTemplateDeclaration instanceof ICPPASTTemplateDeclaration)) {
} else {
restoreLeadingComments(rewriter, newDefinition); restoreLeadingComments(rewriter, newDefinition);
} }
} }
@ -84,7 +82,7 @@ public class ToggleFromInHeaderToClassStrategy implements IToggleRefactoringStra
} }
private ASTRewrite removeDefinition(ModificationCollector modifications) { private ASTRewrite removeDefinition(ModificationCollector modifications) {
ASTRewrite rewriter = modifications.rewriterForTranslationUnit(context.getDefinitionUnit()); ASTRewrite rewriter = modifications.rewriterForTranslationUnit(context.getDefinitionAST());
IASTNode parentRemovePoint = ToggleNodeHelper.getParentRemovePoint(context.getDefinition()); IASTNode parentRemovePoint = ToggleNodeHelper.getParentRemovePoint(context.getDefinition());
rewriter.remove(parentRemovePoint, infoText); rewriter.remove(parentRemovePoint, infoText);
return rewriter; return rewriter;
@ -92,7 +90,7 @@ public class ToggleFromInHeaderToClassStrategy implements IToggleRefactoringStra
private IASTFunctionDefinition getNewDefinition() { private IASTFunctionDefinition getNewDefinition() {
IASTFunctionDefinition newDefinition = ToggleNodeHelper.createInClassDefinition( IASTFunctionDefinition newDefinition = ToggleNodeHelper.createInClassDefinition(
context.getDeclaration(), context.getDefinition(), context.getDefinitionUnit()); context.getDeclaration(), context.getDefinition(), context.getDefinitionAST());
newDefinition.setBody(context.getDefinition().getBody().copy(CopyStyle.withLocations)); newDefinition.setBody(context.getDefinition().getBody().copy(CopyStyle.withLocations));
if (newDefinition instanceof ICPPASTFunctionWithTryBlock) { if (newDefinition instanceof ICPPASTFunctionWithTryBlock) {
ICPPASTFunctionWithTryBlock newTryFun = (ICPPASTFunctionWithTryBlock) newDefinition; ICPPASTFunctionWithTryBlock newTryFun = (ICPPASTFunctionWithTryBlock) newDefinition;
@ -105,9 +103,8 @@ public class ToggleFromInHeaderToClassStrategy implements IToggleRefactoringStra
IASTNode parent = CPPVisitor.findAncestorWithType(context.getDefinition(), ICPPASTCompositeTypeSpecifier.class); IASTNode parent = CPPVisitor.findAncestorWithType(context.getDefinition(), ICPPASTCompositeTypeSpecifier.class);
if (parent != null) { if (parent != null) {
newDefinition.setParent(parent); newDefinition.setParent(parent);
} } else {
else { newDefinition.setParent(context.getDefinitionAST());
newDefinition.setParent(context.getDefinitionUnit());
} }
return newDefinition; return newDefinition;
} }

View file

@ -14,6 +14,8 @@ package org.eclipse.cdt.internal.ui.refactoring.togglefunction;
import java.util.List; import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
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;
@ -58,7 +60,7 @@ import org.eclipse.cdt.internal.ui.refactoring.Container;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefactoringStrategy { public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefactoringStrategy {
private IASTTranslationUnit implUnit; private IASTTranslationUnit implAst;
private ToggleRefactoringContext context; private ToggleRefactoringContext context;
private TextEditGroup infoText; private TextEditGroup infoText;
private ASTLiteralNode includeNode; private ASTLiteralNode includeNode;
@ -69,11 +71,10 @@ public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefact
} }
@Override @Override
public void run(ModificationCollector collector) { public void run(ModificationCollector collector) throws CoreException {
if (!newFileCheck()) { if (!newFileCheck()) {
return; return;
} }
// newFileCheck();
ICPPASTFunctionDefinition newDefinition = getNewDefinition(); ICPPASTFunctionDefinition newDefinition = getNewDefinition();
if (context.getDeclaration() != null) { if (context.getDeclaration() != null) {
removeDefinitionFromHeader(collector); removeDefinitionFromHeader(collector);
@ -81,9 +82,9 @@ public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefact
replaceDefinitionWithDeclaration(collector); replaceDefinitionWithDeclaration(collector);
} }
ASTRewrite implRewrite = collector.rewriterForTranslationUnit(implUnit); ASTRewrite implRewrite = collector.rewriterForTranslationUnit(implAst);
if (includeNode != null) { if (includeNode != null) {
implRewrite.insertBefore(implUnit, null, includeNode, infoText); implRewrite.insertBefore(implAst, null, includeNode, infoText);
} }
IASTNode insertionParent = null; IASTNode insertionParent = null;
@ -94,20 +95,20 @@ public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefact
insertionParent = searchNamespaceInImplementation(parent.getName()); insertionParent = searchNamespaceInImplementation(parent.getName());
if (insertionParent == null) { if (insertionParent == null) {
insertionParent = createNamespace(parent); insertionParent = createNamespace(parent);
implRewrite = implRewrite.insertBefore(implUnit.getTranslationUnit(), implRewrite = implRewrite.insertBefore(implAst.getTranslationUnit(),
null, insertionParent, infoText); null, insertionParent, infoText);
} }
} else { } else {
insertionParent = implUnit.getTranslationUnit(); insertionParent = implAst.getTranslationUnit();
} }
newDefinition.setParent(insertionParent); newDefinition.setParent(insertionParent);
IASTNode insertionPoint = findInsertionPoint(insertionParent, IASTNode insertionPoint = findInsertionPoint(insertionParent,
context.getDeclarationUnit()); context.getDeclarationAST());
ASTRewrite newRewriter = implRewrite.insertBefore(insertionParent, ASTRewrite newRewriter = implRewrite.insertBefore(insertionParent,
insertionPoint, newDefinition, infoText); insertionPoint, newDefinition, infoText);
copyCommentsToNewFile(newDefinition, newRewriter, collector.rewriterForTranslationUnit(context.getDefinitionUnit())); copyCommentsToNewFile(newDefinition, newRewriter, collector.rewriterForTranslationUnit(context.getDefinitionAST()));
restoreLeadingComments(newDefinition, newRewriter, collector); restoreLeadingComments(newDefinition, newRewriter, collector);
} }
@ -241,14 +242,14 @@ public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefact
}); });
} }
private boolean newFileCheck() { private boolean newFileCheck() throws CoreException {
implUnit = context.getTUForSiblingFile(); implAst = context.getASTForPartnerFile();
if (implUnit == null) { if (implAst == null) {
ToggleFileCreator filecreator = new ToggleFileCreator(context, ".cpp"); //$NON-NLS-1$ ToggleFileCreator fileCreator = new ToggleFileCreator(context, ".cpp"); //$NON-NLS-1$
if (filecreator.askUserForFileCreation(context)) { if (fileCreator.askUserForFileCreation(context)) {
filecreator.createNewFile(); IFile file = fileCreator.createNewFile();
implUnit = filecreator.loadTranslationUnit(); implAst = context.getAST(file, null);
includeNode = new ASTLiteralNode(filecreator.getIncludeStatement()); includeNode = new ASTLiteralNode(fileCreator.getIncludeStatement());
return true; return true;
} else { } else {
return false; return false;
@ -268,7 +269,7 @@ public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefact
private IASTNode findInsertionPoint(IASTNode insertionParent, IASTTranslationUnit unit) { private IASTNode findInsertionPoint(IASTNode insertionParent, IASTTranslationUnit unit) {
IASTFunctionDeclarator declarator = context.getDeclaration(); IASTFunctionDeclarator declarator = context.getDeclaration();
if (unit == null) { if (unit == null) {
unit = context.getDefinitionUnit(); unit = context.getDefinitionAST();
} }
if (declarator == null) { if (declarator == null) {
declarator = context.getDefinition().getDeclarator(); declarator = context.getDefinition().getDeclarator();
@ -280,7 +281,7 @@ public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefact
private void restoreLeadingComments(ICPPASTFunctionDefinition newDefinition, private void restoreLeadingComments(ICPPASTFunctionDefinition newDefinition,
ASTRewrite newRewriter, ModificationCollector collector) { ASTRewrite newRewriter, ModificationCollector collector) {
ASTRewrite rw = collector.rewriterForTranslationUnit(context.getDefinitionUnit()); ASTRewrite rw = collector.rewriterForTranslationUnit(context.getDefinitionAST());
List<IASTComment>comments = rw.getComments(context.getDefinition(), CommentPosition.leading); List<IASTComment>comments = rw.getComments(context.getDefinition(), CommentPosition.leading);
if (comments != null) { if (comments != null) {
for (IASTComment comment : comments) { for (IASTComment comment : comments) {
@ -295,7 +296,7 @@ public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefact
private void replaceDefinitionWithDeclaration(ModificationCollector collector) { private void replaceDefinitionWithDeclaration(ModificationCollector collector) {
IASTSimpleDeclaration newdeclarator = IASTSimpleDeclaration newdeclarator =
ToggleNodeHelper.createDeclarationFromDefinition(context.getDefinition()); ToggleNodeHelper.createDeclarationFromDefinition(context.getDefinition());
ASTRewrite rewrite = collector.rewriterForTranslationUnit(context.getDefinitionUnit()); ASTRewrite rewrite = collector.rewriterForTranslationUnit(context.getDefinitionAST());
rewrite.replace(context.getDefinition(), newdeclarator, infoText); rewrite.replace(context.getDefinition(), newdeclarator, infoText);
} }
@ -343,19 +344,19 @@ public class ToggleFromInHeaderToImplementationStrategy implements IToggleRefact
private CPPASTNamespaceDefinition createNamespace(ICPPASTNamespaceDefinition parent_namespace) { private CPPASTNamespaceDefinition createNamespace(ICPPASTNamespaceDefinition parent_namespace) {
CPPASTNamespaceDefinition insertionParent = new CPPASTNamespaceDefinition( CPPASTNamespaceDefinition insertionParent = new CPPASTNamespaceDefinition(
parent_namespace.getName().copy(CopyStyle.withLocations)); parent_namespace.getName().copy(CopyStyle.withLocations));
insertionParent.setParent(implUnit); insertionParent.setParent(implAst);
return insertionParent; return insertionParent;
} }
private void removeDefinitionFromHeader(ModificationCollector collector) { private void removeDefinitionFromHeader(ModificationCollector collector) {
ASTRewrite header_rewrite = collector.rewriterForTranslationUnit( ASTRewrite header_rewrite = collector.rewriterForTranslationUnit(
context.getDefinitionUnit()); context.getDefinitionAST());
header_rewrite.remove(ToggleNodeHelper.getParentRemovePoint(context.getDefinition()), infoText); header_rewrite.remove(ToggleNodeHelper.getParentRemovePoint(context.getDefinition()), infoText);
} }
private IASTNode searchNamespaceInImplementation(final IASTName name) { private IASTNode searchNamespaceInImplementation(final IASTName name) {
final Container<IASTNode> result = new Container<IASTNode>(); final Container<IASTNode> result = new Container<IASTNode>();
this.implUnit.accept(new ASTVisitor() { this.implAst.accept(new ASTVisitor() {
{ {
shouldVisitNamespaces = true; shouldVisitNamespaces = true;
} }

View file

@ -16,11 +16,6 @@ import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.Stack; import java.util.Stack;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.dom.ast.IASTComment; import org.eclipse.cdt.core.dom.ast.IASTComment;
import org.eclipse.cdt.core.dom.ast.IASTCompositeTypeSpecifier; import org.eclipse.cdt.core.dom.ast.IASTCompositeTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier; import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier;
@ -46,15 +41,6 @@ import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateDeclaration;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateId; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateId;
import org.eclipse.cdt.core.dom.rewrite.ASTRewrite; import org.eclipse.cdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.cdt.core.dom.rewrite.ASTRewrite.CommentPosition; import org.eclipse.cdt.core.dom.rewrite.ASTRewrite.CommentPosition;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.index.IIndexFile;
import org.eclipse.cdt.core.index.IIndexInclude;
import org.eclipse.cdt.core.index.IndexLocationFactory;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.CoreModelUtil;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTCompoundStatement; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTCompoundStatement;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTFunctionDefinition; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTFunctionDefinition;
@ -64,8 +50,6 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTQualifiedName;
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.CPPASTTemplateId; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTemplateId;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTypeId; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTypeId;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor;
import org.eclipse.cdt.internal.core.model.TranslationUnit;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
import org.eclipse.cdt.internal.ui.refactoring.utils.NodeHelper; import org.eclipse.cdt.internal.ui.refactoring.utils.NodeHelper;
@ -82,8 +66,7 @@ public class ToggleNodeHelper extends NodeHelper {
} }
} }
private static ArrayList<ICPPASTConstructorChainInitializer> private static List<ICPPASTConstructorChainInitializer> getInitializerList(IASTFunctionDefinition definition) {
getInitializerList(IASTFunctionDefinition definition) {
ArrayList<ICPPASTConstructorChainInitializer> initalizers = ArrayList<ICPPASTConstructorChainInitializer> initalizers =
new ArrayList<ICPPASTConstructorChainInitializer>(); new ArrayList<ICPPASTConstructorChainInitializer>();
@ -95,8 +78,7 @@ public class ToggleNodeHelper extends NodeHelper {
return initalizers; return initalizers;
} }
static IASTSimpleDeclaration createDeclarationFromDefinition( static IASTSimpleDeclaration createDeclarationFromDefinition(IASTFunctionDefinition oldDefinition) {
IASTFunctionDefinition oldDefinition) {
IASTDeclarator newDeclarator = oldDefinition.getDeclarator().copy(CopyStyle.withLocations); IASTDeclarator newDeclarator = oldDefinition.getDeclarator().copy(CopyStyle.withLocations);
IASTDeclSpecifier newDeclSpec = oldDefinition.getDeclSpecifier().copy(CopyStyle.withLocations); IASTDeclSpecifier newDeclSpec = oldDefinition.getDeclSpecifier().copy(CopyStyle.withLocations);
IASTSimpleDeclaration newDeclaration = new CPPASTSimpleDeclaration(newDeclSpec); IASTSimpleDeclaration newDeclaration = new CPPASTSimpleDeclaration(newDeclSpec);
@ -133,8 +115,7 @@ public class ToggleNodeHelper extends NodeHelper {
return newFuncDecl; return newFuncDecl;
} }
private static void copyInitializerList(ICPPASTFunctionDefinition newFunc, private static void copyInitializerList(ICPPASTFunctionDefinition newFunc, IASTFunctionDefinition oldFunc) {
IASTFunctionDefinition oldFunc) {
for (ICPPASTConstructorChainInitializer initializer : getInitializerList(oldFunc)) { for (ICPPASTConstructorChainInitializer initializer : getInitializerList(oldFunc)) {
initializer.setParent(newFunc); initializer.setParent(newFunc);
newFunc.addMemberInitializer(initializer); newFunc.addMemberInitializer(initializer);
@ -168,12 +149,12 @@ public class ToggleNodeHelper extends NodeHelper {
} }
private static ICPPASTTemplateDeclaration addTemplateDeclarationsInOrder( private static ICPPASTTemplateDeclaration addTemplateDeclarationsInOrder(
ArrayList<ICPPASTTemplateDeclaration> templdecs, IASTFunctionDefinition newfunc) { ArrayList<ICPPASTTemplateDeclaration> templDecs, IASTFunctionDefinition newFunction) {
ListIterator<ICPPASTTemplateDeclaration> iter1 = templdecs.listIterator(); ListIterator<ICPPASTTemplateDeclaration> iter1 = templDecs.listIterator();
ICPPASTTemplateDeclaration child = null; ICPPASTTemplateDeclaration child = null;
while (iter1.hasNext()) { while (iter1.hasNext()) {
child = iter1.next(); child = iter1.next();
child.setDeclaration(newfunc); child.setDeclaration(newFunction);
ListIterator<ICPPASTTemplateDeclaration> iter2 = iter1; ListIterator<ICPPASTTemplateDeclaration> iter2 = iter1;
if (iter2.hasNext()) { if (iter2.hasNext()) {
ICPPASTTemplateDeclaration parent = iter2.next(); ICPPASTTemplateDeclaration parent = iter2.next();
@ -185,8 +166,7 @@ public class ToggleNodeHelper extends NodeHelper {
return child; return child;
} }
private static ArrayList<ICPPASTTemplateDeclaration> getAllTemplateDeclaration( private static ArrayList<ICPPASTTemplateDeclaration> getAllTemplateDeclaration(IASTNode node) {
IASTNode node) {
ArrayList<ICPPASTTemplateDeclaration> templdecs = new ArrayList<ICPPASTTemplateDeclaration>(); ArrayList<ICPPASTTemplateDeclaration> templdecs = new ArrayList<ICPPASTTemplateDeclaration>();
while (node.getParent() != null) { while (node.getParent() != null) {
node = node.getParent(); node = node.getParent();
@ -198,10 +178,10 @@ public class ToggleNodeHelper extends NodeHelper {
} }
static IASTFunctionDefinition createInClassDefinition(IASTFunctionDeclarator dec, static IASTFunctionDefinition createInClassDefinition(IASTFunctionDeclarator dec,
IASTFunctionDefinition def, IASTTranslationUnit insertionunit) { IASTFunctionDefinition def, IASTTranslationUnit insertionAst) {
IASTFunctionDeclarator declarator = dec.copy(CopyStyle.withLocations); IASTFunctionDeclarator declarator = dec.copy(CopyStyle.withLocations);
ICPPASTDeclSpecifier declSpec = (ICPPASTDeclSpecifier) def.getDeclSpecifier().copy( ICPPASTDeclSpecifier declSpec =
CopyStyle.withLocations); (ICPPASTDeclSpecifier) def.getDeclSpecifier().copy(CopyStyle.withLocations);
declSpec.setInline(false); declSpec.setInline(false);
if (ToggleNodeHelper.isVirtual(dec)) { if (ToggleNodeHelper.isVirtual(dec)) {
declSpec.setVirtual(true); declSpec.setVirtual(true);
@ -263,8 +243,8 @@ public class ToggleNodeHelper extends NodeHelper {
return qName; return qName;
} }
private static Stack<IASTNode> getQualifiedNames( private static Stack<IASTNode> getQualifiedNames(IASTFunctionDeclarator declarator,
IASTFunctionDeclarator declarator, IASTNode limiter, IASTNode node) { IASTNode limiter, IASTNode node) {
IASTName lastName = declarator.getName(); IASTName lastName = declarator.getName();
Stack<IASTNode> nodes = new Stack<IASTNode>(); Stack<IASTNode> nodes = new Stack<IASTNode>();
while (node.getParent() != null && node.getParent() != limiter) { while (node.getParent() != null && node.getParent() != limiter) {
@ -294,12 +274,12 @@ public class ToggleNodeHelper extends NodeHelper {
private static ICPPASTTemplateId getTemplateParameter(IASTNode node, IASTName name) { private static ICPPASTTemplateId getTemplateParameter(IASTNode node, IASTName name) {
ICPPASTTemplateId templateID = new CPPASTTemplateId(); ICPPASTTemplateId templateID = new CPPASTTemplateId();
templateID.setTemplateName(name.copy(CopyStyle.withLocations)); templateID.setTemplateName(name.copy(CopyStyle.withLocations));
for(IASTNode child : node.getChildren()) { for (IASTNode child : node.getChildren()) {
if (child instanceof ICPPASTSimpleTypeTemplateParameter) { if (child instanceof ICPPASTSimpleTypeTemplateParameter) {
ICPPASTSimpleTypeTemplateParameter tempcild = (ICPPASTSimpleTypeTemplateParameter) child; ICPPASTSimpleTypeTemplateParameter tempChild = (ICPPASTSimpleTypeTemplateParameter) child;
CPPASTNamedTypeSpecifier namedTypeSpecifier = new CPPASTNamedTypeSpecifier(); CPPASTNamedTypeSpecifier namedTypeSpecifier = new CPPASTNamedTypeSpecifier();
namedTypeSpecifier.setName(tempcild.getName().copy(CopyStyle.withLocations)); namedTypeSpecifier.setName(tempChild.getName().copy(CopyStyle.withLocations));
CPPASTTypeId id = new CPPASTTypeId(); CPPASTTypeId id = new CPPASTTypeId();
id.setDeclSpecifier(namedTypeSpecifier); id.setDeclSpecifier(namedTypeSpecifier);
@ -309,54 +289,6 @@ public class ToggleNodeHelper extends NodeHelper {
return templateID; return templateID;
} }
/**
* @deprecated Use SourceHeaderPartnerHelper
*/
@Deprecated
static IASTTranslationUnit getSiblingFile(IFile file, IASTTranslationUnit ast) throws CoreException {
ICProject cProject = CoreModel.getDefault().create(file).getCProject();
ICProject[] projects = CoreModel.getDefault().getCModel().getCProjects();
IIndex projectIndex = CCorePlugin.getIndexManager().getIndex(projects);
try {
projectIndex.acquireReadLock();
IIndexFile[] thisFileVariants = projectIndex.getFiles(ast.getLinkage().getLinkageID(),
IndexLocationFactory.getWorkspaceIFL(file));
String fileName = ToggleNodeHelper.getFilenameWithoutExtension(
file.getFullPath().toString());
if (ast.isHeaderUnit()) {
for (IIndexFile thisFile : thisFileVariants) {
for (IIndexInclude include : projectIndex.findIncludedBy(thisFile)) {
if (ToggleNodeHelper.getFilenameWithoutExtension(include.getIncludedBy().getLocation().getFullPath()).equals(fileName)) {
ITranslationUnit tu = CoreModelUtil.findTranslationUnitForLocation(include.getIncludedBy().getLocation().getURI(), cProject);
return tu.getAST(projectIndex, ITranslationUnit.AST_SKIP_ALL_HEADERS);
}
}
}
} else {
for (IIndexFile thisFile : thisFileVariants) {
for (IIndexInclude include : projectIndex.findIncludes(thisFile)) {
if (ToggleNodeHelper.getFilenameWithoutExtension(include.getFullName()).equals(fileName)) {
if (include.getIncludesLocation() == null) {
throw new NotSupportedException("The include file does not exist"); //$NON-NLS-1$
}
String loc = include.getIncludesLocation().getFullPath();
ICElement tufile = CoreModel.getDefault().create(new Path(loc));
if (tufile instanceof TranslationUnit) {
return ((TranslationUnit) tufile).getAST(null, ITranslationUnit.AST_SKIP_ALL_HEADERS);
}
}
}
}
}
} catch (InterruptedException e) {
// Ignore
} finally {
projectIndex.releaseReadLock();
}
return null;
}
public static String getFilenameWithoutExtension(String filename) { public static String getFilenameWithoutExtension(String filename) {
int indexP = filename.lastIndexOf('.'); int indexP = filename.lastIndexOf('.');
int indexS = filename.lastIndexOf('/'); int indexS = filename.lastIndexOf('/');
@ -395,31 +327,31 @@ public class ToggleNodeHelper extends NodeHelper {
* Gets comments inside the body of a function. * Gets comments inside the body of a function.
* @return The body as a string and all the catch handlers * @return The body as a string and all the catch handlers
*/ */
public static String getBody(IASTFunctionDefinition oldDefinition, IASTTranslationUnit oldUnit, public static String getBody(IASTFunctionDefinition oldDefinition, IASTTranslationUnit ast,
ModificationCollector modifications) { ModificationCollector modifications) {
return getBodyOnly(oldDefinition, oldUnit, modifications) return getBodyOnly(oldDefinition, ast, modifications)
+ getCatchHandlers(oldDefinition, oldUnit, modifications); + getCatchHandlers(oldDefinition, ast, modifications);
} }
private static String getBodyOnly(IASTFunctionDefinition oldDefinition, IASTTranslationUnit oldUnit, private static String getBodyOnly(IASTFunctionDefinition oldDefinition, IASTTranslationUnit ast,
ModificationCollector modifications) { ModificationCollector modifications) {
String leadingComments = getCommentsAsString(getLeadingCommentsFromNode(oldDefinition.getBody(), String leadingComments = getCommentsAsString(getLeadingCommentsFromNode(oldDefinition.getBody(),
oldUnit, modifications)); ast, modifications));
String trailingComments = getCommentsAsString(getTrailingComments(oldDefinition.getBody(), String trailingComments = getCommentsAsString(getTrailingComments(oldDefinition.getBody(),
oldUnit, modifications)); ast, modifications));
return leadingComments + oldDefinition.getBody().getRawSignature() + trailingComments; return leadingComments + oldDefinition.getBody().getRawSignature() + trailingComments;
} }
private static String getCatchHandlers(IASTFunctionDefinition oldDefinition, IASTTranslationUnit oldUnit, private static String getCatchHandlers(IASTFunctionDefinition oldDefinition, IASTTranslationUnit ast,
ModificationCollector modifications) { ModificationCollector modifications) {
if (oldDefinition instanceof ICPPASTFunctionWithTryBlock) { if (oldDefinition instanceof ICPPASTFunctionWithTryBlock) {
ICPPASTCatchHandler[] oldCatches = ICPPASTCatchHandler[] oldCatches =
((ICPPASTFunctionWithTryBlock) oldDefinition).getCatchHandlers(); ((ICPPASTFunctionWithTryBlock) oldDefinition).getCatchHandlers();
String allCatchHandlers = ""; //$NON-NLS-1$ String allCatchHandlers = ""; //$NON-NLS-1$
for (int i = 0; i < oldCatches.length; i++) { for (int i = 0; i < oldCatches.length; i++) {
String lead = getCommentsAsString(getLeadingCommentsFromNode(oldCatches[i], oldUnit, String lead = getCommentsAsString(getLeadingCommentsFromNode(oldCatches[i], ast,
modifications)); modifications));
String trail = getCommentsAsString(getTrailingComments(oldCatches[i], oldUnit, modifications)); String trail = getCommentsAsString(getTrailingComments(oldCatches[i], ast, modifications));
allCatchHandlers += lead + oldCatches[i].getRawSignature() + trail; allCatchHandlers += lead + oldCatches[i].getRawSignature() + trail;
} }
return allCatchHandlers; return allCatchHandlers;
@ -428,14 +360,14 @@ public class ToggleNodeHelper extends NodeHelper {
} }
private static List<IASTComment> getLeadingCommentsFromNode(IASTNode existingNode, private static List<IASTComment> getLeadingCommentsFromNode(IASTNode existingNode,
IASTTranslationUnit oldUnit, ModificationCollector modifications) { IASTTranslationUnit ast, ModificationCollector modifications) {
ASTRewrite rw = modifications.rewriterForTranslationUnit(oldUnit); ASTRewrite rw = modifications.rewriterForTranslationUnit(ast);
return rw.getComments(existingNode, CommentPosition.leading); return rw.getComments(existingNode, CommentPosition.leading);
} }
private static List<IASTComment> getTrailingComments(IASTNode existingNode, private static List<IASTComment> getTrailingComments(IASTNode existingNode,
IASTTranslationUnit oldUnit, ModificationCollector modifications) { IASTTranslationUnit ast, ModificationCollector modifications) {
ASTRewrite rw = modifications.rewriterForTranslationUnit(oldUnit); ASTRewrite rw = modifications.rewriterForTranslationUnit(ast);
return rw.getComments(existingNode, CommentPosition.trailing); return rw.getComments(existingNode, CommentPosition.trailing);
} }

View file

@ -12,24 +12,18 @@
******************************************************************************/ ******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.togglefunction; package org.eclipse.cdt.internal.ui.refactoring.togglefunction;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
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.jface.text.ITextSelection; import org.eclipse.jface.text.ITextSelection;
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.ui.ide.IDE;
import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.index.IIndexManager; import org.eclipse.cdt.core.index.IIndexManager;
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.core.pdom.indexer.IndexerPreferences;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
@ -42,14 +36,11 @@ public class ToggleRefactoring extends CRefactoring {
private ITextSelection selection; private ITextSelection selection;
private IToggleRefactoringStrategy strategy; private IToggleRefactoringStrategy strategy;
private ToggleRefactoringContext context; private ToggleRefactoringContext context;
private IIndex fIndex;
public ToggleRefactoring(IFile file, ITextSelection selection, ICProject proj) { public ToggleRefactoring(ICElement element, ITextSelection selection, ICProject project) {
super(file, selection, null, proj); super(element, selection, project);
if (selection == null || file == null || project == null) if (selection == null || tu.getResource() == null || project == null)
initStatus.addFatalError(Messages.ToggleRefactoring_InvalidSelection); initStatus.addFatalError(Messages.ToggleRefactoring_InvalidSelection);
if (!IDE.saveAllEditors(new IResource[] { ResourcesPlugin.getWorkspace().getRoot() }, false))
initStatus.addFatalError(Messages.ToggleRefactoring_CanNotSaveFiles);
this.selection = selection; this.selection = selection;
} }
@ -60,19 +51,15 @@ public class ToggleRefactoring extends CRefactoring {
pm.subTask(Messages.ToggleRefactoring_WaitingForIndexer); pm.subTask(Messages.ToggleRefactoring_WaitingForIndexer);
prepareIndexer(pm); prepareIndexer(pm);
pm.subTask(Messages.ToggleRefactoring_AnalyseSelection); pm.subTask(Messages.ToggleRefactoring_AnalyseSelection);
context = new ToggleRefactoringContext(fIndex, file, selection); context = new ToggleRefactoringContext(refactoringContext, getIndex(), tu, selection);
strategy = new ToggleStrategyFactory(context).getAppropriateStategy(); strategy = new ToggleStrategyFactory(context).getAppropriateStategy();
} catch (InterruptedException e) {
} catch (NotSupportedException e) { } catch (NotSupportedException e) {
initStatus.addFatalError(e.getMessage()); initStatus.addFatalError(e.getMessage());
} finally {
fIndex.releaseReadLock();
} }
return initStatus; return initStatus;
} }
private void prepareIndexer(IProgressMonitor pm) throws CoreException, InterruptedException { private void prepareIndexer(IProgressMonitor pm) throws CoreException {
IIndexManager im = CCorePlugin.getIndexManager(); IIndexManager im = CCorePlugin.getIndexManager();
while (!im.isProjectIndexed(project)) { while (!im.isProjectIndexed(project)) {
im.joinIndexer(500, pm); im.joinIndexer(500, pm);
@ -81,14 +68,11 @@ public class ToggleRefactoring extends CRefactoring {
} }
if (!im.isProjectIndexed(project)) if (!im.isProjectIndexed(project))
throw new NotSupportedException(Messages.ToggleRefactoring_NoIndex); throw new NotSupportedException(Messages.ToggleRefactoring_NoIndex);
IndexerPreferences.set(project.getProject(), IndexerPreferences.KEY_INDEX_UNUSED_HEADERS_WITH_DEFAULT_LANG, Boolean.TRUE.toString());
fIndex = CCorePlugin.getIndexManager().getIndex(project);
fIndex.acquireReadLock();
} }
@Override @Override
protected void collectModifications(IProgressMonitor pm, protected void collectModifications(IProgressMonitor pm, ModificationCollector modifications)
ModificationCollector modifications) throws CoreException { throws CoreException {
pm.subTask(Messages.ToggleRefactoring_CalculateModifications); pm.subTask(Messages.ToggleRefactoring_CalculateModifications);
strategy.run(modifications); strategy.run(modifications);
} }

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2011 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2011, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others. * Rapperswil, University of applied sciences and others.
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -7,14 +7,15 @@
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* Contributors: * Contributors:
* Martin Schwab & Thomas Kallenberg - initial API and implementation * Martin Schwab & Thomas Kallenberg - initial API and implementation
* Sergey Prigogin (Google)
******************************************************************************/ ******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.togglefunction; package org.eclipse.cdt.internal.ui.refactoring.togglefunction;
import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextSelection;
import org.eclipse.cdt.core.dom.ast.IASTFunctionDeclarator; import org.eclipse.cdt.core.dom.ast.IASTFunctionDeclarator;
@ -27,30 +28,38 @@ import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.index.IIndex; import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.index.IIndexName; import org.eclipse.cdt.core.index.IIndexName;
import org.eclipse.cdt.core.model.CModelException; import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.CoreModelUtil;
import org.eclipse.cdt.core.model.ITranslationUnit;
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.core.dom.parser.cpp.semantics.CPPVisitor;
import org.eclipse.cdt.internal.corext.util.CModelUtil;
import org.eclipse.cdt.internal.ui.editor.SourceHeaderPartnerFinder;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringContext;
import org.eclipse.cdt.internal.ui.refactoring.IndexToASTNameHelper; import org.eclipse.cdt.internal.ui.refactoring.IndexToASTNameHelper;
import org.eclipse.cdt.internal.ui.refactoring.utils.TranslationUnitHelper;
public class ToggleRefactoringContext { public class ToggleRefactoringContext {
private IASTFunctionDefinition targetDefinition; private IASTFunctionDefinition targetDefinition;
private IASTFunctionDeclarator targetDeclaration; private IASTFunctionDeclarator targetDeclaration;
private IASTTranslationUnit targetDefinitionUnit; private IASTTranslationUnit targetDefinitionAST;
private IASTTranslationUnit targetDeclarationUnit; private IASTTranslationUnit targetDeclarationAST;
private IIndex index; private final CRefactoringContext refactoringContext;
private IASTTranslationUnit selectionUnit; private final IIndex index;
private IFile selectionFile; private final ITranslationUnit selectionTU;
private IASTTranslationUnit selectionAST;
private IBinding binding; private IBinding binding;
private IASTName selectionName; private IASTName selectionName;
private boolean defaultAnswer; private boolean defaultAnswer;
private boolean settedDefaultAnswer; private boolean settedDefaultAnswer;
public ToggleRefactoringContext(IIndex index, IFile file, ITextSelection selection) { public ToggleRefactoringContext(CRefactoringContext refactoringContext, IIndex index,
ITranslationUnit translationUnit, ITextSelection selection)
throws OperationCanceledException, CoreException {
this.refactoringContext = refactoringContext;
this.index = index; this.index = index;
this.selectionFile = file; this.selectionTU = translationUnit;
findSelectionUnit(); findSelectionAST();
findSelectedFunctionDeclarator(selection); findSelectedFunctionDeclarator(selection);
findBinding(); findBinding();
findDeclaration(); findDeclaration();
@ -58,7 +67,7 @@ public class ToggleRefactoringContext {
} }
public void findSelectedFunctionDeclarator(ITextSelection selection) { public void findSelectedFunctionDeclarator(ITextSelection selection) {
selectionName = new DeclaratorFinder(selection, selectionUnit).getName(); selectionName = new DeclaratorFinder(selection, selectionAST).getName();
} }
public void findBinding() { public void findBinding() {
@ -80,12 +89,12 @@ public class ToggleRefactoringContext {
throw new NotSupportedException( throw new NotSupportedException(
Messages.ToggleRefactoringContext_MultipleDeclarations); Messages.ToggleRefactoringContext_MultipleDeclarations);
for (IIndexName iname : decnames) { for (IIndexName iname : decnames) {
selectionUnit = getTUForNameInFile(iname); selectionAST = getASTForIndexName(iname);
IASTName astname = IndexToASTNameHelper.findMatchingASTName( IASTName astname = IndexToASTNameHelper.findMatchingASTName(
selectionUnit, iname, index); selectionAST, iname, index);
if (astname != null) { if (astname != null) {
targetDeclaration = findFunctionDeclarator(astname); targetDeclaration = findFunctionDeclarator(astname);
targetDeclarationUnit = selectionUnit; targetDeclarationAST = selectionAST;
break; break;
} }
} }
@ -101,11 +110,11 @@ public class ToggleRefactoringContext {
throw new NotSupportedException(Messages.ToggleRefactoringContext_MultipleDefinitions); throw new NotSupportedException(Messages.ToggleRefactoringContext_MultipleDefinitions);
} }
for (IIndexName iname : defnames) { for (IIndexName iname : defnames) {
IASTTranslationUnit unit = getTUForNameInFile(iname); IASTTranslationUnit unit = getASTForIndexName(iname);
IASTName astname = IndexToASTNameHelper.findMatchingASTName(unit, iname, index); IASTName astname = IndexToASTNameHelper.findMatchingASTName(unit, iname, index);
if (astname != null) { if (astname != null) {
targetDefinition = findFunctionDefinition(astname); targetDefinition = findFunctionDefinition(astname);
targetDefinitionUnit = unit; targetDefinitionAST = unit;
break; break;
} }
} }
@ -124,51 +133,51 @@ public class ToggleRefactoringContext {
return targetDefinition; return targetDefinition;
} }
public IASTTranslationUnit getDeclarationUnit() { public IASTTranslationUnit getDeclarationAST() {
return targetDeclarationUnit; return targetDeclarationAST;
} }
public IASTTranslationUnit getDefinitionUnit() { public IASTTranslationUnit getDefinitionAST() {
return targetDefinitionUnit; return targetDefinitionAST;
}
public ITranslationUnit getSelectionTU() {
return selectionTU;
} }
public IFile getSelectionFile() { public IFile getSelectionFile() {
return selectionFile; return (IFile) selectionTU.getResource();
} }
public IASTTranslationUnit getTUForSiblingFile() { public IASTTranslationUnit getASTForPartnerFile() throws CoreException {
IASTTranslationUnit unit = getDeclarationUnit(); ITranslationUnit tu =
if (unit == null) SourceHeaderPartnerFinder.getPartnerTranslationUnit(selectionTU, refactoringContext);
unit = getDefinitionUnit(); if (tu == null)
try {
return ToggleNodeHelper.getSiblingFile(getSelectionFile(), unit);
} catch (CoreException e) {
CUIPlugin.log(e);
return null; return null;
} return refactoringContext.getAST(tu, null);
} }
private void findSelectionUnit() { private void findSelectionAST() throws OperationCanceledException, CoreException {
try { selectionAST = refactoringContext.getAST(selectionTU, null);
selectionUnit = TranslationUnitHelper.loadTranslationUnit(selectionFile, true); if (selectionAST == null)
} catch (Exception e) {
}
if (selectionUnit == null)
throw new NotSupportedException(Messages.ToggleRefactoringContext_NoTuFound); throw new NotSupportedException(Messages.ToggleRefactoringContext_NoTuFound);
} }
private IASTTranslationUnit getTUForNameInFile(IIndexName iname) private IASTTranslationUnit getASTForIndexName(IIndexName indexName)
throws CModelException, CoreException { throws CModelException, CoreException {
if (isSameFileAsInTU(iname)) { if (isSameFileAsInTU(indexName)) {
return selectionUnit; return selectionAST;
} }
IPath path = new Path(iname.getFileLocation().getFileName()); ITranslationUnit tu = CoreModelUtil.findTranslationUnitForLocation(
return TranslationUnitHelper.loadTranslationUnit(path.toString(), true); indexName.getFile().getLocation(), null);
if (tu == null)
return null;
return refactoringContext.getAST(tu, null);
} }
private boolean isSameFileAsInTU(IIndexName iname) { private boolean isSameFileAsInTU(IIndexName indexName) {
return iname.getFileLocation().getFileName().equals( return indexName.getFileLocation().getFileName().equals(
selectionUnit.getFileLocation().getFileName()); selectionAST.getFileLocation().getFileName());
} }
private IASTFunctionDeclarator findFunctionDeclarator(IASTNode node) { private IASTFunctionDeclarator findFunctionDeclarator(IASTNode node) {
@ -197,4 +206,13 @@ public class ToggleRefactoringContext {
public boolean isSettedDefaultAnswer() { public boolean isSettedDefaultAnswer() {
return settedDefaultAnswer; return settedDefaultAnswer;
} }
public IASTTranslationUnit getAST(IFile file, IProgressMonitor pm)
throws OperationCanceledException, CoreException {
ITranslationUnit tu = CoreModelUtil.findTranslationUnit(file);
if (tu == null)
return null;
tu = CModelUtil.toWorkingCopy(tu);
return refactoringContext.getAST(tu, pm);
}
} }

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2011 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2011, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others. * Rapperswil, University of applied sciences and others.
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -7,11 +7,11 @@
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* Contributors: * Contributors:
* Martin Schwab & Thomas Kallenberg - initial API and implementation * Martin Schwab & Thomas Kallenberg - initial API and implementation
* Sergey Prigogin (Google)
******************************************************************************/ ******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.togglefunction; package org.eclipse.cdt.internal.ui.refactoring.togglefunction;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.window.IShellProvider; import org.eclipse.jface.window.IShellProvider;
@ -21,6 +21,7 @@ import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.refactoring.RefactoringRunner; import org.eclipse.cdt.internal.ui.refactoring.RefactoringRunner;
import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper;
/** /**
* Responsible for scheduling a job which runs the ToggleRefactoring. Differs * Responsible for scheduling a job which runs the ToggleRefactoring. Differs
@ -29,21 +30,24 @@ import org.eclipse.cdt.internal.ui.refactoring.RefactoringRunner;
*/ */
public class ToggleRefactoringRunner extends RefactoringRunner { public class ToggleRefactoringRunner extends RefactoringRunner {
private ToggleRefactoring refactoring; public ToggleRefactoringRunner(ICElement element, ITextSelection selection,
IShellProvider shellProvider, ICProject project) {
public ToggleRefactoringRunner(IFile file, ITextSelection selection, super(element, selection, shellProvider, project);
ICElement element, IShellProvider shellProvider, ICProject project) {
super(file, selection, element, shellProvider, project);
refactoring = new ToggleRefactoring(file, selection, project);
} }
@Override @Override
public void run() { public void run() {
Job[] jobs = Job.getJobManager().find(RefactoringJob.FAMILY_TOGGLE_DEFINITION); Job[] jobs = Job.getJobManager().find(RefactoringJob.FAMILY_TOGGLE_DEFINITION);
if (jobs.length > 0) { if (jobs.length > 0) {
CUIPlugin.log("no concurrent toggling allowed", new NotSupportedException("")); //$NON-NLS-1$//$NON-NLS-2$ CUIPlugin.log("No concurrent toggling allowed", new NotSupportedException("")); //$NON-NLS-1$//$NON-NLS-2$
return; return;
} }
RefactoringSaveHelper saveHelper= new RefactoringSaveHelper(RefactoringSaveHelper.SAVE_REFACTORING);
if (!saveHelper.saveEditors(shellProvider.getShell()))
return;
ToggleRefactoring refactoring =
new ToggleRefactoring(element, (ITextSelection) selection, project);
new RefactoringJob(refactoring).schedule(); new RefactoringJob(refactoring).schedule();
} }
} }

View file

@ -17,7 +17,6 @@ import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateDeclaration;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor; import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor;
public class ToggleStrategyFactory { public class ToggleStrategyFactory {
private ToggleRefactoringContext context; private ToggleRefactoringContext context;
public ToggleStrategyFactory(ToggleRefactoringContext context) { public ToggleStrategyFactory(ToggleRefactoringContext context) {
@ -27,7 +26,7 @@ public class ToggleStrategyFactory {
public IToggleRefactoringStrategy getAppropriateStategy() { public IToggleRefactoringStrategy getAppropriateStategy() {
if (context.getDefinition() == null) if (context.getDefinition() == null)
throw new NotSupportedException(Messages.ToggleStrategyFactory_NoDefinitionFound); throw new NotSupportedException(Messages.ToggleStrategyFactory_NoDefinitionFound);
if (!context.getDefinitionUnit().isHeaderUnit()) if (!context.getDefinitionAST().isHeaderUnit())
return new ToggleFromImplementationToHeaderOrClassStrategy(context); return new ToggleFromImplementationToHeaderOrClassStrategy(context);
if (isInClassSituation()) if (isInClassSituation())
return new ToggleFromClassToInHeaderStrategy(context); return new ToggleFromClassToInHeaderStrategy(context);
@ -40,7 +39,7 @@ public class ToggleStrategyFactory {
private boolean isinHeaderSituation() { private boolean isinHeaderSituation() {
return (context.getDefinition() != null) return (context.getDefinition() != null)
&& (context.getDefinitionUnit().isHeaderUnit()); && (context.getDefinitionAST().isHeaderUnit());
} }
private boolean isInClassSituation() { private boolean isInClassSituation() {

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2011 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2011, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others. * Rapperswil, University of applied sciences and others.
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -7,11 +7,11 @@
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* Contributors: * Contributors:
* Martin Schwab & Thomas Kallenberg - initial API and implementation * Martin Schwab & Thomas Kallenberg - initial API and implementation
* Sergey Prigogin (Google)
******************************************************************************/ ******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.togglefunction; package org.eclipse.cdt.internal.ui.refactoring.togglefunction;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IAction;
import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelection;
@ -20,8 +20,7 @@ import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate; import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.cdt.ui.CUIPlugin;
/** /**
@ -31,11 +30,8 @@ import org.eclipse.cdt.ui.CUIPlugin;
* Order of execution is: constructor, init, selectionChanged, run * Order of execution is: constructor, init, selectionChanged, run
*/ */
public class TogglingActionDelegate implements IWorkbenchWindowActionDelegate { public class TogglingActionDelegate implements IWorkbenchWindowActionDelegate {
private IWorkbenchWindow window; private IWorkbenchWindow window;
private TextSelection selection; private TextSelection selection;
private ICProject project;
private IFile file;
@Override @Override
public void init(IWorkbenchWindow window) { public void init(IWorkbenchWindow window) {
@ -45,36 +41,27 @@ public class TogglingActionDelegate implements IWorkbenchWindowActionDelegate {
@Override @Override
public void selectionChanged(IAction action, ISelection selection) { public void selectionChanged(IAction action, ISelection selection) {
boolean isTextSelection = selection != null boolean isTextSelection = selection != null && selection instanceof TextSelection;
&& selection instanceof TextSelection;
action.setEnabled(isTextSelection); action.setEnabled(isTextSelection);
if (!isTextSelection) if (!isTextSelection)
return; return;
//get our own selection due to (a possible) bug?? // Get our own selection due to (a possible) bug?
this.selection = (TextSelection) CUIPlugin.getActivePage().getActiveEditor().getEditorSite().getSelectionProvider().getSelection(); this.selection = (TextSelection) CUIPlugin.getActivePage().getActiveEditor().getEditorSite().getSelectionProvider().getSelection();
} }
@Override @Override
public void run(IAction action) { public void run(IAction action) {
if (!isWorkbenchReady())
return;
new ToggleRefactoringRunner(file, selection, project, window, project).run();
}
private boolean isWorkbenchReady() {
IWorkbenchPage activePage = window.getActivePage(); IWorkbenchPage activePage = window.getActivePage();
if (activePage == null) if (activePage == null)
return false; return;
IEditorPart editor = activePage.getActiveEditor(); IEditorPart editor = activePage.getActiveEditor();
if (editor == null || editor.getEditorInput() == null) if (editor == null || editor.getEditorInput() == null)
return false; return;
IWorkingCopy wc = CUIPlugin.getDefault().getWorkingCopyManager() ITranslationUnit tu =
.getWorkingCopy(editor.getEditorInput()); CUIPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(editor.getEditorInput());
if (wc == null) if (tu == null || tu.getResource() == null)
return false; return;
project = wc.getCProject(); new ToggleRefactoringRunner(tu, selection, window, tu.getCProject()).run();
file = (IFile) wc.getResource();
return project != null && file != null;
} }
@Override @Override

View file

@ -1,170 +0,0 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 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.filesystem.URIUtil;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.dom.CDOM;
import org.eclipse.cdt.core.dom.IASTServiceProvider.UnsupportedDialectException;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTFileLocation;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.refactoring.Container;
/**
* A collection of methods that deal with IASTTranslationUnits.
*
* @author Mirko Stocker
*/
public class TranslationUnitHelper {
private static final int AST_STYLE = ITranslationUnit.AST_CONFIGURE_USING_SOURCE_CONTEXT | ITranslationUnit.AST_SKIP_INDEXED_HEADERS;
/**
* Visits all names in the TU to find the specified name
*/
public static IASTName findNameInTranslationUnit(IASTTranslationUnit transUnit, IASTNode oldName) {
final String oldFileName = oldName.getFileLocation().getFileName();
final IASTFileLocation pos = oldName.getFileLocation();
final Container<IASTName> nameCon = new Container<IASTName>();
transUnit.accept(new ASTVisitor() {
{
shouldVisitNames = true;
}
@Override
public int visit(IASTName locName) {
IASTFileLocation locFileLocation = locName.getFileLocation();
if (locFileLocation != null && oldFileName.equals(locFileLocation.getFileName()) && pos.getNodeOffset() == locFileLocation.getNodeOffset()
&& pos.getNodeLength() == locFileLocation.getNodeLength()) {
nameCon.setObject(locName);
return PROCESS_ABORT;
}
return super.visit(locName);
}
});
return nameCon.getObject();
}
/**
* @return the first node in the translation unit or null
*/
public static IASTNode getFirstNode(IASTTranslationUnit unit) {
IASTDeclaration firstNode = null;
for (IASTDeclaration each : unit.getDeclarations()) {
if (firstNode == null) {
firstNode = each;
} else if (each.getNodeLocations() != null &&
each.getNodeLocations()[0].getNodeOffset() < firstNode.getNodeLocations()[0].getNodeOffset()) {
firstNode = each;
}
}
return firstNode;
}
/**
* @param filename to load the translation unit from
* @return the translation unit for the file or null
* @throws CoreException
* @deprecated Use RefactoringASTCache.
*/
@Deprecated
public static IASTTranslationUnit loadTranslationUnit(String filename, boolean useIndex) throws CoreException{
if (filename != null) {
IFile[] tmpFile = null;
tmpFile = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(
URIUtil.toURI(filename));
return loadTranslationUnit(tmpFile[0], useIndex);
}
return null;
}
/**
* @param file to load the translation unit from
* @return the translation unit for the file or null
* @throws CoreException
* @deprecated Use RefactoringASTCache.
*/
@Deprecated
public static IASTTranslationUnit loadTranslationUnit(IFile file, boolean useIndex) throws CoreException {
if (file == null) {
return null;
}
if (useIndex) {
return loadIndexBasedTranslationUnit(file);
} else {
return loadFileBasedTranslationUnit(file);
}
}
private static IASTTranslationUnit loadFileBasedTranslationUnit(IFile file) {
try {
IASTTranslationUnit fileUnit = CDOM.getInstance().getTranslationUnit(file, CDOM.getInstance().getCodeReaderFactory(CDOM.PARSE_SAVED_RESOURCES), true);
return fileUnit;
} catch (UnsupportedDialectException e) {
return null;
}
}
private static IASTTranslationUnit loadIndexBasedTranslationUnit(IFile file) throws CoreException {
IIndex index = null;
try {
index = lockIndex();
ITranslationUnit tu = (ITranslationUnit) CCorePlugin.getDefault().getCoreModel().create(file);
return tu.getAST(index, AST_STYLE);
} catch (InterruptedException e) {
CUIPlugin.log(e);
} finally {
unlockIndex(index);
}
return null;
}
private static IIndex lockIndex() throws CoreException, InterruptedException {
IIndex index;
ICProject[] projects= CoreModel.getDefault().getCModel().getCProjects();
index= CCorePlugin.getIndexManager().getIndex(projects);
try {
index.acquireReadLock();
} catch (InterruptedException e) {
// no lock was acquired
index= null;
throw e;
}
return index;
}
private static void unlockIndex(IIndex index) {
if (index != null) {
index.releaseReadLock();
}
}
}

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2011 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2011, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others. * Rapperswil, University of applied sciences and others.
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -7,34 +7,29 @@
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* Contributors: * Contributors:
* Institute for Software (IFS)- initial API and implementation * Institute for Software (IFS)- initial API and implementation
* Sergey Prigogin (Google)
******************************************************************************/ ******************************************************************************/
package org.eclipse.cdt.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;
import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPage;
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.IWorkingCopy; import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.refactoring.togglefunction.ToggleRefactoringRunner; import org.eclipse.cdt.internal.ui.refactoring.togglefunction.ToggleRefactoringRunner;
/** /**
*
* @since 5.3 * @since 5.3
* @author Emanuel Graf IFS * @author Emanuel Graf IFS
* *
* @noextend This class is not intended to be subclassed by clients. * @noextend This class is not intended to be subclassed by clients.
*/ */
public class ToggleFunctionAction extends RefactoringAction { public class ToggleFunctionAction extends RefactoringAction {
private ICProject project;
private IFile file;
public ToggleFunctionAction() { public ToggleFunctionAction() {
super(Messages.ToggleFunctionAction_label); super(Messages.ToggleFunctionAction_label);
@ -46,30 +41,16 @@ public class ToggleFunctionAction extends RefactoringAction {
} }
@Override @Override
public void run(IShellProvider shellProvider, IWorkingCopy wc, public void run(IShellProvider shellProvider, IWorkingCopy wc, ITextSelection selection) {
ITextSelection s) { if (wc == null || wc.getResource() == null)
IResource res = wc.getResource(); return;
if (isWorkbenchReady(wc) && res instanceof IFile) { IWorkbenchPage activePage = CUIPlugin.getActivePage();
new ToggleRefactoringRunner(file, s, project, shellProvider, project).run(); if (activePage == null)
} return;
} IEditorPart editor = activePage.getActiveEditor();
if (editor == null || editor.getEditorInput() == null)
private boolean isWorkbenchReady(IWorkingCopy wc) { return;
try { new ToggleRefactoringRunner(wc, selection, shellProvider, wc.getCProject()).run();
IWorkbenchPage activePage = CUIPlugin.getActivePage();
if (activePage == null)
return false;
IEditorPart editor = activePage.getActiveEditor();
if (editor == null || editor.getEditorInput() == null)
return false;
if (wc == null)
return false;
project = wc.getCProject();
file = (IFile) wc.getResource();
return project != null && file != null;
} catch (ClassCastException e) {
return false;
}
} }
@Override @Override
@ -77,5 +58,4 @@ public class ToggleFunctionAction extends RefactoringAction {
super.updateSelection(elem); super.updateSelection(elem);
setEnabled(false); setEnabled(false);
} }
} }