c++ - 如何使用 Clang AST 工具在代码库中查找移动构造函数?

标签 c++ clang abstract-syntax-tree move-constructor

跟进来自 this question 的评论:如何使用 Clang AST 工具在 C++ 代码库中找到移动构造函数? (仅查找定义/声明)

最佳答案

Clang AST 匹配器现在通过 isMoveConstructor 匹配器提供此功能。这是一个示例程序:

#include <iostream>

#include "clang/AST/AST.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Refactoring.h"

static llvm::cl::OptionCategory ToolingSampleCategory("move constructor finder");

struct MoveCtorHandler : public clang::ast_matchers::MatchFinder::MatchCallback {
public:
    virtual void run(clang::ast_matchers::MatchFinder::MatchResult const& result) override {
        using namespace clang;
        // reject things from include files
        ASTContext *ctx = result.Context;
        const CXXConstructorDecl *decl = result.Nodes.getStmtAs<CXXConstructorDecl>("moveCtor");
        auto loc = decl->getLocation();
        if (!ctx->getSourceManager().isInMainFile(loc)) {
            return;
        }

        std::cout << "found a move constructor at "
                  << loc.printToString(ctx->getSourceManager())
                  << std::endl;
    }
};

int main(int argc, char const **argv) {
    using namespace clang;
    using namespace clang::tooling;
    using namespace clang::ast_matchers;

    CommonOptionsParser opt(argc, argv, ToolingSampleCategory);
    RefactoringTool     tool(opt.getCompilations(), opt.getSourcePathList());

    MatchFinder  finder;

    // set up callbacks
    MoveCtorHandler       move_ctor_handler;
    finder.addMatcher(constructorDecl(isMoveConstructor()).bind("moveCtor"),
                      &move_ctor_handler);

    if (int result = tool.run(newFrontendActionFactory(&finder).get())) {
        return result;
    }

    return 0;
}

应用于以下输入时:

#include <vector>

struct foo {
    foo() {}
    foo(foo && other) : v_(std::move(other.v_)) {}
private:
    std::vector<int>  v_;
};

int main() {
}

它产生输出:

found a move constructor at xxx.cpp:5:5

关于c++ - 如何使用 Clang AST 工具在代码库中查找移动构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24706053/

相关文章:

c++ - MFC CFormView OnKeyDown 事件未触发

c++ - 将 GUI 附加到命令行工具

c++ g++ llvm-clang 编译器分析

java - 使用 eclipse AST 检查 Java 代码片段

c++ - pData1 和 pData2 有什么区别,构建如下

android - 将 clang 的 objcopy 与输入文件一起使用返回 : "File format not recognized"

c++ - 使用 clang Libtooling API 打印完全限定类型的参数 (ParmVarDecl) 或字段 (FieldDecl)

objective-c - 如何从 Objective-C 代码中提取 AST?

abstract-syntax-tree - 从另一个程序获取 Perl 6 文件的 QAST

c++ - 如果目标应用程序在 C++ 中崩溃,则无法使用 LVM_GETITEMTEXT