clang-tools 23.0.0git
UseAnonymousNamespaceCheck.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/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13
14using namespace clang::ast_matchers;
15
16namespace clang::tidy::misc {
17namespace {
18AST_POLYMORPHIC_MATCHER_P(isInHeaderFile,
19 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
20 VarDecl),
21 const FileExtensionsSet *, HeaderFileExtensions) {
23 Node.getBeginLoc(), Finder->getASTContext().getSourceManager(),
24 *HeaderFileExtensions);
25}
26
27AST_MATCHER(FunctionDecl, isMemberFunction) {
28 return isa<CXXMethodDecl>(&Node);
29}
30AST_MATCHER(VarDecl, isStaticDataMember) { return Node.isStaticDataMember(); }
31} // namespace
32
36
38 Finder->addMatcher(
39 functionDecl(isStaticStorageClass(),
40 unless(anyOf(isInHeaderFile(&getHeaderFileExtensions()),
41 isInAnonymousNamespace(), isMemberFunction())))
42 .bind("x"),
43 this);
44 Finder->addMatcher(
45 varDecl(isStaticStorageClass(),
46 unless(anyOf(isInHeaderFile(&getHeaderFileExtensions()),
47 isInAnonymousNamespace(), isStaticLocal(),
48 isStaticDataMember(), hasType(isConstQualified()))))
49 .bind("x"),
50 this);
51}
52
53void UseAnonymousNamespaceCheck::check(const MatchFinder::MatchResult &Result) {
54 if (const auto *MatchedDecl = Result.Nodes.getNodeAs<NamedDecl>("x")) {
55 const StringRef Type = isa<VarDecl>(MatchedDecl) ? "variable" : "function";
56 diag(MatchedDecl->getLocation(),
57 "%0 %1 declared 'static', move to anonymous namespace instead")
58 << Type << MatchedDecl;
59 }
60}
61
62} // namespace clang::tidy::misc
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
UseAnonymousNamespaceCheck(StringRef Name, ClangTidyContext *Context)
AST_MATCHER(BinaryOperator, isRelationalOperator)
bool isExpansionLocInHeaderFile(SourceLocation Loc, const SourceManager &SM, const FileExtensionsSet &HeaderFileExtensions)
Checks whether expansion location of Loc is in header file.
llvm::SmallSet< llvm::StringRef, 5 > FileExtensionsSet