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

1

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?

Sharondasharos answered 1/3, 2021 at 20:28 Comment(0)
N
3

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")))))))))))
Nocturne answered 1/3, 2021 at 22:36 Comment(3)
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.Sharondasharos
weak_ptr only has one template argument.Nocturne
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.Nocturne

© 2022 - 2024 — McMap. All rights reserved.