Search code examples
c++clangabstract-syntax-treeclang-ast-matchers

clang-query: Examining name of template parameter of a function argument's type


I have a big project, and a slew of C++ class member functions of the form:

Return CClass::MemberFunction(
   Arg1 arg1,
   //...
   std::weak_ptr<IMemberFunctionListenerInterface> listener) {
//...
}

I'm trying to write a matcher that finds functions like these, which have arguments whose types have the string "Listener" in their name.

I can find functions with arguments whose types have "weak_ptr" in their name:

clang-query> m cxxMethodDecl(hasAnyParameter(hasType(cxxRecordDecl(matchesName("weak_ptr")))))

This matches the above function just fine. But if I change "weak_ptr" to "Listener", the function is no longer matched. I'm guessing this is because it is the name of a template parameter to the std::weak_ptr class template.

I've tried a lot of different variations of this query, but I haven't hit on the one that matches the functions I'm interested in.

Any pointers?


Solution

  • On one line:

    clang-query> m cxxMethodDecl(hasAnyParameter(hasType(allOf(cxxRecordDecl(matchesName("weak_ptr")), classTemplateSpecializationDecl(hasTemplateArgument(0, templateArgument(refersToType(hasDeclaration(cxxRecordDecl(matchesName(".*Listener")))))))))))
    

    clang-formatted:

    cxxMethodDecl(hasAnyParameter(
        hasType(allOf(cxxRecordDecl(matchesName("weak_ptr")),
                      classTemplateSpecializationDecl(hasTemplateArgument(
                          0, templateArgument(refersToType(hasDeclaration(
                                 cxxRecordDecl(matchesName(".*Listener")))))))))))