6

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?

Eric Niebler
  • 5,927
  • 2
  • 29
  • 43

1 Answers1

2

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")))))))))))
pepsiman
  • 56
  • 2
  • Awesome, thanks! The `hasDeclaration` was the bit that I never tried in all my blind flailings. And replacing `hasTemplateArgument(0, ...)` with `hasAnyTemplateArgument(...)` gets me the rest of the way. – Eric Niebler Mar 01 '21 at 23:03
  • 1
    `weak_ptr` only has one template argument. – pepsiman Mar 02 '21 at 08:28
  • 1
    clang-query's context-sensitive tab-completion is helpful for seeing what you can match next, and use `anything()` to check you're on the right track. – pepsiman Mar 02 '21 at 08:40