clang-tools 24.0.0git
UseInternalLinkageCheck.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/Decl.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/ASTMatchers/ASTMatchers.h"
14#include "clang/ASTMatchers/ASTMatchersMacros.h"
15#include "clang/Basic/Module.h"
16#include "clang/Basic/SourceLocation.h"
17#include "clang/Basic/Specifiers.h"
18#include "clang/Lex/Token.h"
19#include "llvm/ADT/DenseSet.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallVector.h"
22
23using namespace clang::ast_matchers;
24
25namespace clang::tidy {
26
27template <>
28struct OptionEnumMapping<misc::UseInternalLinkageCheck::FixModeKind> {
29 static llvm::ArrayRef<
30 std::pair<misc::UseInternalLinkageCheck::FixModeKind, StringRef>>
32 static constexpr std::pair<misc::UseInternalLinkageCheck::FixModeKind,
33 StringRef>
34 Mapping[] = {
37 "UseStatic"},
38 };
39 return {Mapping};
40 }
41};
42
43} // namespace clang::tidy
44
45namespace clang::tidy::misc {
46
47static bool isInMainFile(SourceLocation L, const SourceManager &SM,
48 const FileExtensionsSet &HeaderFileExtensions) {
49 for (;;) {
50 if (utils::isExpansionLocInHeaderFile(L, SM, HeaderFileExtensions))
51 return false;
52 if (SM.isInMainFile(L))
53 return true;
54 // not in header file but not in main file
55 L = SM.getIncludeLoc(SM.getFileID(L));
56 if (L.isValid())
57 continue;
58 // Conservative about the unknown
59 return false;
60 }
61}
62
63namespace {
64
65AST_MATCHER(Decl, isFirstDecl) { return Node.isFirstDecl(); }
66
67AST_MATCHER(FunctionDecl, hasBody) { return Node.hasBody(); }
68
69AST_MATCHER(Decl, isInImportableModuleUnit) {
70 const Module *OwningModule = Node.getOwningModule();
71 return OwningModule &&
72 (OwningModule->Kind == Module::ModuleInterfaceUnit ||
73 OwningModule->Kind == Module::ModulePartitionInterface ||
74 OwningModule->Kind == Module::ModulePartitionImplementation);
75}
76
77AST_MATCHER_P(Decl, isAllRedeclsInMainFile, const FileExtensionsSet *,
78 HeaderFileExtensions) {
79 return llvm::all_of(Node.redecls(), [&](const Decl *D) {
80 return isInMainFile(D->getLocation(),
81 Finder->getASTContext().getSourceManager(),
82 *HeaderFileExtensions);
83 });
84}
85
86AST_POLYMORPHIC_MATCHER(isExternStorageClass,
87 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
88 VarDecl)) {
89 return Node.getStorageClass() == SC_Extern;
90}
91
92AST_MATCHER(FunctionDecl, isAllocationOrDeallocationOverloadedFunction) {
93 // [basic.stc.dynamic.allocation]
94 // An allocation function that is not a class member function shall belong to
95 // the global scope and not have a name with internal linkage.
96 // [basic.stc.dynamic.deallocation]
97 // A deallocation function that is not a class member function shall belong to
98 // the global scope and not have a name with internal linkage.
99 static const llvm::DenseSet<OverloadedOperatorKind> OverloadedOperators{
100 OverloadedOperatorKind::OO_New,
101 OverloadedOperatorKind::OO_Array_New,
102 OverloadedOperatorKind::OO_Delete,
103 OverloadedOperatorKind::OO_Array_Delete,
104 };
105 return OverloadedOperators.contains(Node.getOverloadedOperator());
106}
107
108AST_POLYMORPHIC_MATCHER(isExplicitlyExternC,
109 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
110 VarDecl)) {
111 return Finder->getASTContext().getLangOpts().CPlusPlus && Node.isExternC();
112}
113
114AST_MATCHER(TagDecl, hasNameForLinkage) { return Node.hasNameForLinkage(); }
115
116AST_MATCHER(CXXRecordDecl, isExplicitTemplateInstantiation) {
117 return Node.getTemplateSpecializationKind() ==
118 TSK_ExplicitInstantiationDefinition;
119}
120
121} // namespace
122
124 ClangTidyContext *Context)
125 : ClangTidyCheck(Name, Context),
126 FixMode(Options.get("FixMode", FixModeKind::UseStatic)),
127 AnalyzeFunctions(Options.get("AnalyzeFunctions", true)),
128 AnalyzeVariables(Options.get("AnalyzeVariables", true)),
129 AnalyzeTypes(Options.get("AnalyzeTypes", true)) {
130 if (!AnalyzeFunctions && !AnalyzeVariables && !AnalyzeTypes)
131 configurationDiag(
132 "the 'misc-use-internal-linkage' check will not perform any "
133 "analysis because its 'AnalyzeFunctions', 'AnalyzeVariables', "
134 "and 'AnalyzeTypes' options have all been set to false");
135}
136
138 Options.store(Opts, "FixMode", FixMode);
139 Options.store(Opts, "AnalyzeFunctions", AnalyzeFunctions);
140 Options.store(Opts, "AnalyzeVariables", AnalyzeVariables);
141 Options.store(Opts, "AnalyzeTypes", AnalyzeTypes);
142}
143
145 const auto Common =
146 allOf(isFirstDecl(), isAllRedeclsInMainFile(&getHeaderFileExtensions()),
147 unless(anyOf(isInAnonymousNamespace(), isInImportableModuleUnit(),
148 hasAncestor(decl(friendDecl())))));
149
150 if (AnalyzeFunctions)
151 Finder->addMatcher(
152 functionDecl(
153 Common, hasBody(),
154 unless(anyOf(
155 isExplicitlyExternC(), isStaticStorageClass(),
156 isExternStorageClass(), isExplicitTemplateSpecialization(),
157 cxxMethodDecl(), isConsteval(),
158 isAllocationOrDeallocationOverloadedFunction(), isMain())))
159 .bind("fn"),
160 this);
161
162 if (AnalyzeVariables)
163 Finder->addMatcher(
164 varDecl(Common, hasGlobalStorage(),
165 unless(anyOf(isExplicitlyExternC(), isStaticStorageClass(),
166 isExternStorageClass(),
167 isExplicitTemplateSpecialization(),
168 hasThreadStorageDuration())))
169 .bind("var"),
170 this);
171
172 if (getLangOpts().CPlusPlus && AnalyzeTypes)
173 Finder->addMatcher(
174 tagDecl(Common, isDefinition(), hasNameForLinkage(),
175 hasDeclContext(anyOf(translationUnitDecl(), namespaceDecl())),
176 unless(anyOf(
177 classTemplatePartialSpecializationDecl(),
178 cxxRecordDecl(anyOf(isExplicitTemplateSpecialization(),
179 isExplicitTemplateInstantiation())))))
180 .bind("tag"),
181 this);
182}
183
184static constexpr StringRef Message =
185 "%0 %1 can be made static %select{|or moved into an anonymous namespace }2"
186 "to enforce internal linkage";
187
188void UseInternalLinkageCheck::check(const MatchFinder::MatchResult &Result) {
189 if (const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("fn")) {
190 const DiagnosticBuilder DB = diag(FD->getLocation(), Message)
191 << "function" << FD << getLangOpts().CPlusPlus;
192 const SourceLocation FixLoc = FD->getInnerLocStart();
193 if (FixLoc.isInvalid() || FixLoc.isMacroID())
194 return;
195 if (FixMode == FixModeKind::UseStatic)
196 DB << FixItHint::CreateInsertion(FixLoc, "static ");
197 return;
198 }
199 if (const auto *VD = Result.Nodes.getNodeAs<VarDecl>("var")) {
200 // In C++, const variables at file scope have implicit internal linkage,
201 // so we should not warn there. This is not the case in C.
202 // https://eel.is/c++draft/diff#basic-3
203 if (getLangOpts().CPlusPlus && VD->getType().isConstQualified())
204 return;
205
206 const DiagnosticBuilder DB = diag(VD->getLocation(), Message)
207 << "variable" << VD << getLangOpts().CPlusPlus;
208 const SourceLocation FixLoc = VD->getInnerLocStart();
209 if (FixLoc.isInvalid() || FixLoc.isMacroID())
210 return;
211 if (FixMode == FixModeKind::UseStatic)
212 DB << FixItHint::CreateInsertion(FixLoc, "static ");
213 return;
214 }
215 if (const auto *TD = Result.Nodes.getNodeAs<TagDecl>("tag")) {
216 diag(TD->getLocation(), "%0 %1 can be moved into an anonymous namespace "
217 "to enforce internal linkage")
218 << TD->getKindName() << TD;
219 return;
220 }
221 llvm_unreachable("");
222}
223
224} // namespace clang::tidy::misc
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
UseInternalLinkageCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
AST_POLYMORPHIC_MATCHER(isInAbseilFile, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc, NestedNameSpecifierLoc))
Matches AST nodes that were found within Abseil files.
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID)
AST_MATCHER(BinaryOperator, isRelationalOperator)
static bool isInMainFile(SourceLocation L, const SourceManager &SM, const FileExtensionsSet &HeaderFileExtensions)
static constexpr StringRef Message
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
llvm::StringMap< ClangTidyValue > OptionMap
static llvm::ArrayRef< std::pair< misc::UseInternalLinkageCheck::FixModeKind, StringRef > > getEnumMapping()
This class should be specialized by any enum type that needs to be converted to and from an llvm::Str...