clang-tools 19.0.0git
GlobalNamesInHeadersCheck.cpp
Go to the documentation of this file.
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
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
15using namespace clang::ast_matchers;
16
18
20 ClangTidyContext *Context)
21 : ClangTidyCheck(Name, Context),
22 HeaderFileExtensions(Context->getHeaderFileExtensions()) {}
23
25 ast_matchers::MatchFinder *Finder) {
26 Finder->addMatcher(decl(anyOf(usingDecl(), usingDirectiveDecl()),
27 hasDeclContext(translationUnitDecl()))
28 .bind("using_decl"),
29 this);
30}
31
32void GlobalNamesInHeadersCheck::check(const MatchFinder::MatchResult &Result) {
33 const auto *D = Result.Nodes.getNodeAs<Decl>("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 Result.SourceManager->getExpansionLoc(D->getBeginLoc()))) {
41 // unless that file is a header.
43 D->getBeginLoc(), *Result.SourceManager, HeaderFileExtensions))
44 return;
45 }
46
47 if (const auto *UsingDirective = dyn_cast<UsingDirectiveDecl>(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(D->getBeginLoc(),
58 "using declarations in the global namespace in headers are prohibited");
59}
60
61} // namespace clang::tidy::google::readability
const FunctionDecl * Decl
llvm::SmallString< 256U > Name
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
GlobalNamesInHeadersCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
bool isSpellingLocInHeaderFile(SourceLocation Loc, SourceManager &SM, const FileExtensionsSet &HeaderFileExtensions)
Checks whether spelling location of Loc is in header file.