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