我正在编译在Clang 3.5
计算机上使用Ubuntu 13.04 x86
的程序。我想获得在cpp项目中声明的所有变量。这是我写的: -
// Declares clang::SyntaxOnlyAction.
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
// Declares llvm::cl::extrahelp.
#include "llvm/Support/CommandLine.h"
#include "clang/AST/DeclCXX.h"
#include <iostream>
#include <vector>
using namespace clang::tooling;
using namespace llvm;
using namespace clang::ast_matchers;
using namespace clang;
using namespace std;
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
static cl::extrahelp MoreHelp("\nMore help text...");
static cl::OptionCategory MyToolCategory("My Tool Category");
internal::Matcher<Decl> fields = fieldDecl().bind("field");
internal::Matcher<Decl> params = parmVarDecl().bind("param");
internal::Matcher<Decl> vars = varDecl().bind("var");
class VarDeclPrinter : public MatchFinder::MatchCallback {
public:
int counter;
virtual void run(const MatchFinder::MatchResult &Result) {
const Decl* dec;
if(const FieldDecl* field = Result.Nodes.getNodeAs<FieldDecl>("field"))
llvm::outs() << "Member Variable: " << field->getName() << "\t\t"
<< field->getParent()->getQualifiedNameAsString() << "\n";
if(const ParmVarDecl* param = Result.Nodes.getNodeAs<ParmVarDecl>("param"))
llvm::outs() << "Argument Variable: " << param->getName() << "\t\t"
<< ((CXXMethodDecl*)(param->getParentFunctionOrMethod()))->getQualifiedNameAsString() << "\n";
if(const VarDecl* var = Result.Nodes.getNodeAs<VarDecl>("var"))
llvm::outs() << "Local Variable: " << var->getName() << "\t\t"
<< ((CXXMethodDecl*)(var->getParentFunctionOrMethod()))->getQualifiedNameAsString() << "\n";
counter++;
//llvm::outs() << "Variable count: " << counter << "\n";
//ASTContext* Context = Result.Context;
}
};
int main(int argc, const char **argv) {
CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
VarDeclPrinter VarDeclCallback;
MatchFinder Finder;
Finder.addMatcher(fields, &VarDeclCallback);
Finder.addMatcher(params, &VarDeclCallback);
Finder.addMatcher(vars, &VarDeclCallback);
return Tool.run(newFrontendActionFactory(&Finder));
}
当我尝试运行此程序时,我得到分段错误(可能在我将var->getParentFunctionOrMethod()
投射到CXXMethodDecl*
时)。如果它是局部变量,我想要声明此变量的方法名称。任何人都可以告诉我错误的原因是什么?或者什么是更好的方法来获取变量的方法名称?
答案 0 :(得分:1)
我得到了解决方案。这是因为我试图获取方法名称,即使var
不在方法内。这是解决方案: -
if(const VarDecl* var = Result.Nodes.getNodeAs<VarDecl>("var")) {
llvm::outs() << "Local Variable: " << var->getName() << "\t\t";
if(var->isFunctionOrMethodVarDecl())
llvm::outs() << ((CXXMethodDecl*)(var->getParentFunctionOrMethod()))->getQualifiedNameAsString();
llvm::outs() << "\n";
}