如何使用Clang AST工具在代码库中查找移动构造函数? [英] How to find move constructors in codebase using Clang AST tools?

查看:1428
本文介绍了如何使用Clang AST工具在代码库中查找移动构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关注了此问题的评论:我如何使用Clang AST工具在C ++代码库中查找移动构造函数? (仅查找定义/声明)

Following up a comment from this question: how can I find move constructors in C++ codebase using Clang AST tools? (find definitions / declarations only)

推荐答案

Clang AST匹配器现在提供了 isMoveConstructor matcher。下面是一个示例程序:

The Clang AST matcher now provides this functionality with the isMoveConstructor matcher. Here's an example program:

#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中找到移动构造函数

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

这篇关于如何使用Clang AST工具在代码库中查找移动构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆