【问题标题】:How do you print the conditional statement of an IfStmt in Clang?如何在 Clang 中打印 IfStmt 的条件语句?
【发布时间】:2015-08-11 01:53:33
【问题描述】:

我正在为 clang 编译器开发一个插件,并且想要字符串形式的 if 语句的条件表达式。也就是说,给定:

if (a + b + c > 10)
    return;

以及对代表它的IfStmt节点的引用,我想获得字符串“a + b + c > 10”。

我怀疑这是不可能的,但如果有人有任何见解,将不胜感激。

【问题讨论】:

    标签: clang clang++ llvm-clang


    【解决方案1】:

    提取 IfStmt 的条件部分,获取它的开始和结束位置,并使用它来查询词法分析器以获取底层源代码。

    using namespace clang;
    
    class IfStmtVisitor
      : public RecursiveASTVisitor<IfStmtVisitor> {
      SourceManager &sm; // Initialize me!
      CompilerInstance &ci;  // Initialize me!
    
      bool VisitIfStmt(IfStmt *stmt) {
        Expr *expr = stmt->getCond();
        bool invalid;
    
        CharSourceRange conditionRange =
            CharSourceRange::getTokenRange(expr->getLocStart(), expr->getLocEnd());
        StringRef str =
            Lexer::getSourceText(conditionRange, sm, ci.getLangOpts(), &invalid);
        if (invalid) {
          return false;
        }
        llvm::outs() << "Condition: " << str << "\n";
        return true;
      }
    };
    

    输入源:

    bool f(int a, int b, int c)
    {
      if (a + b + c > 10)
        return true;
      return false;
    }
    

    输出:

    Condition string: a + b + c > 10
    

    【讨论】:

      【解决方案2】:

      我相信您可能想尝试查看Stmt 中定义的printPretty 函数,IfStmt 继承自该函数。希望这能让你接近你想要的。

      【讨论】:

        猜你喜欢
        • 2021-06-04
        • 1970-01-01
        • 2021-06-11
        • 2017-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多