【问题标题】:Creating custom CDT refactorings without using internal classes在不使用内部类的情况下创建自定义 CDT 重构
【发布时间】:2013-02-10 02:24:39
【问题描述】:

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

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

【问题讨论】:

  • 那么你最后做了什么?

标签: eclipse eclipse-plugin eclipse-cdt automated-refactoring


【解决方案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% 地持续工作。关于实际的重构,我没有更多的补充。

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

【讨论】:

    【解决方案2】:

    有关访问和操作 AST 的信息,请参阅 here(请注意,此代码是为 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();
    }
    

    至于定义和注册新的重构,您需要查看this article

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 2023-04-07
      • 2017-12-07
      • 2013-08-16
      • 1970-01-01
      相关资源
      最近更新 更多