1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-04-23 14:42:11 +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.
*/
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 exclusionPatterns
* @return
* @return <code>true</code> if the given path matches one of the exclusion patterns.
*/
public static boolean isExcludedPath(IPath resourcePath, IPath[] exclusionPatterns) {
int length = exclusionPatterns.length;
@ -56,24 +55,19 @@ public class CoreModelUtil {
return isExcluded(resourcePath, fullCharExclusionPatterns);
}
/*
/**
* Returns whether the given resource matches one of the exclusion patterns.
*
* @see IClasspathEntry#getExclusionPatterns
*/
public final static boolean isExcluded(IResource resource, char[][] exclusionPatterns) {
IPath path = resource.getFullPath();
// ensure that folders are only excluded if all of their children are
// excluded
// Ensure that folders are only excluded if all of their children are excluded.
if (resource.getType() == IResource.FOLDER)
path = path.append("*"); //$NON-NLS-1$
return isExcluded(path, exclusionPatterns);
}
/*
/**
* Returns whether the given resource path matches one of the exclusion patterns.
*
* @see IClasspathEntry#getExclusionPatterns
*/
public final static boolean isExcluded(IPath resourcePath, char[][] exclusionPatterns) {
if (exclusionPatterns == null)
@ -93,7 +87,7 @@ public class CoreModelUtil {
/*
* 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)
return true;
if (a == null || b == null)
@ -110,7 +104,6 @@ public class CoreModelUtil {
return false;
}
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.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;
/**
@ -165,8 +165,8 @@ public abstract class RefactoringTestBase extends BaseTestCase {
Refactoring refactoring = createRefactoring();
RefactoringContext context;
if (refactoring instanceof CRefactoring2) {
context = new CRefactoringContext((CRefactoring2) refactoring);
if (refactoring instanceof CRefactoring) {
context = new CRefactoringContext((CRefactoring) refactoring);
} else {
context = new RefactoringContext(refactoring);
}

View file

@ -49,7 +49,7 @@ public class ToggleRefactoringTest extends RefactoringTestBase {
@Override
protected Refactoring createRefactoring() {
refactoring = new ToggleRefactoring(getSelectedFile(), getSelection(), getCProject());
refactoring = new ToggleRefactoring(getSelectedTranslationUnit(), getSelection(), getCProject());
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.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.ModificationCollector;
import org.eclipse.cdt.internal.ui.refactoring.utils.DefinitionFinder;
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) {
super(element, selection, project);
}
@ -64,7 +64,7 @@ public class DefinitionFinderTest extends RefactoringTestBase {
}
@Override
protected CRefactoring2 createRefactoring() {
protected CRefactoring createRefactoring() {
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 {
UtilTestSuite suite = new UtilTestSuite();
suite.addTest(IdentifierHelperTest.suite());
suite.addTestSuite(TranslationUnitHelperTest.class);
suite.addTestSuite(DefinitionFinderTest.class);
suite.addTestSuite(PseudoNameGeneratorTest.class);
suite.addTestSuite(NameComposerTest.class);

View file

@ -330,13 +330,13 @@ public final class SourceHeaderPartnerFinder {
}
public static ITranslationUnit getPartnerTranslationUnit(ITranslationUnit tu,
CRefactoringContext astCache) throws CoreException {
CRefactoringContext refactoringContext) throws CoreException {
ITranslationUnit partnerUnit= getPartnerFileFromFilename(tu);
if (partnerUnit == null) {
// Search partner file based on definition/declaration association
IProgressMonitor monitor= new NullProgressMonitor();
IASTTranslationUnit ast = astCache.getAST(tu, monitor);
IASTTranslationUnit ast = refactoringContext.getAST(tu, monitor);
PartnerFileVisitor visitor = new PartnerFileVisitor();
ast.accept(visitor);
partnerUnit = createTranslationUnit(visitor.getPartnerFileLocation(), tu.getCProject());
@ -344,12 +344,12 @@ public final class SourceHeaderPartnerFinder {
return partnerUnit;
}
private static ITranslationUnit createTranslationUnit(IPath partnerFileLoation, ICProject cProject) {
private static ITranslationUnit createTranslationUnit(IPath partnerFileLoation, ICProject project) {
ITranslationUnit partnerUnit = null;
if (partnerFileLoation != null) {
partnerUnit= (ITranslationUnit) CoreModel.getDefault().create(partnerFileLoation);
if (partnerUnit == null) {
partnerUnit= CoreModel.getDefault().createTranslationUnitFrom(cProject.getCProject(),
partnerUnit= CoreModel.getDefault().createTranslationUnitFrom(project,
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
* All rights reserved. This program and the accompanying materials
* 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
*
* 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;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
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;
@ -24,12 +30,15 @@ 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.CCorePlugin;
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;
@ -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.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.CoreModel;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
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.ui.CUIPlugin;
import org.eclipse.cdt.internal.corext.util.CModelUtil;
import org.eclipse.cdt.internal.ui.refactoring.utils.SelectionHelper;
/**
* The base class for all other refactorings, provides some common implementations for
* condition checking, change generating, selection handling and translation unit loading.
* @deprecated Use CRefactoring2.
* The base class for all AST based refactorings, provides some common implementations for
* AST creation, condition checking, change generating, and selection handling.
*/
@Deprecated
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 IFile file;
protected final ICProject project;
protected final ITranslationUnit tu;
protected Region region;
protected RefactoringStatus initStatus;
protected IASTTranslationUnit ast;
protected ICProject project;
private IIndex fIndex;
protected Region selectedRegion;
protected final RefactoringStatus initStatus;
protected CRefactoringContext refactoringContext;
public CRefactoring(IFile file, ISelection selection, ICElement element, ICProject proj) {
project = proj;
if (element instanceof ISourceReference) {
ISourceReference sourceRef= (ISourceReference) element;
this.tu = sourceRef.getTranslationUnit();
IResource res= tu.getResource();
if (res instanceof IFile)
this.file= (IFile) res;
public CRefactoring(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 {
final ISourceRange sourceRange = sourceRef.getSourceRange();
this.region = new Region(sourceRange.getIdStartPos(), sourceRange.getIdLength());
ISourceRange sourceRange = sourceRef.getSourceRange();
this.selectedRegion = new Region(sourceRange.getIdStartPos(), sourceRange.getIdLength());
} catch (CModelException 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();
if (this.file == null || region == null) {
initStatus.addFatalError(Messages.Refactoring_SelectionNotValid);
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 {
@ -102,7 +236,7 @@ public abstract class CRefactoring extends Refactoring {
public ProblemFinder(RefactoringStatus status) {
this.status = status;
}
{
shouldVisitProblems = true;
shouldVisitDeclarations = true;
@ -116,7 +250,7 @@ public abstract class CRefactoring extends Refactoring {
addWarningToState();
return ASTVisitor.PROCESS_CONTINUE;
}
@Override
public int visit(IASTDeclaration declaration) {
if (declaration instanceof IASTProblemDeclaration) {
@ -124,7 +258,7 @@ public abstract class CRefactoring extends Refactoring {
}
return ASTVisitor.PROCESS_CONTINUE;
}
@Override
public int visit(IASTExpression expression) {
if (expression instanceof IASTProblemExpression) {
@ -152,7 +286,7 @@ public abstract class CRefactoring extends Refactoring {
public boolean hasProblem() {
return problemFound;
}
private void addWarningToState() {
if (!problemFound) {
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 IASTTranslationUnit fSharedAST;
public CRefactoringContext(CRefactoring2 refactoring) {
public CRefactoringContext(CRefactoring refactoring) {
super(refactoring);
refactoring.setContext(this);
fASTCache = new ConcurrentHashMap<ITranslationUnit, IASTTranslationUnit>();

View file

@ -32,11 +32,7 @@ public abstract class CRefactoringContribution extends RefactoringContribution {
if (descriptor instanceof CRefactoringDescriptor) {
CRefactoringDescriptor refDesc = (CRefactoringDescriptor) descriptor;
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
public abstract CRefactoring2 createRefactoring(RefactoringStatus status) throws CoreException;
public abstract CRefactoring createRefactoring(RefactoringStatus status) throws CoreException;
@Override
public CRefactoringContext createRefactoringContext(RefactoringStatus status) throws CoreException {
CRefactoring2 refactoring= createRefactoring(status);
CRefactoring refactoring= createRefactoring(status);
if (refactoring == null)
return null;
return new CRefactoringContext(refactoring);

View file

@ -1,46 +1,48 @@
/*******************************************************************************
* 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;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
/**
* Base class for all refactoring runners.
*
* @deprecated Use RefactoringRunner2.
*
* @author Emanuel Graf
*/
@Deprecated
public abstract class RefactoringRunner {
protected IFile file;
protected ISelection selection;
protected ICElement celement;
protected IShellProvider shellProvider;
protected ICProject project;
public RefactoringRunner(IFile file, ISelection selection, ICElement element,
IShellProvider shellProvider, ICProject cProject) {
this.file = file;
this.selection = selection;
this.celement= element;
this.shellProvider= shellProvider;
this.project = cProject;
}
public abstract void run();
}
/*******************************************************************************
* 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.
*/
public abstract class RefactoringRunner {
protected final ISelection selection;
protected final ICElement element;
protected final ICProject project;
protected final IShellProvider shellProvider;
public RefactoringRunner(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, CRefactoring 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

@ -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) {
RefactoringSaveHelper saveHelper= new RefactoringSaveHelper(saveMode);
if (!canActivate(saveHelper, parent))
if (!saveHelper.saveEditors(parent))
return false;
try {
@ -46,8 +46,4 @@ public class RefactoringStarter {
public RefactoringStatus getInitialConditionCheckingStatus() {
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.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.ClassMemberInserter;
import org.eclipse.cdt.internal.ui.refactoring.MethodContext;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
import org.eclipse.cdt.internal.ui.refactoring.utils.NodeHelper;
import org.eclipse.cdt.internal.ui.refactoring.utils.TranslationUnitHelper;
import org.eclipse.cdt.internal.ui.util.NameComposer;
/**
@ -80,7 +79,7 @@ import org.eclipse.cdt.internal.ui.util.NameComposer;
*
* @author Mirko Stocker
*/
public class ExtractConstantRefactoring extends CRefactoring2 {
public class ExtractConstantRefactoring extends CRefactoring {
public static final String ID =
"org.eclipse.cdt.ui.refactoring.extractconstant.ExtractConstantRefactoring"; //$NON-NLS-1$
@ -344,11 +343,27 @@ public class ExtractConstantRefactoring extends CRefactoring2 {
} else {
IASTDeclaration nodes = getConstNodesGlobal(constName, ast.getASTNodeFactory());
ASTRewrite rewriter = collector.rewriterForTranslationUnit(ast);
rewriter.insertBefore(ast, TranslationUnitHelper.getFirstNode(ast), nodes,
rewriter.insertBefore(ast, getFirstNode(ast), nodes,
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
protected RefactoringDescriptor getRefactoringDescriptor() {
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.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.utils.VisibilityEnum;
@ -39,7 +39,7 @@ public class ExtractConstantRefactoringDescriptor extends CRefactoringDescriptor
}
@Override
public CRefactoring2 createRefactoring(RefactoringStatus status)
public CRefactoring createRefactoring(RefactoringStatus status)
throws CoreException {
ISelection selection = getSelection();
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.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;
/**
* @author Emanuel Graf
*/
public class ExtractConstantRefactoringRunner extends RefactoringRunner2 {
public class ExtractConstantRefactoringRunner extends RefactoringRunner {
public ExtractConstantRefactoringRunner(ICElement element, ISelection selection,
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.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.ClassMemberInserter;
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.viewsupport.BasicElementLabels;
public class ExtractFunctionRefactoring extends CRefactoring2 {
public class ExtractFunctionRefactoring extends CRefactoring {
public static final String ID =
"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.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.utils.VisibilityEnum;
@ -40,7 +40,7 @@ public class ExtractFunctionRefactoringDescriptor extends CRefactoringDescriptor
}
@Override
public CRefactoring2 createRefactoring(RefactoringStatus status) throws CoreException {
public CRefactoring createRefactoring(RefactoringStatus status) throws CoreException {
ISelection selection = getSelection();
ICProject project = getCProject();
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.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;
/**
* @author Emanuel Graf
*/
public class ExtractFunctionRefactoringRunner extends RefactoringRunner2 {
public class ExtractFunctionRefactoringRunner extends RefactoringRunner {
public ExtractFunctionRefactoringRunner(ICElement element, ISelection selection,
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.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.ModificationCollector;
import org.eclipse.cdt.internal.ui.refactoring.NodeContainer;
@ -83,7 +83,7 @@ import org.eclipse.cdt.internal.ui.util.NameComposer;
*
* @author Tom Ball
*/
public class ExtractLocalVariableRefactoring extends CRefactoring2 {
public class ExtractLocalVariableRefactoring extends CRefactoring {
public static final String ID =
"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.internal.ui.refactoring.CRefactoring2;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor;
/**
@ -37,7 +37,7 @@ public class ExtractLocalVariableRefactoringDescriptor extends CRefactoringDescr
}
@Override
public CRefactoring2 createRefactoring(RefactoringStatus status) throws CoreException {
public CRefactoring createRefactoring(RefactoringStatus status) throws CoreException {
ISelection selection = getSelection();
ICProject proj = getCProject();
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.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;
/**
@ -26,7 +26,7 @@ import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper;
*
* @author Tom Ball
*/
public class ExtractLocalVariableRefactoringRunner extends RefactoringRunner2 {
public class ExtractLocalVariableRefactoringRunner extends RefactoringRunner {
public ExtractLocalVariableRefactoringRunner(ICElement element, ISelection selection,
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.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.Container;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
@ -59,7 +59,7 @@ import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum;
/**
* @author Thomas Corbat
*/
public class GenerateGettersAndSettersRefactoring extends CRefactoring2 {
public class GenerateGettersAndSettersRefactoring extends CRefactoring {
private final class CompositeTypeSpecFinder extends ASTVisitor {
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.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;
/**
* @author Thomas Corbat
*/
public class GenerateGettersAndSettersRefactoringRunner extends RefactoringRunner2 {
public class GenerateGettersAndSettersRefactoringRunner extends RefactoringRunner {
public GenerateGettersAndSettersRefactoringRunner(ICElement element, ISelection selection,
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.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.ClassMemberInserter;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
@ -72,7 +72,7 @@ import org.eclipse.cdt.internal.ui.util.EditorUtility;
/**
* @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$
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.internal.ui.refactoring.CRefactoring2;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor;
/**
@ -35,7 +35,7 @@ public class HideMethodRefactoringDescriptor extends CRefactoringDescriptor {
}
@Override
public CRefactoring2 createRefactoring(RefactoringStatus status) throws CoreException {
public CRefactoring createRefactoring(RefactoringStatus status) throws CoreException {
ISelection selection = getSelection();
ICProject proj = getCProject();
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.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;
/**
* @author Guido Zgraggen IFS
*/
public class HideMethodRefactoringRunner extends RefactoringRunner2 {
public class HideMethodRefactoringRunner extends RefactoringRunner {
public HideMethodRefactoringRunner(ICElement element, ISelection selection,
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.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.utils.Checks;
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
*/
public class ImplementMethodRefactoring extends CRefactoring2 {
public class ImplementMethodRefactoring extends CRefactoring {
private ICPPASTFunctionDeclarator createdMethodDeclarator;
private ImplementMethodData data;
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.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;
/**
* @author Lukas Felber
*/
public class ImplementMethodRefactoringRunner extends RefactoringRunner2 {
public class ImplementMethodRefactoringRunner extends RefactoringRunner {
public ImplementMethodRefactoringRunner(ICElement element, ISelection selection,
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.
* All rights reserved. This program and the accompanying materials
* 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
*
* 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;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
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.
* All rights reserved. This program and the accompanying materials
* 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
*
* 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;
@ -18,12 +19,10 @@ public class Messages extends NLS {
public static String DeclaratorFinder_NoDeclarator;
public static String DeclaratorFinder_MultipleDeclarators;
public static String RefactoringJob_UndoName;
public static String ToggleFileCreator_andMove;
public static String ToggleFileCreator_CanNotCreateNewFile;
public static String ToggleFileCreator_CreateNewFile;
public static String ToggleFileCreator_CreateNewFilePrompt;
public static String ToggleFileCreator_NewImplFile;
public static String ToggleFileCreator_NoTuForSibling;
public static String ToggleFileCreator_QMark;
public static String ToggleFromClassToInHeaderStrategy_DefAndDecInsideClass;
public static String EditGroupName;
public static String ToggleFromImplementationToHeaderOrClassStrategy_CanNotCreateNewFile;

View file

@ -7,18 +7,17 @@
# http://www.eclipse.org/legal/epl-v10.html
#
# 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_NoDeclarator=Cannot work without declarator
DeclaratorFinder_MultipleDeclarators=Cannot work with multiple declarators
RefactoringJob_UndoName=Toggle function definition
ToggleFileCreator_andMove=\ and move
ToggleFileCreator_CanNotCreateNewFile=Cannot create new file change
ToggleFileCreator_CreateNewFile=Create a new file named:
ToggleFileCreator_CanNotCreateNewFile=Cannot create new file ''{0}''
ToggleFileCreator_CreateNewFilePrompt=Create a new file ''{0}'' and move {1}?
ToggleFileCreator_NewImplFile=New Implementation file?
ToggleFileCreator_NoTuForSibling=Cannot find translation unit for sibling file
ToggleFileCreator_QMark=?
ToggleFromClassToInHeaderStrategy_DefAndDecInsideClass=Definition and Declaration both inside class. Behavior is undefined.
ToggleFromImplementationToHeaderOrClassStrategy_CanNotCreateNewFile=Cannot create new File
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
* All rights reserved. This program and the accompanying materials
* 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
*
* 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;
@ -20,18 +21,19 @@ import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.IUndoManager;
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.RefactoringStatus;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringContext;
class RefactoringJob extends Job {
public final static Object FAMILY_TOGGLE_DEFINITION = new Object();
private final Refactoring refactoring;
private final ToggleRefactoring refactoring;
RefactoringJob(Refactoring refactoring) {
super("'toggle function definition' code automation"); //$NON-NLS-1$
RefactoringJob(ToggleRefactoring refactoring) {
super("Toggle Function Definition code automation"); //$NON-NLS-1$
this.refactoring = refactoring;
setPriority(Job.SHORT);
}
@ -43,6 +45,7 @@ class RefactoringJob extends Job {
@Override
protected IStatus run(IProgressMonitor monitor) {
CRefactoringContext context = new CRefactoringContext(refactoring);
IUndoManager undoManager = RefactoringCore.getUndoManager();
Change change = new NullChange();
Change undoChange = new NullChange();
@ -64,6 +67,7 @@ class RefactoringJob extends Job {
} catch (CoreException e) {
CUIPlugin.log("Failure during generation of changes.", e); //$NON-NLS-1$
} finally {
context.dispose();
undoChange.initializeValidationData(monitor);
undoManager.changePerformed(change, success);
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.
* All rights reserved. This program and the accompanying materials
* 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
*
* 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;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Shell;
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.CoreModelUtil;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.refactoring.Container;
import org.eclipse.cdt.internal.ui.refactoring.CreateFileChange;
public class ToggleFileCreator {
@ -38,8 +40,8 @@ public class ToggleFileCreator {
this.context = context;
this.ending = ending;
}
public IASTTranslationUnit loadTranslationUnit() {
public ITranslationUnit getTranslationUnit() {
String filename;
if (context.getDeclaration() != null) {
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$
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(filename));
IASTTranslationUnit result = null;
ITranslationUnit result = null;
try {
result = CoreModelUtil.findTranslationUnitForLocation(file.getFullPath(), null).getAST();
result = CoreModelUtil.findTranslationUnitForLocation(file.getFullPath(), null);
} catch (CModelException e) {
} catch (CoreException e) {
}
if (result == null) {
throw new NotSupportedException(Messages.ToggleFileCreator_NoTuForSibling);
@ -66,14 +67,17 @@ public class ToggleFileCreator {
return result;
}
public void createNewFile() {
public IFile createNewFile() {
String filename = getNewFileName();
IPath path = new Path(getPath() + filename);
try {
CreateFileChange change = new CreateFileChange(filename, new Path(getPath() + filename),
EMPTY_STRING, context.getSelectionFile().getCharset());
CreateFileChange change = new CreateFileChange(filename, path, EMPTY_STRING,
context.getSelectionFile().getCharset());
change.perform(new NullProgressMonitor());
return (IFile) change.getModifiedElement();
} 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()) {
return context.getDefaultAnswer();
}
final Container<Boolean> answer = new Container<Boolean>();
final boolean[] answer = new boolean[1];
Runnable r = new Runnable() {
@Override
public void run() {
Shell shell = CUIPlugin.getDefault().getWorkbench().getWorkbenchWindows()[0].getShell();
String functionname;
String functionName;
if (context.getDeclaration() != null) {
functionname = context.getDeclaration().getRawSignature();
functionName = context.getDeclaration().getRawSignature();
} else {
functionname = context.getDefinition().getDeclarator().getRawSignature();
functionName = context.getDefinition().getDeclarator().getRawSignature();
}
boolean createnew = MessageDialog.openQuestion(shell, Messages.ToggleFileCreator_NewImplFile,
Messages.ToggleFileCreator_CreateNewFile + getNewFileName() + Messages.ToggleFileCreator_andMove + functionname + Messages.ToggleFileCreator_QMark);
answer.setObject(createnew);
answer[0] = MessageDialog.openQuestion(shell, Messages.ToggleFileCreator_NewImplFile,
NLS.bind(Messages.ToggleFileCreator_CreateNewFilePrompt, getNewFileName(), functionName));
}
};
PlatformUI.getWorkbench().getDisplay().syncExec(r);
return answer.getObject();
return answer[0];
}
public String getIncludeStatement() {

View file

@ -7,7 +7,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* 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;
@ -33,7 +33,6 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
public class ToggleFromClassToInHeaderStrategy implements IToggleRefactoringStrategy {
protected TextEditGroup infoText = new TextEditGroup(Messages.EditGroupName);
private ToggleRefactoringContext context;
@ -61,7 +60,7 @@ public class ToggleFromClassToInHeaderStrategy implements IToggleRefactoringStra
private IASTNode getNewDefinition(IASTNode parentNamespace) {
IASTNode newDefinition = ToggleNodeHelper.getQualifiedNameDefinition(
context.getDefinition(), context.getDefinitionUnit(), parentNamespace);
context.getDefinition(), context.getDefinitionAST(), parentNamespace);
((IASTFunctionDefinition) newDefinition).setBody(
context.getDefinition().getBody().copy(CopyStyle.withLocations));
if (newDefinition instanceof ICPPASTFunctionWithTryBlock) {
@ -76,7 +75,7 @@ public class ToggleFromClassToInHeaderStrategy implements IToggleRefactoringStra
if (templdecl != null) {
newDefinition = templdecl;
}
newDefinition.setParent(context.getDefinitionUnit());
newDefinition.setParent(context.getDefinitionAST());
return newDefinition;
}
@ -84,7 +83,7 @@ public class ToggleFromClassToInHeaderStrategy implements IToggleRefactoringStra
IASTNode parentNamespace =
CPPVisitor.findAncestorWithType(context.getDefinition(), ICPPASTNamespaceDefinition.class);
if (parentNamespace == null)
parentNamespace = context.getDefinitionUnit();
parentNamespace = context.getDefinitionAST();
return parentNamespace;
}
@ -99,13 +98,13 @@ public class ToggleFromClassToInHeaderStrategy implements IToggleRefactoringStra
ModificationCollector modifications,
IASTSimpleDeclaration newDeclaration) {
ASTRewrite rewriter = modifications.rewriterForTranslationUnit(
context.getDefinitionUnit());
context.getDefinitionAST());
rewriter.replace(context.getDefinition(), newDeclaration, infoText);
return rewriter;
}
private IASTSimpleDeclaration getNewDeclaration() {
INodeFactory factory = context.getDefinitionUnit().getASTNodeFactory();
INodeFactory factory = context.getDefinitionAST().getASTNodeFactory();
IASTDeclSpecifier newDeclSpecifier =
context.getDefinition().getDeclSpecifier().copy(CopyStyle.withLocations);
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.
* All rights reserved. This program and the accompanying materials
* 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
*
* 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;
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.cdt.core.dom.ast.IASTComment;
@ -37,8 +40,8 @@ import org.eclipse.cdt.internal.ui.refactoring.utils.CPPASTAllVisitor;
public class ToggleFromImplementationToHeaderOrClassStrategy implements IToggleRefactoringStrategy {
private ToggleRefactoringContext context;
private TextEditGroup infoText;
private IASTTranslationUnit other_tu;
private ASTLiteralNode includenode;
private IASTTranslationUnit otherAst;
private ASTLiteralNode includeNode;
public ToggleFromImplementationToHeaderOrClassStrategy(ToggleRefactoringContext context) {
this.context = context;
@ -50,34 +53,34 @@ public class ToggleFromImplementationToHeaderOrClassStrategy implements IToggleR
}
@Override
public void run(ModificationCollector modifications) {
public void run(ModificationCollector modifications) throws CoreException {
newFileCheck();
ASTRewrite implast = modifications.rewriterForTranslationUnit(context.getDefinitionUnit());
List<IASTComment>leadingComments = implast.getComments(context.getDefinition(), CommentPosition.leading);
removeDefinitionFromImplementation(implast);
if (includenode != null) {
implast.insertBefore(context.getDefinitionUnit(),
context.getDefinitionUnit().getChildren()[0], includenode, infoText);
ASTRewrite implAst = modifications.rewriterForTranslationUnit(context.getDefinitionAST());
List<IASTComment>leadingComments = implAst.getComments(context.getDefinition(), CommentPosition.leading);
removeDefinitionFromImplementation(implAst);
if (includeNode != null) {
implAst.insertBefore(context.getDefinitionAST(),
context.getDefinitionAST().getChildren()[0], includeNode, infoText);
}
if (context.getDeclarationUnit() != null) {
if (context.getDeclarationAST() != null) {
addDefinitionToClass(modifications, leadingComments);
} else {
addDefinitionToHeader(modifications, leadingComments);
}
}
private void newFileCheck() {
if (context.getDeclarationUnit() == null) {
private void newFileCheck() throws CoreException {
if (context.getDeclarationAST() == null) {
if (isFreeFunction(context.getDefinition())) {
throw new NotSupportedException(Messages.ToggleFromImplementationToHeaderOrClassStrategy_CanNotToggle);
}
other_tu = context.getTUForSiblingFile();
if (other_tu == null) {
ToggleFileCreator filecreator = new ToggleFileCreator(context, ".h"); //$NON-NLS-1$
if (filecreator.askUserForFileCreation(context)) {
filecreator.createNewFile();
other_tu = filecreator.loadTranslationUnit();
includenode = new ASTLiteralNode(filecreator.getIncludeStatement() + "\n\n"); //$NON-NLS-1$
otherAst = context.getASTForPartnerFile();
if (otherAst == null) {
ToggleFileCreator fileCreator = new ToggleFileCreator(context, ".h"); //$NON-NLS-1$
if (fileCreator.askUserForFileCreation(context)) {
IFile file = fileCreator.createNewFile();
otherAst = context.getAST(file, null);
includeNode = new ASTLiteralNode(fileCreator.getIncludeStatement() + "\n\n"); //$NON-NLS-1$
} else {
throw new NotSupportedException(Messages.ToggleFromImplementationToHeaderOrClassStrategy_CanNotCreateNewFile);
}
@ -86,13 +89,13 @@ public class ToggleFromImplementationToHeaderOrClassStrategy implements IToggleR
}
private void addDefinitionToHeader(ModificationCollector modifications, List<IASTComment> leadingComments) {
ASTRewrite headerRewrite = modifications.rewriterForTranslationUnit(other_tu);
ASTRewrite headerRewrite = modifications.rewriterForTranslationUnit(otherAst);
IASTFunctionDefinition newDefinition = ToggleNodeHelper.createFunctionSignatureWithEmptyBody(
context.getDefinition().getDeclSpecifier().copy(CopyStyle.withLocations),
context.getDefinition().getDeclarator().copy(CopyStyle.withLocations),
context.getDefinition().copy(CopyStyle.withLocations));
newDefinition.setParent(other_tu);
headerRewrite.insertBefore(other_tu.getTranslationUnit(), null, newDefinition, infoText);
newDefinition.setParent(otherAst);
headerRewrite.insertBefore(otherAst.getTranslationUnit(), null, newDefinition, infoText);
restoreBody(headerRewrite, newDefinition, modifications);
for (IASTComment comment : leadingComments) {
headerRewrite.addComment(newDefinition, comment, CommentPosition.leading);
@ -101,9 +104,9 @@ public class ToggleFromImplementationToHeaderOrClassStrategy implements IToggleR
private void addDefinitionToClass(ModificationCollector modifications, List<IASTComment> leadingComments) {
ASTRewrite headerRewrite = modifications.rewriterForTranslationUnit(
context.getDeclarationUnit());
context.getDeclarationAST());
IASTFunctionDefinition newDefinition = ToggleNodeHelper.createInClassDefinition(
context.getDeclaration(), context.getDefinition(), context.getDeclarationUnit());
context.getDeclaration(), context.getDefinition(), context.getDeclarationAST());
newDefinition.setParent(getParent());
restoreBody(headerRewrite, newDefinition, modifications);
headerRewrite.replace(context.getDeclaration().getParent(), newDefinition, infoText);
@ -119,7 +122,7 @@ public class ToggleFromImplementationToHeaderOrClassStrategy implements IToggleR
if (parent != null) {
parentnode = parent;
} else {
parentnode =context.getDeclarationUnit();
parentnode =context.getDeclarationAST();
}
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;
public class ToggleFromInHeaderToClassStrategy implements IToggleRefactoringStrategy {
private TextEditGroup infoText;
private ToggleRefactoringContext context;
@ -67,8 +66,7 @@ public class ToggleFromInHeaderToClassStrategy implements IToggleRefactoringStra
IASTNode parentTemplateDeclaration =
ToggleNodeHelper.getParentTemplateDeclaration(context.getDeclaration());
if (parentTemplateDeclaration instanceof ICPPASTTemplateDeclaration) {
} else {
if (!(parentTemplateDeclaration instanceof ICPPASTTemplateDeclaration)) {
restoreLeadingComments(rewriter, newDefinition);
}
}
@ -84,7 +82,7 @@ public class ToggleFromInHeaderToClassStrategy implements IToggleRefactoringStra
}
private ASTRewrite removeDefinition(ModificationCollector modifications) {
ASTRewrite rewriter = modifications.rewriterForTranslationUnit(context.getDefinitionUnit());
ASTRewrite rewriter = modifications.rewriterForTranslationUnit(context.getDefinitionAST());
IASTNode parentRemovePoint = ToggleNodeHelper.getParentRemovePoint(context.getDefinition());
rewriter.remove(parentRemovePoint, infoText);
return rewriter;
@ -92,7 +90,7 @@ public class ToggleFromInHeaderToClassStrategy implements IToggleRefactoringStra
private IASTFunctionDefinition getNewDefinition() {
IASTFunctionDefinition newDefinition = ToggleNodeHelper.createInClassDefinition(
context.getDeclaration(), context.getDefinition(), context.getDefinitionUnit());
context.getDeclaration(), context.getDefinition(), context.getDefinitionAST());
newDefinition.setBody(context.getDefinition().getBody().copy(CopyStyle.withLocations));
if (newDefinition instanceof ICPPASTFunctionWithTryBlock) {
ICPPASTFunctionWithTryBlock newTryFun = (ICPPASTFunctionWithTryBlock) newDefinition;
@ -105,9 +103,8 @@ public class ToggleFromInHeaderToClassStrategy implements IToggleRefactoringStra
IASTNode parent = CPPVisitor.findAncestorWithType(context.getDefinition(), ICPPASTCompositeTypeSpecifier.class);
if (parent != null) {
newDefinition.setParent(parent);
}
else {
newDefinition.setParent(context.getDefinitionUnit());
} else {
newDefinition.setParent(context.getDefinitionAST());
}
return newDefinition;
}

View file

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

View file

@ -16,11 +16,6 @@ import java.util.List;
import java.util.ListIterator;
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.IASTCompositeTypeSpecifier;
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.rewrite.ASTRewrite;
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.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.CPPASTTemplateId;
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.utils.NodeHelper;
@ -82,8 +66,7 @@ public class ToggleNodeHelper extends NodeHelper {
}
}
private static ArrayList<ICPPASTConstructorChainInitializer>
getInitializerList(IASTFunctionDefinition definition) {
private static List<ICPPASTConstructorChainInitializer> getInitializerList(IASTFunctionDefinition definition) {
ArrayList<ICPPASTConstructorChainInitializer> initalizers =
new ArrayList<ICPPASTConstructorChainInitializer>();
@ -95,8 +78,7 @@ public class ToggleNodeHelper extends NodeHelper {
return initalizers;
}
static IASTSimpleDeclaration createDeclarationFromDefinition(
IASTFunctionDefinition oldDefinition) {
static IASTSimpleDeclaration createDeclarationFromDefinition(IASTFunctionDefinition oldDefinition) {
IASTDeclarator newDeclarator = oldDefinition.getDeclarator().copy(CopyStyle.withLocations);
IASTDeclSpecifier newDeclSpec = oldDefinition.getDeclSpecifier().copy(CopyStyle.withLocations);
IASTSimpleDeclaration newDeclaration = new CPPASTSimpleDeclaration(newDeclSpec);
@ -133,8 +115,7 @@ public class ToggleNodeHelper extends NodeHelper {
return newFuncDecl;
}
private static void copyInitializerList(ICPPASTFunctionDefinition newFunc,
IASTFunctionDefinition oldFunc) {
private static void copyInitializerList(ICPPASTFunctionDefinition newFunc, IASTFunctionDefinition oldFunc) {
for (ICPPASTConstructorChainInitializer initializer : getInitializerList(oldFunc)) {
initializer.setParent(newFunc);
newFunc.addMemberInitializer(initializer);
@ -168,12 +149,12 @@ public class ToggleNodeHelper extends NodeHelper {
}
private static ICPPASTTemplateDeclaration addTemplateDeclarationsInOrder(
ArrayList<ICPPASTTemplateDeclaration> templdecs, IASTFunctionDefinition newfunc) {
ListIterator<ICPPASTTemplateDeclaration> iter1 = templdecs.listIterator();
ArrayList<ICPPASTTemplateDeclaration> templDecs, IASTFunctionDefinition newFunction) {
ListIterator<ICPPASTTemplateDeclaration> iter1 = templDecs.listIterator();
ICPPASTTemplateDeclaration child = null;
while (iter1.hasNext()) {
child = iter1.next();
child.setDeclaration(newfunc);
child.setDeclaration(newFunction);
ListIterator<ICPPASTTemplateDeclaration> iter2 = iter1;
if (iter2.hasNext()) {
ICPPASTTemplateDeclaration parent = iter2.next();
@ -185,8 +166,7 @@ public class ToggleNodeHelper extends NodeHelper {
return child;
}
private static ArrayList<ICPPASTTemplateDeclaration> getAllTemplateDeclaration(
IASTNode node) {
private static ArrayList<ICPPASTTemplateDeclaration> getAllTemplateDeclaration(IASTNode node) {
ArrayList<ICPPASTTemplateDeclaration> templdecs = new ArrayList<ICPPASTTemplateDeclaration>();
while (node.getParent() != null) {
node = node.getParent();
@ -198,10 +178,10 @@ public class ToggleNodeHelper extends NodeHelper {
}
static IASTFunctionDefinition createInClassDefinition(IASTFunctionDeclarator dec,
IASTFunctionDefinition def, IASTTranslationUnit insertionunit) {
IASTFunctionDefinition def, IASTTranslationUnit insertionAst) {
IASTFunctionDeclarator declarator = dec.copy(CopyStyle.withLocations);
ICPPASTDeclSpecifier declSpec = (ICPPASTDeclSpecifier) def.getDeclSpecifier().copy(
CopyStyle.withLocations);
ICPPASTDeclSpecifier declSpec =
(ICPPASTDeclSpecifier) def.getDeclSpecifier().copy(CopyStyle.withLocations);
declSpec.setInline(false);
if (ToggleNodeHelper.isVirtual(dec)) {
declSpec.setVirtual(true);
@ -263,8 +243,8 @@ public class ToggleNodeHelper extends NodeHelper {
return qName;
}
private static Stack<IASTNode> getQualifiedNames(
IASTFunctionDeclarator declarator, IASTNode limiter, IASTNode node) {
private static Stack<IASTNode> getQualifiedNames(IASTFunctionDeclarator declarator,
IASTNode limiter, IASTNode node) {
IASTName lastName = declarator.getName();
Stack<IASTNode> nodes = new Stack<IASTNode>();
while (node.getParent() != null && node.getParent() != limiter) {
@ -294,12 +274,12 @@ public class ToggleNodeHelper extends NodeHelper {
private static ICPPASTTemplateId getTemplateParameter(IASTNode node, IASTName name) {
ICPPASTTemplateId templateID = new CPPASTTemplateId();
templateID.setTemplateName(name.copy(CopyStyle.withLocations));
for(IASTNode child : node.getChildren()) {
for (IASTNode child : node.getChildren()) {
if (child instanceof ICPPASTSimpleTypeTemplateParameter) {
ICPPASTSimpleTypeTemplateParameter tempcild = (ICPPASTSimpleTypeTemplateParameter) child;
ICPPASTSimpleTypeTemplateParameter tempChild = (ICPPASTSimpleTypeTemplateParameter) child;
CPPASTNamedTypeSpecifier namedTypeSpecifier = new CPPASTNamedTypeSpecifier();
namedTypeSpecifier.setName(tempcild.getName().copy(CopyStyle.withLocations));
namedTypeSpecifier.setName(tempChild.getName().copy(CopyStyle.withLocations));
CPPASTTypeId id = new CPPASTTypeId();
id.setDeclSpecifier(namedTypeSpecifier);
@ -309,54 +289,6 @@ public class ToggleNodeHelper extends NodeHelper {
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) {
int indexP = filename.lastIndexOf('.');
int indexS = filename.lastIndexOf('/');
@ -395,31 +327,31 @@ public class ToggleNodeHelper extends NodeHelper {
* Gets comments inside the body of a function.
* @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) {
return getBodyOnly(oldDefinition, oldUnit, modifications)
+ getCatchHandlers(oldDefinition, oldUnit, modifications);
return getBodyOnly(oldDefinition, ast, modifications)
+ getCatchHandlers(oldDefinition, ast, modifications);
}
private static String getBodyOnly(IASTFunctionDefinition oldDefinition, IASTTranslationUnit oldUnit,
private static String getBodyOnly(IASTFunctionDefinition oldDefinition, IASTTranslationUnit ast,
ModificationCollector modifications) {
String leadingComments = getCommentsAsString(getLeadingCommentsFromNode(oldDefinition.getBody(),
oldUnit, modifications));
ast, modifications));
String trailingComments = getCommentsAsString(getTrailingComments(oldDefinition.getBody(),
oldUnit, modifications));
ast, modifications));
return leadingComments + oldDefinition.getBody().getRawSignature() + trailingComments;
}
private static String getCatchHandlers(IASTFunctionDefinition oldDefinition, IASTTranslationUnit oldUnit,
private static String getCatchHandlers(IASTFunctionDefinition oldDefinition, IASTTranslationUnit ast,
ModificationCollector modifications) {
if (oldDefinition instanceof ICPPASTFunctionWithTryBlock) {
ICPPASTCatchHandler[] oldCatches =
((ICPPASTFunctionWithTryBlock) oldDefinition).getCatchHandlers();
String allCatchHandlers = ""; //$NON-NLS-1$
for (int i = 0; i < oldCatches.length; i++) {
String lead = getCommentsAsString(getLeadingCommentsFromNode(oldCatches[i], oldUnit,
String lead = getCommentsAsString(getLeadingCommentsFromNode(oldCatches[i], ast,
modifications));
String trail = getCommentsAsString(getTrailingComments(oldCatches[i], oldUnit, modifications));
String trail = getCommentsAsString(getTrailingComments(oldCatches[i], ast, modifications));
allCatchHandlers += lead + oldCatches[i].getRawSignature() + trail;
}
return allCatchHandlers;
@ -428,14 +360,14 @@ public class ToggleNodeHelper extends NodeHelper {
}
private static List<IASTComment> getLeadingCommentsFromNode(IASTNode existingNode,
IASTTranslationUnit oldUnit, ModificationCollector modifications) {
ASTRewrite rw = modifications.rewriterForTranslationUnit(oldUnit);
IASTTranslationUnit ast, ModificationCollector modifications) {
ASTRewrite rw = modifications.rewriterForTranslationUnit(ast);
return rw.getComments(existingNode, CommentPosition.leading);
}
private static List<IASTComment> getTrailingComments(IASTNode existingNode,
IASTTranslationUnit oldUnit, ModificationCollector modifications) {
ASTRewrite rw = modifications.rewriterForTranslationUnit(oldUnit);
IASTTranslationUnit ast, ModificationCollector modifications) {
ASTRewrite rw = modifications.rewriterForTranslationUnit(ast);
return rw.getComments(existingNode, CommentPosition.trailing);
}

View file

@ -12,24 +12,18 @@
******************************************************************************/
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.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ui.ide.IDE;
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.model.ICElement;
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.ModificationCollector;
@ -42,14 +36,11 @@ public class ToggleRefactoring extends CRefactoring {
private ITextSelection selection;
private IToggleRefactoringStrategy strategy;
private ToggleRefactoringContext context;
private IIndex fIndex;
public ToggleRefactoring(IFile file, ITextSelection selection, ICProject proj) {
super(file, selection, null, proj);
if (selection == null || file == null || project == null)
public ToggleRefactoring(ICElement element, ITextSelection selection, ICProject project) {
super(element, selection, project);
if (selection == null || tu.getResource() == null || project == null)
initStatus.addFatalError(Messages.ToggleRefactoring_InvalidSelection);
if (!IDE.saveAllEditors(new IResource[] { ResourcesPlugin.getWorkspace().getRoot() }, false))
initStatus.addFatalError(Messages.ToggleRefactoring_CanNotSaveFiles);
this.selection = selection;
}
@ -60,19 +51,15 @@ public class ToggleRefactoring extends CRefactoring {
pm.subTask(Messages.ToggleRefactoring_WaitingForIndexer);
prepareIndexer(pm);
pm.subTask(Messages.ToggleRefactoring_AnalyseSelection);
context = new ToggleRefactoringContext(fIndex, file, selection);
context = new ToggleRefactoringContext(refactoringContext, getIndex(), tu, selection);
strategy = new ToggleStrategyFactory(context).getAppropriateStategy();
} catch (InterruptedException e) {
} catch (NotSupportedException e) {
initStatus.addFatalError(e.getMessage());
} finally {
fIndex.releaseReadLock();
}
return initStatus;
}
private void prepareIndexer(IProgressMonitor pm) throws CoreException, InterruptedException {
private void prepareIndexer(IProgressMonitor pm) throws CoreException {
IIndexManager im = CCorePlugin.getIndexManager();
while (!im.isProjectIndexed(project)) {
im.joinIndexer(500, pm);
@ -81,14 +68,11 @@ public class ToggleRefactoring extends CRefactoring {
}
if (!im.isProjectIndexed(project))
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
protected void collectModifications(IProgressMonitor pm,
ModificationCollector modifications) throws CoreException {
protected void collectModifications(IProgressMonitor pm, ModificationCollector modifications)
throws CoreException {
pm.subTask(Messages.ToggleRefactoring_CalculateModifications);
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.
* All rights reserved. This program and the accompanying materials
* 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
*
* 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;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jface.text.ITextSelection;
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.IIndexName;
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.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.utils.TranslationUnitHelper;
public class ToggleRefactoringContext {
private IASTFunctionDefinition targetDefinition;
private IASTFunctionDeclarator targetDeclaration;
private IASTTranslationUnit targetDefinitionUnit;
private IASTTranslationUnit targetDeclarationUnit;
private IIndex index;
private IASTTranslationUnit selectionUnit;
private IFile selectionFile;
private IASTTranslationUnit targetDefinitionAST;
private IASTTranslationUnit targetDeclarationAST;
private final CRefactoringContext refactoringContext;
private final IIndex index;
private final ITranslationUnit selectionTU;
private IASTTranslationUnit selectionAST;
private IBinding binding;
private IASTName selectionName;
private boolean defaultAnswer;
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.selectionFile = file;
findSelectionUnit();
this.selectionTU = translationUnit;
findSelectionAST();
findSelectedFunctionDeclarator(selection);
findBinding();
findDeclaration();
@ -58,7 +67,7 @@ public class ToggleRefactoringContext {
}
public void findSelectedFunctionDeclarator(ITextSelection selection) {
selectionName = new DeclaratorFinder(selection, selectionUnit).getName();
selectionName = new DeclaratorFinder(selection, selectionAST).getName();
}
public void findBinding() {
@ -80,12 +89,12 @@ public class ToggleRefactoringContext {
throw new NotSupportedException(
Messages.ToggleRefactoringContext_MultipleDeclarations);
for (IIndexName iname : decnames) {
selectionUnit = getTUForNameInFile(iname);
selectionAST = getASTForIndexName(iname);
IASTName astname = IndexToASTNameHelper.findMatchingASTName(
selectionUnit, iname, index);
selectionAST, iname, index);
if (astname != null) {
targetDeclaration = findFunctionDeclarator(astname);
targetDeclarationUnit = selectionUnit;
targetDeclarationAST = selectionAST;
break;
}
}
@ -101,11 +110,11 @@ public class ToggleRefactoringContext {
throw new NotSupportedException(Messages.ToggleRefactoringContext_MultipleDefinitions);
}
for (IIndexName iname : defnames) {
IASTTranslationUnit unit = getTUForNameInFile(iname);
IASTTranslationUnit unit = getASTForIndexName(iname);
IASTName astname = IndexToASTNameHelper.findMatchingASTName(unit, iname, index);
if (astname != null) {
targetDefinition = findFunctionDefinition(astname);
targetDefinitionUnit = unit;
targetDefinitionAST = unit;
break;
}
}
@ -124,51 +133,51 @@ public class ToggleRefactoringContext {
return targetDefinition;
}
public IASTTranslationUnit getDeclarationUnit() {
return targetDeclarationUnit;
public IASTTranslationUnit getDeclarationAST() {
return targetDeclarationAST;
}
public IASTTranslationUnit getDefinitionUnit() {
return targetDefinitionUnit;
public IASTTranslationUnit getDefinitionAST() {
return targetDefinitionAST;
}
public ITranslationUnit getSelectionTU() {
return selectionTU;
}
public IFile getSelectionFile() {
return selectionFile;
return (IFile) selectionTU.getResource();
}
public IASTTranslationUnit getTUForSiblingFile() {
IASTTranslationUnit unit = getDeclarationUnit();
if (unit == null)
unit = getDefinitionUnit();
try {
return ToggleNodeHelper.getSiblingFile(getSelectionFile(), unit);
} catch (CoreException e) {
CUIPlugin.log(e);
public IASTTranslationUnit getASTForPartnerFile() throws CoreException {
ITranslationUnit tu =
SourceHeaderPartnerFinder.getPartnerTranslationUnit(selectionTU, refactoringContext);
if (tu == null)
return null;
}
return refactoringContext.getAST(tu, null);
}
private void findSelectionUnit() {
try {
selectionUnit = TranslationUnitHelper.loadTranslationUnit(selectionFile, true);
} catch (Exception e) {
}
if (selectionUnit == null)
private void findSelectionAST() throws OperationCanceledException, CoreException {
selectionAST = refactoringContext.getAST(selectionTU, null);
if (selectionAST == null)
throw new NotSupportedException(Messages.ToggleRefactoringContext_NoTuFound);
}
private IASTTranslationUnit getTUForNameInFile(IIndexName iname)
private IASTTranslationUnit getASTForIndexName(IIndexName indexName)
throws CModelException, CoreException {
if (isSameFileAsInTU(iname)) {
return selectionUnit;
if (isSameFileAsInTU(indexName)) {
return selectionAST;
}
IPath path = new Path(iname.getFileLocation().getFileName());
return TranslationUnitHelper.loadTranslationUnit(path.toString(), true);
ITranslationUnit tu = CoreModelUtil.findTranslationUnitForLocation(
indexName.getFile().getLocation(), null);
if (tu == null)
return null;
return refactoringContext.getAST(tu, null);
}
private boolean isSameFileAsInTU(IIndexName iname) {
return iname.getFileLocation().getFileName().equals(
selectionUnit.getFileLocation().getFileName());
private boolean isSameFileAsInTU(IIndexName indexName) {
return indexName.getFileLocation().getFileName().equals(
selectionAST.getFileLocation().getFileName());
}
private IASTFunctionDeclarator findFunctionDeclarator(IASTNode node) {
@ -197,4 +206,13 @@ public class ToggleRefactoringContext {
public boolean isSettedDefaultAnswer() {
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.
* All rights reserved. This program and the accompanying materials
* 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
*
* 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;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.text.ITextSelection;
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.internal.ui.refactoring.RefactoringRunner;
import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper;
/**
* 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 {
private ToggleRefactoring refactoring;
public ToggleRefactoringRunner(IFile file, ITextSelection selection,
ICElement element, IShellProvider shellProvider, ICProject project) {
super(file, selection, element, shellProvider, project);
refactoring = new ToggleRefactoring(file, selection, project);
public ToggleRefactoringRunner(ICElement element, ITextSelection selection,
IShellProvider shellProvider, ICProject project) {
super(element, selection, shellProvider, project);
}
@Override
public void run() {
Job[] jobs = Job.getJobManager().find(RefactoringJob.FAMILY_TOGGLE_DEFINITION);
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;
}
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();
}
}

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;
public class ToggleStrategyFactory {
private ToggleRefactoringContext context;
public ToggleStrategyFactory(ToggleRefactoringContext context) {
@ -27,7 +26,7 @@ public class ToggleStrategyFactory {
public IToggleRefactoringStrategy getAppropriateStategy() {
if (context.getDefinition() == null)
throw new NotSupportedException(Messages.ToggleStrategyFactory_NoDefinitionFound);
if (!context.getDefinitionUnit().isHeaderUnit())
if (!context.getDefinitionAST().isHeaderUnit())
return new ToggleFromImplementationToHeaderOrClassStrategy(context);
if (isInClassSituation())
return new ToggleFromClassToInHeaderStrategy(context);
@ -40,7 +39,7 @@ public class ToggleStrategyFactory {
private boolean isinHeaderSituation() {
return (context.getDefinition() != null)
&& (context.getDefinitionUnit().isHeaderUnit());
&& (context.getDefinitionAST().isHeaderUnit());
}
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.
* All rights reserved. This program and the accompanying materials
* 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
*
* 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;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection;
@ -20,8 +20,7 @@ import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.ui.CUIPlugin;
/**
@ -31,11 +30,8 @@ import org.eclipse.cdt.ui.CUIPlugin;
* Order of execution is: constructor, init, selectionChanged, run
*/
public class TogglingActionDelegate implements IWorkbenchWindowActionDelegate {
private IWorkbenchWindow window;
private TextSelection selection;
private ICProject project;
private IFile file;
@Override
public void init(IWorkbenchWindow window) {
@ -45,36 +41,27 @@ public class TogglingActionDelegate implements IWorkbenchWindowActionDelegate {
@Override
public void selectionChanged(IAction action, ISelection selection) {
boolean isTextSelection = selection != null
&& selection instanceof TextSelection;
boolean isTextSelection = selection != null && selection instanceof TextSelection;
action.setEnabled(isTextSelection);
if (!isTextSelection)
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();
}
@Override
public void run(IAction action) {
if (!isWorkbenchReady())
return;
new ToggleRefactoringRunner(file, selection, project, window, project).run();
}
private boolean isWorkbenchReady() {
IWorkbenchPage activePage = window.getActivePage();
if (activePage == null)
return false;
return;
IEditorPart editor = activePage.getActiveEditor();
if (editor == null || editor.getEditorInput() == null)
return false;
IWorkingCopy wc = CUIPlugin.getDefault().getWorkingCopyManager()
.getWorkingCopy(editor.getEditorInput());
if (wc == null)
return false;
project = wc.getCProject();
file = (IFile) wc.getResource();
return project != null && file != null;
return;
ITranslationUnit tu =
CUIPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(editor.getEditorInput());
if (tu == null || tu.getResource() == null)
return;
new ToggleRefactoringRunner(tu, selection, window, tu.getCProject()).run();
}
@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.
* All rights reserved. This program and the accompanying materials
* 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
*
* 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;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
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.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.refactoring.togglefunction.ToggleRefactoringRunner;
/**
*
* @since 5.3
* @author Emanuel Graf IFS
*
* @noextend This class is not intended to be subclassed by clients.
*/
public class ToggleFunctionAction extends RefactoringAction {
private ICProject project;
private IFile file;
public ToggleFunctionAction() {
super(Messages.ToggleFunctionAction_label);
@ -46,30 +41,16 @@ public class ToggleFunctionAction extends RefactoringAction {
}
@Override
public void run(IShellProvider shellProvider, IWorkingCopy wc,
ITextSelection s) {
IResource res = wc.getResource();
if (isWorkbenchReady(wc) && res instanceof IFile) {
new ToggleRefactoringRunner(file, s, project, shellProvider, project).run();
}
}
private boolean isWorkbenchReady(IWorkingCopy wc) {
try {
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;
}
public void run(IShellProvider shellProvider, IWorkingCopy wc, ITextSelection selection) {
if (wc == null || wc.getResource() == null)
return;
IWorkbenchPage activePage = CUIPlugin.getActivePage();
if (activePage == null)
return;
IEditorPart editor = activePage.getActiveEditor();
if (editor == null || editor.getEditorInput() == null)
return;
new ToggleRefactoringRunner(wc, selection, shellProvider, wc.getCProject()).run();
}
@Override
@ -77,5 +58,4 @@ public class ToggleFunctionAction extends RefactoringAction {
super.updateSelection(elem);
setEnabled(false);
}
}