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 ast_matchers {
19 AST_MATCHER(NamespaceDecl, isAnonymousNamespace) {
20   return Node.isAnonymousNamespace();
21 }
22 } // namespace ast_matchers
23 
24 namespace tidy {
25 namespace google {
26 namespace build {
27 
28 void UnnamedNamespaceInHeaderCheck::registerMatchers(
29     ast_matchers::MatchFinder *Finder) {
30   Finder->addMatcher(
31       namespaceDecl(isAnonymousNamespace()).bind("anonymousNamespace"), this);
32 }
33 
34 void
35 UnnamedNamespaceInHeaderCheck::check(const MatchFinder::MatchResult &Result) {
36   SourceManager *SM = Result.SourceManager;
37   const auto *N = Result.Nodes.getNodeAs<NamespaceDecl>("anonymousNamespace");
38   SourceLocation Loc = N->getLocStart();
39   if (!Loc.isValid())
40     return;
41 
42   // Look if we're inside a header, check for common suffixes only.
43   // TODO: Allow configuring the set of file extensions.
44   StringRef FileName = SM->getPresumedLoc(Loc).getFilename();
45   if (FileName.endswith(".h") || FileName.endswith(".hh") ||
46       FileName.endswith(".hpp") || FileName.endswith(".hxx"))
47     diag(Loc, "do not use unnamed namespaces in header files.");
48 }
49 
50 } // namespace build
51 } // namespace google
52 } // namespace tidy
53 } // namespace clang
54