compiler-construction - 使用 Clang 的 ASTvisitor 匹配 <= BinaryOperator
问题描述
我有以下内容AST
,我想<=
使用 BinaryOperator 访问者访问:
| | `-ForStmt 0xfcb1fd8 <line:7:2, line:14:2>
| | |-DeclStmt 0xfcb1680 <line:7:7, col:20>
| | | `-VarDecl 0xfcb15e8 <col:7, col:19> col:17 used i 'uint16_t':'unsigned short' cinit
| | | `-ImplicitCastExpr 0xfcb1668 <col:19> 'uint16_t':'unsigned short' <IntegralCast>
| | | `-IntegerLiteral 0xfcb1648 <col:19> 'int' 0
| | |-BinaryOperator 0xfcb1a28 <col:22, col:55> 'bool' '<='
| | | |-ImplicitCastExpr 0xfcb19f8 <col:22> 'int' <IntegralCast>
BinaryOperator继承自Expr::BinaryOperator
,我不太清楚如何从 a 向下遍历Expr *E
到 a BinaryOperator *BO
:
static bool vectorLoopConditionVisitor(Sema &S, BinaryOperator *BO){
if (!BO){
// error
}
if (!BO->isAssignmentOp() && //need a condition to match with "<=" ){
// error
}
return false;
}
static bool vectorLoopVisitor(Sema &S, Stmt *St, uint32_t Depth) {
ForStmt *Fst = dyn_cast<ForStmt>(St);
// ...
vectorLoopConditionVisitor(S, dyn_cast<BinaryOperator>(Fst->getCond()));
// this is most certainly wrong as it returns a null pointer and segfault
//...
vectorLoopBodyVisitor(S, Fst->getBody(), Depth);
return false;
}
解决方案
你能把代码再扩展一点吗?你如何构造访问者以及如何遍历代码?
以下访问者应该为您完成这项工作:
class BinaryVisitor : public clang::RecursiveASTVisitor<BinaryVisitor> {
public:
bool VisitBinaryOperator(clang::BinaryOperator *binaryOperator) {
if (binaryOperator->getOpcode() != clang::BinaryOperator::Opcode::BO_LE) {
return true;
}
// Handle the '<=' matching here
return true;
}
};
/// ...
BinaryVisitor visitor;
visitor.TraverseDecl(someDecl);
此访问者将检查每一个BinaryOperaror
,并将跳过任何不“小于”( clang::BinaryOperator::Opcode::BO_LE
) 的内容。
推荐阅读
- python - 在熊猫中按十一个多列分组
- node.js - 是否可以将 DynamoDb 中的扫描数据保存到 Lambda 函数中的变量中?
- python - 临时变量与数组元素的性能,哪个更快,什么时候?
- jquery - 使用 jQuery 显示一个选项
- javascript - 子组件中的第一次单击在父组件 React 中未定义
- postgresql - 为什么这个是空的?
- c - 在 Docker 容器中使用 Cmake 交叉编译 SDL
- latex - Latex 中的文字不均匀,虽然我使用了 ragged2e 包
- flutter - Flutter 应用程序在发布版本中无法正常工作
- typescript - Vue 3 如何传递一个可选的布尔道具?