Reputation: 298
I have a c code like this
int x;
x = 5;
I used eclipse cdt to generate the AST, and traverse on it, so this is the code of the traversed class
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);
}
}
what I want to visit the node that only has assignation(Initialization) and get the reference of declaration node for that varaiable.
Upvotes: 1
Views: 469
Reputation: 13
like the answer above, but you can do it easiser using IASTTranslationUnit.getReferences(IBinding)
which will give you all reference of IASTName
to your IBinding
, you can find the statement use parent
method.
Upvotes: 0
Reputation: 52967
I'm not sure how VisitorUtil
works (it's not from the CDT code), but I assume it gives you a way to access the the found node. So:
Given the IASTExpressionStatement
node that was found, use IASTExpression.getExpression()
to get the contained expression.
See if it's an IASTBinaryExpression
, and that is getOperator()
is IASTBinaryExpression.op_assign
.
Use IASTBinaryExpression.getOperand1()
to get the assignment expression's left subexpression. Check that it's an IASTIdExpression
, and get the variable it names via IASTIdExpression.getName()
.
Now that you have the name, use IASTName.resolveBinding()
to get the variable's binding. This is the variable's representation in the semantic program model.
To find the variable's definition, use IASTTranslationUnit.getDefinitionsInAST(IBinding)
if you only want it to look in the current file, or IASTTranslationUnit.getDefinitions(IBinding)
if you want it to look in included header files as well (the latter requires the project to be indexed). The IASTTranslationUnit
can be obtained from any IASTNode
via IASTNode.getTranslationUnit()
.
Upvotes: 2