CLang 3.5 LibTooling: getting file name of a variable in clang::VarDecl

南笙酒味 提交于 2019-12-24 02:33:39

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!