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::(StringRef Name, |
20 | ClangTidyContext *Context) |
21 | : ClangTidyCheck(Name, Context), |
22 | HeaderFileExtensions(Context->getHeaderFileExtensions()) {} |
23 | |
24 | void GlobalNamesInHeadersCheck::( |
25 | ast_matchers::MatchFinder *Finder) { |
26 | Finder->addMatcher(NodeMatch: decl(anyOf(usingDecl(), usingDirectiveDecl()), |
27 | hasDeclContext(InnerMatcher: translationUnitDecl())) |
28 | .bind(ID: "using_decl" ), |
29 | Action: this); |
30 | } |
31 | |
32 | void GlobalNamesInHeadersCheck::(const MatchFinder::MatchResult &Result) { |
33 | const auto *D = Result.Nodes.getNodeAs<Decl>(ID: "using_decl" ); |
34 | // If it comes from a macro, we'll assume it is fine. |
35 | if (D->getBeginLoc().isMacroID()) |
36 | return; |
37 | |
38 | // Ignore if it comes from the "main" file ... |
39 | if (Result.SourceManager->isInMainFile( |
40 | Loc: Result.SourceManager->getExpansionLoc(Loc: D->getBeginLoc()))) { |
41 | // unless that file is a header. |
42 | if (!utils::isSpellingLocInHeaderFile( |
43 | Loc: D->getBeginLoc(), SM&: *Result.SourceManager, HeaderFileExtensions)) |
44 | return; |
45 | } |
46 | |
47 | if (const auto *UsingDirective = dyn_cast<UsingDirectiveDecl>(Val: D)) { |
48 | if (UsingDirective->getNominatedNamespace()->isAnonymousNamespace()) { |
49 | // Anonymous namespaces inject a using directive into the AST to import |
50 | // the names into the containing namespace. |
51 | // We should not have them in headers, but there is another warning for |
52 | // that. |
53 | return; |
54 | } |
55 | } |
56 | |
57 | diag(Loc: D->getBeginLoc(), |
58 | Description: "using declarations in the global namespace in headers are prohibited" ); |
59 | } |
60 | |
61 | } // namespace clang::tidy::google::readability |
62 | |