2

我正在尝试使用 Eclipse Indigo 和 CDT 8.0.2 编写自定义 C++ 重构。CDT 提供了一个类 ,CRefactoring2它获取 AST 并提供挂钩。但是这个类在一个内部包中,所以我认为它会在未来的 Eclipse 版本中发生变化,并且我不应该对它进行子类化。

是否有一个外部 API(在 CDT 内;我不想从头开始编写所有获取 AST 的代码)我可以用来获取 AST 并声明我自己的 Eclipse CDT 重构?

4

2 回答 2

1

感谢 Jeff 分享您获取 AST 的方法。我查看了我的代码,我有另一种获取 AST 的方法,但它也使用公共 API。我也想发布该方法:

// 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();
}

我的参与度更高一些;我基本上一直在改变事情,直到东西开始 100% 地持续工作。我没有更多的补充你所说的关于实际重构的内容。

编辑:澄清一下:这是迄今为止我获得翻译单元的最安全的方法。

于 2013-07-19T14:09:45.153 回答
1

有关访问和操作 AST 的信息,请参见此处(请注意,此代码是为 Java 编写的。ASTVisitor 基类的 CDT 版本位于org.eclipse.cdt.core.dom.ast.ASTVisitor)。

我们最终编写的用于从文件访问 C++ AST 的代码基本上是这样的:

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();
}

至于定义和注册一个新的重构,你会想看看这篇文章

于 2013-07-17T04:28:58.867 回答