[clang] [clang-tools-extra] [clang-tidy] Avoid processing declarations in system headers (PR #128150)

Carlos Galvez via cfe-commits cfe-commits at lists.llvm.org
Wed Mar 12 03:05:48 PDT 2025


================
@@ -35,19 +35,41 @@ AST_POLYMORPHIC_MATCHER_P(
                              Builder) != Args.end();
 }
 
+bool isStdOrPosixImpl(const DeclContext *Ctx) {
+  if (!Ctx->isNamespace())
+    return false;
+
+  const auto *ND = cast<NamespaceDecl>(Ctx);
+  if (ND->isInline()) {
+    return isStdOrPosixImpl(ND->getParent());
+  }
+
+  if (!ND->getParent()->getRedeclContext()->isTranslationUnit())
+    return false;
+
+  const IdentifierInfo *II = ND->getIdentifier();
+  return II && (II->isStr("std") || II->isStr("posix"));
+}
+
+AST_MATCHER(Decl, isInStdOrPosixNS) {
+  for (const auto *Ctx = Node.getDeclContext(); Ctx; Ctx = Ctx->getParent()) {
+    if (isStdOrPosixImpl(Ctx))
+      return true;
+  }
+  return false;
+}
+
----------------
carlosgalvezp wrote:

The following existing unit test is correctly handled without warnings:
```cpp
namespace foobar {
  namespace std {
    int bar;
  }
}
```
This is due to this line above:
```
  if (!ND->getParent()->getRedeclContext()->isTranslationUnit())
    return false;
```
E.g. if the namespace is not immediately below the translation unit (i.e. not a top-level namespace) then we bail out. I suppose the name of the matcher could be improved to reflect that.


https://github.com/llvm/llvm-project/pull/128150


More information about the cfe-commits mailing list