clang-tools 24.0.0git
GlobalNamesInHeadersCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/ASTMatchers/ASTMatchers.h"
13#include "clang/Lex/Lexer.h"
14
15using namespace clang::ast_matchers;
16
18
22
24 ast_matchers::MatchFinder *Finder) {
25 Finder->addMatcher(decl(anyOf(usingDecl(), usingDirectiveDecl()),
26 hasDeclContext(translationUnitDecl()))
27 .bind("using_decl"),
28 this);
29}
30
31void GlobalNamesInHeadersCheck::check(const MatchFinder::MatchResult &Result) {
32 const auto *D = Result.Nodes.getNodeAs<Decl>("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 unless that file is a header.
38 if (Result.SourceManager->isInMainFile(
39 Result.SourceManager->getExpansionLoc(D->getBeginLoc())) &&
40 !utils::isSpellingLocInHeaderFile(D->getBeginLoc(), *Result.SourceManager,
41 getHeaderFileExtensions()))
42 return;
43
44 if (const auto *UsingDirective = dyn_cast<UsingDirectiveDecl>(D);
45 UsingDirective &&
46 UsingDirective->getNominatedNamespace()->isAnonymousNamespace()) {
47 // Anonymous namespaces inject a using directive into the AST to import
48 // the names into the containing namespace.
49 // We should not have them in headers, but there is another warning for
50 // that.
51 return;
52 }
53
54 diag(D->getBeginLoc(),
55 "using declarations in the global namespace in headers are prohibited");
56}
57
58} // namespace clang::tidy::google::readability
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
GlobalNamesInHeadersCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
bool isSpellingLocInHeaderFile(SourceLocation Loc, const SourceManager &SM, const FileExtensionsSet &HeaderFileExtensions)
Checks whether spelling location of Loc is in header file.