Debian Codegraph @

llvm-project/clang-tools-extra/clang-tidy/google/GlobalNamesInHeadersCheck.cpp

raw
1 //===--- GlobalNamesInHeadersCheck.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 "GlobalNamesInHeadersCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
13 #include "clang/Lex/Lexer.h"
14
15 using namespace clang::ast_matchers;
16
17 namespace clang::tidy::google::readability {
18
19 GlobalNamesInHeadersCheck::GlobalNamesInHeadersCheck(StringRef Name,
20 ClangTidyContext *Context)
21 : ClangTidyCheck(Name, Context),
22 RawStringHeaderFileExtensions(Options.getLocalOrGlobal(
23 "HeaderFileExtensions", utils::defaultHeaderFileExtensions())) {
24 if (!utils::parseFileExtensions(RawStringHeaderFileExtensions,
25 HeaderFileExtensions,
26 utils::defaultFileExtensionDelimiters())) {
27 this->configurationDiag("Invalid header file extension: '%0'")
28 << RawStringHeaderFileExtensions;
29 }
30 }
31
32 void GlobalNamesInHeadersCheck::storeOptions(
33 ClangTidyOptions::OptionMap &Opts) {
34 Options.store(Opts, "HeaderFileExtensions", RawStringHeaderFileExtensions);
35 }
36
37 void GlobalNamesInHeadersCheck::registerMatchers(
38 ast_matchers::MatchFinder *Finder) {
39 Finder->addMatcher(decl(anyOf(usingDecl(), usingDirectiveDecl()),
40 hasDeclContext(translationUnitDecl()))
41 .bind("using_decl"),
42 this);
43 }
44
45 void GlobalNamesInHeadersCheck::check(const MatchFinder::MatchResult &Result) {
46 const auto *D = Result.Nodes.getNodeAs<Decl>("using_decl");
47 // If it comes from a macro, we'll assume it is fine.
48 if (D->getBeginLoc().isMacroID())
49 return;
50
51 // Ignore if it comes from the "main" file ...
52 if (Result.SourceManager->isInMainFile(
53 Result.SourceManager->getExpansionLoc(D->getBeginLoc()))) {
54 // unless that file is a header.
55 if (!utils::isSpellingLocInHeaderFile(
56 D->getBeginLoc(), *Result.SourceManager, HeaderFileExtensions))
57 return;
58 }
59
60 if (const auto *UsingDirective = dyn_cast<UsingDirectiveDecl>(D)) {
61 if (UsingDirective->getNominatedNamespace()->isAnonymousNamespace()) {
62 // Anonymous namespaces inject a using directive into the AST to import
63 // the names into the containing namespace.
64 // We should not have them in headers, but there is another warning for
65 // that.
66 return;
67 }
68 }
69
70 diag(D->getBeginLoc(),
71 "using declarations in the global namespace in headers are prohibited");
72 }
73
74 } // namespace clang::tidy::google::readability