使用 ASTMatcher 获取至少两个相同访问说明符的 类

Get classes with at least two same access specifiers with ASTMatcher

当 class 中有两个或更多相似的访问说明符时,我需要在 C++ 代码中捕获案例。 假设有两个 classes

class A{
public:
    int b;
public:
    int a;
}

class B{
public:
    int a;
}

如何用 ASTMatcher 匹配 class A(因为它有两个'public')而不是 class B?

此匹配器获取 'public' 声明:

accessSpecDecl(
  isPublic(),
  hasAncestor(cxxRecordDecl().bind("crd"))).bind("asd")

在回调 class 中,您可以跟踪匹配器针对给定结构声明获得的命中数,例如使用 std::map<string,int>:

struct report_public : public MatchCallback{
  using map_t = std::map<string,int>;
  using map_it = map_t::iterator;

  map_t count;

  void run(MatchResult const & result){
    AccessSpecDecl const * asd = result.Nodes.getNodeAs<AccessSpecDecl>("asd");
    CXXRecordDecl const * crd = result.Nodes.getNodeAs<CXXRecordDecl>("crd");
    if(asd && crd){
      string const struct_name = crd->getNameAsString();
      map_it it = count.find(struct_name);
      if(it != count.end()) count[struct_name]++;
      else count[struct_name] = 1;
    }
    else { /* error handling */}
    return;
  } // run
}; // report_public