how to get integer variable name and its value fro

2020-07-22 17:05发布

问题:

I have following code in an overridden method VisitBinaryOperator() for clang:

Expr* lhs = E->getLHS();  
Expr* rhs = E->getRHS();  

I want to extract integer variable name and its value from expression lhs and rhs.

Say I have x = 10;, then I want to get identifier x from lhs and 10 from rhs.
If I have x = x + 10; then I want to get identifier x from lhs and x + 10 as sub expression from rhs

Also for type I am getting this : int identifier when I dump lhs type

QualType type_lhs = lhs->getType();  
type_lhs->dump();  

How this can be done for clang?

回答1:

Use dyn_cast to determine what kind of expression you have on the LHS:

if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(lhs)) {
  // It's a reference to a declaration...
  if (VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
    // It's a reference to a variable (a local, function parameter, global, or static data member).
     std::cout << "LHS is " << VD->getQualifiedNameAsString() << std::endl;
  }
}

You'll need more complex code if you want to handle other expression forms on the LHS. If you want to deal with arbitrary code there, take a look at RecursiveASTVisitor.

To evaluate the value of the right-hand side (assuming it's something that Clang can evaluate, like 10, not like x + 10), use one of Expr's Evaluate* functions:

llvm::APSInt Result;
if (rhs->EvaluateAsInt(Result, ASTContext)) {
  std::cout << "RHS has value " << Result.toString(10) << std::endl;
}


标签: integer clang