【问题标题】:How to get Stmt class object from Expr object in Clang如何从 Clang 中的 Expr 对象获取 Stmt 类对象
【发布时间】:2013-09-18 09:49:34
【问题描述】:

我正在编写一个用于在 C 代码中插入断言的 clang 插件。我已经实现了一个类来访问每个一元运算符并检查它是否是指针解引用。如果是,我想为它插入一个 NULL 指针断言检查。但是我被卡住了,因为我无法弄清楚如何在 Clang 中获取包含 Expr 对象的 Stmt 对象。

这是我的代码,它检测断言,但位置完全错误(即在指针取消引用之后。我想在包含取消引用的语句之前执行此操作。

bool MyRecursiveASTVisitor::VisitUnaryOperator(UnaryOperator *E){
    if (E->getOpcode() == UO_Deref ){
        Expr *e1 = E->getSubExpr();
        SourceLocation SL = E->getLocEnd();
        Rewrite.InsertText(SL, "assert(", true, true);
        Rewrite.InsertText(SL, Rewrite.ConvertToString(e1), true, true);
        Rewrite.InsertText(SL, " != NULL);", true, true);
    }
    return true;
}

【问题讨论】:

    标签: c clang llvm instrumentation


    【解决方案1】:

    ASTContext::getParents怎么样?

    您还可以使用ParentMap 类构建部分父映射。

    【讨论】:

    • 在这种情况下如何获取 ASTContext 对象?我试图使 Context 成为我的类的成员,但它说 = 运算符是私有的,所以我不能为 ASTContext 类型的变量分配任何值。
    • @anirudh:使用对ASTContext的常量引用
    • @anirudh:另外,您可以从TranslationUnitDeclSema 等一堆地方获取ASTContext 引用。在clang 源代码树中Grep 获取getASTContext
    • getParents 返回所有祖先。说,语句是a = b;,我在二元运算符=的visitor方法中,我想知道它的父语句是a = b;,我该怎么做呢?
    猜你喜欢
    • 1970-01-01
    • 2010-11-17
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 2022-12-15
    • 2011-04-08
    相关资源
    最近更新 更多