Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the parameters of a method call from a clang match callback

Tags:

llvm

clang

I'm adapting the Clang tool-template (as described here) to search for a particular method call in my code. In order to later rewrite that call, I would like to get the type of the parameters the method was called with, as well as the type of the object the method was called on.

I managed to find a matcher that calls back the following:

class AddListenerPrinter : public MatchFinder::MatchCallback
{
  public :
  virtual void run(const MatchFinder::MatchResult &Result) {
    if (const auto *FS = Result.Nodes.getNodeAs<clang::MemberExpr>("ListeningBound"))
    {
      FS->dump();
    }
  }
};

which prints out:

MemberExpr 0x7fb05b07b948 '<bound member function type>' .addListener 0x7fb05b077670
`-MemberExpr 0x7fb05b07b918 'class MyCore' lvalue ->mCore 0x7fb05b078e30
  `-CXXThisExpr 0x7fb05b07b900 'class MyComponent *' this

Now I can't find any way to retrieve the type of the object the method was called on (here class MyCore) or the type of the method argument (here class MyComponent).

How can I do this?

like image 800
adanselm Avatar asked Feb 19 '14 17:02

adanselm


1 Answers

I found the answer by browsing the code of the existing matchers.

Using matcher = memberCallExpr( callee(methodDecl(hasName("addListener"))) )

I was able to retrieve a CXXMemberCallExpr node. Then getting the type of the object the method was called on:

// FS is the CXXMemberCallExpr
// Prints out the type of x in x.method()
llvm::outs() << FS->getRecordDecl()->getName();

and the method parameters are accessible through FS->getArg(n).

Bottom line is: Find the CXX object that contains what you're looking for first (e.g. which class has methods to access function arguments?), then find the matcher that will return the same type of object in ASTMatchers.h.

Hoping this can help anybody else with the same problem.

like image 62
adanselm Avatar answered Oct 29 '22 16:10

adanselm