Вопрос

I'm trying to write a custom C++ refactoring using Eclipse Indigo and CDT 8.0.2. The CDT provides a class, CRefactoring2, which obtains the AST and provides hooks. But this class is in an internal package, so I assume it will change in future versions of Eclipse, and that I shouldn't subclass it.

Is there an external API (within the CDT; I don't particularly want to write all the AST-getting code from scratch) I can use to get ASTs and declare my own Eclipse CDT refactorings?

Это было полезно?

Решение

Thank you Jeff for sharing your method of obtaining the AST. I looked through my code and I have a different method of getting the AST but it also uses public API. I would like to post that method as well:

// Assume there is a variable, 'file', of type IFile
ICProject cProject = CoreModel.getDefault().create(file.getProject() );
ITranslationUnit unit = CoreModelUtil.findTranslationUnit(file);
if (unit == null) {
    unit = CoreModel.getDefault().createTranslationUnitFrom(cProject, file.getLocation() );
}
IASTTranslationUnit ast = null;
IIndex index = null;
try {
    index = CCorePlugin.getIndexManager().getIndex(cProject);
} catch (CoreException e) {
    ...
}

try {
    index.acquireReadLock();
    ast = unit.getAST(index, ITranslationUnit.AST_PARSE_INACTIVE_CODE);
    if (ast == null) {
        throw new IllegalArgumentException(file.getLocation().toPortableString() + ": not a valid C/C++ code file");
    }
} catch (InterruptedException e) {
    ...
} catch (CoreException e) {
    ...
} finally {
    index.releaseReadLock();
}

Mine is a little more involved; I basically kept changing things until stuff started working consistently 100% of the time. I have not any more to add on what you said about the actual refactoring.

Edit: To clarify: this is the safest way I have so far of getting the translation unit.

Другие советы

For information on accessing and manipulating an AST, see here (Note that this code is written for Java. The CDT version of the ASTVisitor base class is found at org.eclipse.cdt.core.dom.ast.ASTVisitor).

The code we ended up writing to access a C++ AST from a file was essentially this:

import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.core.resources.IFile;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;

private IASTTranslationUnit getASTFromFile(IFile file) {
    ITranslationUnit tu = (ITranslationUnit) CoreModel.getDefault().create(file);
    return tu.getAST();
}

As for defining and registering a new refactoring, you'll want to look at this article.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top