1 //===--- UseAnonymousNamespaceCheck.cpp - clang-tidy ----------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "UseAnonymousNamespaceCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 using namespace clang::ast_matchers
;
15 namespace clang::tidy::misc
{
17 AST_POLYMORPHIC_MATCHER_P(isInHeaderFile
,
18 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl
,
20 FileExtensionsSet
, HeaderFileExtensions
) {
21 return utils::isExpansionLocInHeaderFile(
22 Node
.getBeginLoc(), Finder
->getASTContext().getSourceManager(),
23 HeaderFileExtensions
);
26 AST_MATCHER(FunctionDecl
, isMemberFunction
) {
27 return llvm::isa
<CXXMethodDecl
>(&Node
);
29 AST_MATCHER(VarDecl
, isStaticDataMember
) { return Node
.isStaticDataMember(); }
32 UseAnonymousNamespaceCheck::UseAnonymousNamespaceCheck(
33 StringRef Name
, ClangTidyContext
*Context
)
34 : ClangTidyCheck(Name
, Context
),
35 HeaderFileExtensions(Context
->getHeaderFileExtensions()) {}
37 void UseAnonymousNamespaceCheck::registerMatchers(MatchFinder
*Finder
) {
39 functionDecl(isStaticStorageClass(),
40 unless(anyOf(isInHeaderFile(HeaderFileExtensions
),
41 isInAnonymousNamespace(), isMemberFunction())))
45 varDecl(isStaticStorageClass(),
46 unless(anyOf(isInHeaderFile(HeaderFileExtensions
),
47 isInAnonymousNamespace(), isStaticLocal(),
48 isStaticDataMember(), hasType(isConstQualified()))))
53 void UseAnonymousNamespaceCheck::check(const MatchFinder::MatchResult
&Result
) {
54 if (const auto *MatchedDecl
= Result
.Nodes
.getNodeAs
<NamedDecl
>("x")) {
55 StringRef Type
= llvm::isa
<VarDecl
>(MatchedDecl
) ? "variable" : "function";
56 diag(MatchedDecl
->getLocation(),
57 "%0 %1 declared 'static', move to anonymous namespace instead")
58 << Type
<< MatchedDecl
;
62 } // namespace clang::tidy::misc