跟随this question的评论:如何使用Clang AST工具在C ++代码库中找到移动构造函数? (仅查找定义/声明)
答案 0 :(得分: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
找到了一个移动构造函数