1 //===--- UnnamedNamespaceInHeaderCheck.cpp - clang-tidy ---------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "UnnamedNamespaceInHeaderCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
13 
14 using namespace clang::ast_matchers;
15 
16 namespace clang {
17 namespace tidy {
18 namespace google {
19 namespace build {
20 
21 UnnamedNamespaceInHeaderCheck::UnnamedNamespaceInHeaderCheck(
22     StringRef Name, ClangTidyContext *Context)
23     : ClangTidyCheck(Name, Context),
24       RawStringHeaderFileExtensions(Options.getLocalOrGlobal(
25           "HeaderFileExtensions", utils::defaultHeaderFileExtensions())) {
26   if (!utils::parseHeaderFileExtensions(RawStringHeaderFileExtensions,
27                                         HeaderFileExtensions, ',')) {
28     llvm::errs() << "Invalid header file extension: "
29                  << RawStringHeaderFileExtensions << "\n";
30   }
31 }
32 
33 void UnnamedNamespaceInHeaderCheck::storeOptions(
34     ClangTidyOptions::OptionMap &Opts) {
35   Options.store(Opts, "HeaderFileExtensions", RawStringHeaderFileExtensions);
36 }
37 
38 void UnnamedNamespaceInHeaderCheck::registerMatchers(
39     ast_matchers::MatchFinder *Finder) {
40   // Only register the matchers for C++; the functionality currently does not
41   // provide any benefit to other languages, despite being benign.
42   if (getLangOpts().CPlusPlus)
43     Finder->addMatcher(namespaceDecl(isAnonymous()).bind("anonymousNamespace"),
44                        this);
45 }
46 
47 void UnnamedNamespaceInHeaderCheck::check(
48     const MatchFinder::MatchResult &Result) {
49   const auto *N = Result.Nodes.getNodeAs<NamespaceDecl>("anonymousNamespace");
50   SourceLocation Loc = N->getBeginLoc();
51   if (!Loc.isValid())
52     return;
53 
54   if (utils::isPresumedLocInHeaderFile(Loc, *Result.SourceManager,
55                                        HeaderFileExtensions))
56     diag(Loc, "do not use unnamed namespaces in header files");
57 }
58 
59 } // namespace build
60 } // namespace google
61 } // namespace tidy
62 } // namespace clang
63