查找变量声明引用抽象语法树eclipse cdt C代码
我有这样的c代码查找变量声明引用抽象语法树eclipse cdt C代码,eclipse,eclipse-cdt,abstract-syntax-tree,Eclipse,Eclipse Cdt,Abstract Syntax Tree,我有这样的c代码 intx; x=5 我使用EclipseCDT生成AST,并对其进行遍历,因此这是被遍历类的代码 public class RuleChk extends AbstractRule { public RuleChk(IASTTranslationUnit ast) { super("RuleChk", false, ast); shouldVisitDeclarations = true; shouldVisitParam
intx;
x=5代码>
我使用EclipseCDT生成AST,并对其进行遍历,因此这是被遍历类的代码
public class RuleChk extends AbstractRule {
public RuleChk(IASTTranslationUnit ast) {
super("RuleChk", false, ast);
shouldVisitDeclarations = true;
shouldVisitParameterDeclarations = true;
}
@Override
public int visit(IASTSimpleDeclaration simpleDecl) {
//if this node has init, e.g: x = 5, do business
if(VisitorUtil.containNode(simpleDecl, CASTExpressionStatement){
// Now I have the x = 5 node,
// I want to get the reference node of it's declaration
// I mean (int x;) node
IASTNode declNode = ?????
}
return super.visit(parameterDeclaration);
}
}
我想访问的是只具有赋值(初始化)的节点,并获取该变量的声明节点的引用。我不确定VisitorUtil
是如何工作的(它不是来自CDT代码),但我假设它为您提供了访问找到的节点的方法。因此:
- 给定找到的
IASTExpressionStatement
节点,使用IASTExpression.getExpression()
获取包含的表达式
- 查看它是否是一个
IASTBinaryExpression
,即getOperator()
是IASTBinaryExpression.op\u assign
- 使用
IASTBinaryExpression.getoperan1()
获取赋值表达式的左子表达式。检查它是否是一个iastideexpression
,并通过iastideexpression.getName()
获取它命名的变量
- 现在已经有了名称,请使用
IASTName.resolveBinding()
获取变量的绑定。这是该变量在语义程序模型中的表示形式
- 若要查找变量的定义,请使用
IASTTranslationUnit.getDefinitionsAst(IBinding)
如果您只希望它在当前文件中查找,或使用IASTTranslationUnit.getDefinitions(IBinding)
如果您希望它也在包含的头文件中查找(后者要求对项目进行索引)。可以通过IASTNode.getTranslationUnit()
从任何IASTNode
获取IASTTranslationUnit
我以前做过,但是我需要获取名称的声明说明符,对于上面的示例,我想返回(int)@MostafaHassan,假设声明在同一个文件中,getDefinitionInAST()
将为您提供一个IASTName
。您可以检查周围的AST以找到decl说明符。例如,名称的父级是IASTDeclarator
,其父级是IASTSimpleDeclaration
,然后您可以使用IASTSimpleDeclaration.getDeclSpecifier()
获取decl说明符。