如何从clang中的Expr *获取整数变量名称及其值 [英] how to get integer variable name and its value from Expr* in clang
问题描述
我在重写的方法中有以下代码 VisitBinaryOperator()
for clang:
Expr * lhs = E-> getLHS();
Expr * rhs = E-> getRHS();
我想从表达式中提取整数变量名称及其值 lhs
和
rhs
。
说我有 x = 10;
,那么我想获得标识符 x
从 lhs
和 10
code>。
如果我有 x = x + 10;
那么我想获得标识符 x
lhs
和 x + 10
作为子表达式从 rhs
此外,当我转储:int identifier
> lhs type
QualType type_lhs = lhs-> getType();
type_lhs-> dump();
如何为clang做到这一点?
if(DeclRefExpr * DRE = dyn_cast< DeclRefExpr>(lhs)){
//它是一个声明的引用...
if(VarDecl * VD = dyn_cast< VarDecl>(DRE-> getDecl())){
//它是对变量(局部,函数参数,全局或静态数据成员)的引用。
std :: cout<< LHS是< VD-> getQualifiedNameAsString()<< std :: endl;
}
}
处理LHS上的其他表达式。如果要处理任意代码,请查看 RecursiveASTVisitor
。
要评估(假设它是Clang可以评估的东西,例如 10
,不像 x + 10
), Expr
的之一函数
llvm :: APSInt结果;
if(rhs-> EvaluateAsInt(Result,ASTContext)){
std :: cout< RHS具有值< Result.toString(10)<< std :: endl;
}
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?
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;
}
这篇关于如何从clang中的Expr *获取整数变量名称及其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!