问题
I am having a clang::VarDecl object. I want to fetch the file name/location of the variable (at least if they are global). I also skimmed through a question:-
How to get location of variable name in clang::VarDecl
But I guess it is not about file name in which variables are declared. I also referred to
http://clang.llvm.org/doxygen/classclang_1_1SourceLocation.html
There isn't any function which may return file name. Can anybody tell me how to get it?
回答1:
You're supposed to use SourceManager to get concrete data out of a SourceLocation. In particular, take a look at the SourceManager::getFilename(SourceLocation) method.
You can get an instance of a SourceManager by using CompilerInstance::getSourceManager.
回答2:
There was no need to create a SourceManager object. MatchFinder::MatchResult::Context gives me the ASTContext* on which I can call getSourceManager to get the SourceManager object. The rest is as we were doing previously.
class VarDeclPrinter : public MatchFinder::MatchCallback {
public:
virtual void run(const MatchFinder::MatchResult &Result) {
SourceManager &srcMgr = Result.Context->getSourceManager();
if(const VarDecl* var = Result.Nodes.getNodeAs<VarDecl>("var")) {
if(var->isFunctionOrMethodVarDecl()) {
cout << setw(20) << left << "Local Variable: " << var->getName().str() << "\t\t";
cout << ((CXXMethodDecl*)(var->getParentFunctionOrMethod()))->getQualifiedNameAsString() << "\t";
cout << "--" << srcMgr.getFilename(var->getLocation()).str();
cout << "\n";
}
if(var->hasExternalStorage()) {
cout << setw(20) << left << "External Variable: " << var->getName().str() << "\t\t";
cout << "--" << srcMgr.getFilename(var->getLocation()).str();
cout << "\n";
}
else if(var->hasGlobalStorage()) {
cout << setw(20) << left << "Global Variable: " << var->getName().str() << "\t\t";
cout << "--" << srcMgr.getFilename(var->getLocation()).str();
cout << "\n";
}
}
}
};
Thanks for your help, @Oak.
来源:https://stackoverflow.com/questions/20658987/clang-3-5-libtooling-getting-file-name-of-a-variable-in-clangvardecl