c++libclangclang-ast-matchers

How to reuse a clang AST matcher?


I'm using AST matchers from lib clang to ensures that some code is present in the body of a foo function.

So all my matchers starts like this:

auto matcher1 = functiondecl(hasname("foo"),
                 hasdescendant(...))));


auto matcher2 = functiondecl(hasname("foo"),
                 hasdescendant(...))));

I would like to deduplicate the functiondecl(hasname("foo"), hasdescendant(...) part. So for example if I want to find a constructor, I can write

auto ctor = inFoo(cxxConstructorExpr());

It seems that I could write my own matcher using AST_MATCHER_P, but I can't figure out how.

Can you show me an example of custom matcher to deduplicate the beginning of my matchers?


Solution

  • You can simply use

    template <class T> 
    auto inFoo(T && f) 
    { 
      return functiondecl(hasname("foo"), hasdescendant(std::forward<T>(f))); 
    }