Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

clang

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?

like image 266
Prakhar Mishra Avatar asked Dec 19 '25 19:12

Prakhar Mishra


2 Answers

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.

like image 98
Prakhar Mishra Avatar answered Dec 22 '25 10:12

Prakhar Mishra


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.

like image 27
Oak Avatar answered Dec 22 '25 11:12

Oak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!