【问题标题】:Matching a <= BinaryOperator using Clang's ASTvisitor使用 Clang 的 ASTvisitor 匹配 <= BinaryOperator
【发布时间】:2020-08-06 06:15:44
【问题描述】:

我有以下AST,我想使用 BinaryOperator 访问者访问&lt;=

| |   `-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,我不知道如何从 Expr *E 向下遍历到 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;
  }

【问题讨论】:

    标签: compiler-construction clang abstract-syntax-tree semantics visitor-pattern


    【解决方案1】:

    您能否再扩展一下代码?如何构造访问者,如何遍历代码?

    以下访问者应该为您完成这项工作:

    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) 的内容。

    【讨论】:

    • 谢谢亚历克斯。如何检查我的 dyn_cast(parent) 何时返回 null?并非所有课程都有IgnoreImpCasts(),而且很多时候我遇到了由nullptrl引起的面部段错误。例如,vectorLoopConditionVisitor(S, dyn_cast&lt;BinaryOperator&gt;(Fst-&gt;getCond())) 的 dyn_cast 正弦我想通过资金 BO 而不是 Expr
    • dyn_cast 返回有效指针或空指针,因此只需检查 if (dyn_cast&lt;BinaryOperator&gt;(something)) 就可以了。
    • 抱歉,如果我的二元运算符 RHS 有一个名为 get_loop_b32(var) 的内置函数 CallExpr -&gt; ImplicitCastExpr -&gt; DeclRefExpr,请告诉我。我还能沿着这条路匹配它吗?我好像没有这样做
    • 会感谢您对我的这个问题的看法:stackoverflow.com/questions/64050621/…
    猜你喜欢
    • 2019-08-03
    • 2016-09-22
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 2020-10-02
    • 1970-01-01
    相关资源
    最近更新 更多