我是使用astmatcher的新手,并遵循教程中的代码-https://github.com/peter-can-talk/cppnow-2017。在这里,可以使用以下命令运行工具clang-Variables:
cd code/clang-variables
docker run -it -v $PWD:/home clang
root@5196c095092d:/home# ./clang-variables test.cpp -- -std=c++14
而不是test.cpp文件,如果我使用另一个源文件,那么我会收到以下错误:
fatal error: 'stddef.h' file not found
#include <stddef.h>
^~~~~~~~~~
我了解我的源文件具有需要包括的这些标头文件。我试图将它们包括在makefile中,如下所示,但仍然存在错误:
clang-variables: $(TARGET).cpp
$(CXX) $(HEADERS) $(LDFLAGS) $(CXXFLAGS) $(TARGET).cpp $(LIBS) -o $(TARGET) -I$(START_DIR)/source -I$(HOME_ROOT)/extern/include
编译时没有错误。因此,我想知道,是否可以向Astmatcher提及"包含文件"作为参数?请在下面找到代码:
// Clang includes
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Type.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
// LLVM includes
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
// Standard includes
#include <memory>
#include <string>
#include <vector>
namespace Mutator {
/// Callback class for clang-variable matches.
class MatchHandler : public clang::ast_matchers::MatchFinder::MatchCallback {
public:
using MatchResult = clang::ast_matchers::MatchFinder::MatchResult;
/// Handles the matched variable.
///
/// Checks if the name of the matched variable is either empty or prefixed
/// with `clang_` else emits a diagnostic and FixItHint.
void run(const MatchResult& Result) {
const clang::VarDecl* Variable =
Result.Nodes.getNodeAs<clang::VarDecl>("clang");
const llvm::StringRef Name = Variable->getName();
if (Name.empty() || Name.startswith("clang_")) return;
clang::DiagnosticsEngine& Engine = Result.Context->getDiagnostics();
const unsigned ID =
Engine.getCustomDiagID(clang::DiagnosticsEngine::Warning,
"found mutating variable");
/// Hint to the user to prefix the variable with 'clang_'.
const clang::FixItHint FixIt =
clang::FixItHint::CreateInsertion(Variable->getLocation(), "precision & accuracy mutation");
Engine.Report(Variable->getLocation(), ID).AddFixItHint(FixIt);
}
}; // namespace Mutator
/// Dispatches the ASTMatcher.
class Consumer : public clang::ASTConsumer {
public:
/// Creates the matcher for clang variables and dispatches it on the TU.
void HandleTranslationUnit(clang::ASTContext& Context) override {
using namespace clang::ast_matchers; // NOLINT(build/namespaces)
const auto Matcher = declaratorDecl(
isExpansionInMainFile(),
hasType(asString("int"))
).bind("clang");
/*
// clang-format off
const auto Matcher = varDecl(
isExpansionInMainFile(),
hasType(isConstQualified()), // const
hasInitializer(
hasType(cxxRecordDecl(
isLambda(), // lambda
has(functionTemplateDecl( // auto
has(cxxMethodDecl(
isNoThrow(), // noexcept
hasBody(compoundStmt(hasDescendant(gotoStmt()))) // goto
)))))))).bind("clang");
// clang-format on
*/
MatchHandler Handler;
MatchFinder MatchFinder;
MatchFinder.addMatcher(Matcher, &Handler);
MatchFinder.matchAST(Context);
}
};
/// Creates an `ASTConsumer` and logs begin and end of file processing.
class Action : public clang::ASTFrontendAction {
public:
using ASTConsumerPointer = std::unique_ptr<clang::ASTConsumer>;
ASTConsumerPointer CreateASTConsumer(clang::CompilerInstance& Compiler,
llvm::StringRef) override {
return std::make_unique<Consumer>();
}
bool BeginSourceFileAction(clang::CompilerInstance& Compiler,
llvm::StringRef Filename) override {
llvm::errs() << "Processing " << Filename << "nn";
return true;
}
void EndSourceFileAction() override {
llvm::errs() << "nFinished processing file ...n";
}
};
} // namespace Mutator
namespace {
llvm::cl::OptionCategory ToolCategory("clang-variables options");
llvm::cl::extrahelp MoreHelp(R"(
Finds all Const Lambdas, that take an Auto parameter, are declared Noexcept
and have a Goto statement inside, e.g.:
const auto lambda = [] (auto) noexcept {
bool done = true;
flip: done = !done;
if (!done) goto flip;
}
)");
llvm::cl::extrahelp
CommonHelp(clang::tooling::CommonOptionsParser::HelpMessage);
} // namespace
auto main(int argc, const char* argv[]) -> int {
using namespace clang::tooling;
CommonOptionsParser OptionsParser(argc, argv, ToolCategory);
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
const auto Action = newFrontendActionFactory<Mutator::Action>();
return Tool.run(Action.get());
}
我感谢任何帮助。
clang工具实例化编译器对象以产生AST。与从分布安装的编译器(在构建项目时被调用(不同,此编译器对象未配置为标头路径信息。
(至少(有两种添加该信息的方法:使用标准标头路径配置编译器,或在编译数据库中添加路径。
首先,您可以使用ClangTool::appendArgumentsAdjuster()
方法以编程方式添加路径。这是coarct中apps/funclister.cc的示例(https://github.com/lanl/coarct(:
ClangTool tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
// add header search paths to compiler
ArgumentsAdjuster ardj1 =
getInsertArgumentAdjuster(corct::clang_inc_dir1.c_str());
ArgumentsAdjuster ardj2 =
getInsertArgumentAdjuster(corct::clang_inc_dir2.c_str());
tool.appendArgumentsAdjuster(ardj1);
tool.appendArgumentsAdjuster(ardj2);
if(verbose_compiler){
ArgumentsAdjuster ardj3 = getInsertArgumentAdjuster("-v");
tool.appendArgumentsAdjuster(ardj3);
}
carct在几个步骤中定义了包含目录:首先,顶级cmakelists.txt猜测目录在哪里,并将这些信息放入宏中;其次,lib/utilities.h以编译器标志的形式将宏放入clang_inc_dir1/2
字符串(即clang_inc_dir1="-I/path1/to/headers"
(;然后,像Funclister.cc这样的客户将这些用作AppendArgumentsAdjuster((的参数。
添加编译器搜索路径的第二种方法是更改编译数据库中的编译器命令。如果您使用的是CMAKE,请将set(CMAKE_EXPORT_COMPILE_COMMANDS TRUE)
添加到顶级cmakelists.txt。这应该在构建目录中产生一个称为Compile_commands.json的编译数据库文件。每个源文件都有一个条目;该条目将包括
"command":"compiler command line here"
您可以将-I/path/to/headers
添加到Compile命令中,以获取要运行工具的任何文件。然后,您将使用
clang-variables test.cpp -p /path/to/compile_commands.json
如果您的项目不使用cmake,则在此处介绍数据库文件的结构:https://clang.llvm.org/docs/jsoncompilationdatabase.html。