1

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

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

+0

那你最后做了什么? – 2013-06-26 02:16:34

回答

1

谢谢杰夫分享你获得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(); 
} 

矿是多一点涉及;我基本上一直在不停地变化,直到所有事情始终如一地开始工作。我没有什么可以补充你所说的关于实际重构的内容。

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

1

有关访问和操作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

相关问题