0

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

4

1 回答 1

2

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() {
}

它产生输出:

在 xxx.cpp:5:5 找到了一个移动构造函数

于 2015-08-18T21:23:44.233 回答