我在 clang 的覆盖方法 VisitBinaryOperator()
中有以下代码:
Expr* lhs = E->getLHS();
Expr* rhs = E->getRHS();
我想从表达式 lhs
和 rhs
中提取整型变量名及其值。
假设我有 x = 10;
,那么我想从 lhs
和 10
中获取标识符 x
来自 rhs
。
如果我有 x = x + 10;
那么我想从 lhs
和 x + 10
中获取标识符 x
作为 rhs
同样对于类型,当我转储 lhs
类型
: int identifier
QualType type_lhs = lhs->getType();
type_lhs->dump();
如何为 clang 做到这一点?
最佳答案
使用 dyn_cast
确定您在 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;
}
}
如果您想在 LHS 上处理其他表达式形式,您将需要更复杂的代码。如果您想在那里处理任意代码,请查看 RecursiveASTVisitor
。
要计算右侧的值(假设它是 Clang 可以计算的值,例如 10
,而不是 x + 10
),请使用 Expr
的 Evaluate*
函数:
llvm::APSInt Result;
if (rhs->EvaluateAsInt(Result, ASTContext)) {
std::cout << "RHS has value " << Result.toString(10) << std::endl;
}
关于integer - 如何从 clang 中的 Expr* 获取整数变量名称及其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13189848/