1 //===--- UnnamedNamespaceInHeaderCheck.cpp - clang-tidy ---------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "UnnamedNamespaceInHeaderCheck.h" 11 #include "clang/AST/ASTContext.h" 12 #include "clang/ASTMatchers/ASTMatchFinder.h" 13 #include "clang/ASTMatchers/ASTMatchers.h" 14 15 using namespace clang::ast_matchers; 16 17 namespace clang { 18 namespace tidy { 19 namespace google { 20 namespace build { 21 22 void UnnamedNamespaceInHeaderCheck::registerMatchers( 23 ast_matchers::MatchFinder *Finder) { 24 // Only register the matchers for C++; the functionality currently does not 25 // provide any benefit to other languages, despite being benign. 26 if (getLangOpts().CPlusPlus) 27 Finder->addMatcher(namespaceDecl(isAnonymous()).bind("anonymousNamespace"), 28 this); 29 } 30 31 void 32 UnnamedNamespaceInHeaderCheck::check(const MatchFinder::MatchResult &Result) { 33 SourceManager *SM = Result.SourceManager; 34 const auto *N = Result.Nodes.getNodeAs<NamespaceDecl>("anonymousNamespace"); 35 SourceLocation Loc = N->getLocStart(); 36 if (!Loc.isValid()) 37 return; 38 39 // Look if we're inside a header, check for common suffixes only. 40 // TODO: Allow configuring the set of file extensions. 41 StringRef FileName = SM->getPresumedLoc(Loc).getFilename(); 42 if (FileName.endswith(".h") || FileName.endswith(".hh") || 43 FileName.endswith(".hpp") || FileName.endswith(".hxx")) 44 diag(Loc, "do not use unnamed namespaces in header files"); 45 } 46 47 } // namespace build 48 } // namespace google 49 } // namespace tidy 50 } // namespace clang 51