clang-tools 22.0.0git
InconsistentDeclarationParameterNameCheck.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
10#include "clang/ASTMatchers/ASTMatchFinder.h"
11#include "llvm/ADT/STLExtras.h"
12
13using namespace clang::ast_matchers;
14
16
17namespace {
18
19AST_MATCHER(FunctionDecl, hasOtherDeclarations) {
20 auto It = Node.redecls_begin();
21 auto EndIt = Node.redecls_end();
22
23 if (It == EndIt)
24 return false;
25
26 ++It;
27 return It != EndIt;
28}
29
30struct DifferingParamInfo {
31 DifferingParamInfo(StringRef SourceName, StringRef OtherName,
32 SourceRange OtherNameRange, bool GenerateFixItHint)
33 : SourceName(SourceName), OtherName(OtherName),
34 OtherNameRange(OtherNameRange), GenerateFixItHint(GenerateFixItHint) {}
35
36 StringRef SourceName;
37 StringRef OtherName;
38 SourceRange OtherNameRange;
39 bool GenerateFixItHint;
40};
41
42using DifferingParamsContainer = llvm::SmallVector<DifferingParamInfo, 10>;
43
44struct InconsistentDeclarationInfo {
45 InconsistentDeclarationInfo(SourceLocation DeclarationLocation,
46 DifferingParamsContainer &&DifferingParams)
47 : DeclarationLocation(DeclarationLocation),
48 DifferingParams(std::move(DifferingParams)) {}
49
50 SourceLocation DeclarationLocation;
51 DifferingParamsContainer DifferingParams;
52};
53
54using InconsistentDeclarationsContainer =
55 llvm::SmallVector<InconsistentDeclarationInfo, 2>;
56
57} // namespace
58
59static bool
60checkIfFixItHintIsApplicable(const FunctionDecl *ParameterSourceDeclaration,
61 const ParmVarDecl *SourceParam,
62 const FunctionDecl *OriginalDeclaration) {
63 // Assumptions with regard to function declarations/definition:
64 // * If both function declaration and definition are seen, assume that
65 // definition is most up-to-date, and use it to generate replacements.
66 // * If only function declarations are seen, there is no easy way to tell
67 // which is up-to-date and which is not, so don't do anything.
68 // TODO: This may be changed later, but for now it seems the reasonable
69 // solution.
70 if (!ParameterSourceDeclaration->isThisDeclarationADefinition())
71 return false;
72
73 // Assumption: if parameter is not referenced in function definition body, it
74 // may indicate that it's outdated, so don't touch it.
75 if (!SourceParam->isReferenced())
76 return false;
77
78 // In case there is the primary template definition and (possibly several)
79 // template specializations (and each with possibly several redeclarations),
80 // it is not at all clear what to change.
81 if (OriginalDeclaration->getTemplatedKind() ==
82 FunctionDecl::TK_FunctionTemplateSpecialization)
83 return false;
84
85 // Other cases seem OK to allow replacements.
86 return true;
87}
88
89static bool nameMatch(StringRef L, StringRef R, bool Strict) {
90 if (Strict)
91 return L.empty() || R.empty() || L == R;
92 // We allow two names if one is a prefix/suffix of the other, ignoring case.
93 // Important special case: this is true if either parameter has no name!
94 return L.starts_with_insensitive(R) || R.starts_with_insensitive(L) ||
95 L.ends_with_insensitive(R) || R.ends_with_insensitive(L);
96}
97
98static DifferingParamsContainer
99findDifferingParamsInDeclaration(const FunctionDecl *ParameterSourceDeclaration,
100 const FunctionDecl *OtherDeclaration,
101 const FunctionDecl *OriginalDeclaration,
102 bool Strict) {
103 DifferingParamsContainer DifferingParams;
104
105 const auto *SourceParamIt = ParameterSourceDeclaration->param_begin();
106 const auto *OtherParamIt = OtherDeclaration->param_begin();
107
108 while (SourceParamIt != ParameterSourceDeclaration->param_end() &&
109 OtherParamIt != OtherDeclaration->param_end()) {
110 if ((*SourceParamIt)->isParameterPack() !=
111 (*OtherParamIt)->isParameterPack())
112 break;
113
114 auto SourceParamName = (*SourceParamIt)->getName();
115 auto OtherParamName = (*OtherParamIt)->getName();
116
117 // FIXME: Provide a way to extract commented out parameter name from comment
118 // next to it.
119 if (!nameMatch(SourceParamName, OtherParamName, Strict)) {
120 const SourceRange OtherParamNameRange =
121 DeclarationNameInfo((*OtherParamIt)->getDeclName(),
122 (*OtherParamIt)->getLocation())
123 .getSourceRange();
124
125 const bool GenerateFixItHint = checkIfFixItHintIsApplicable(
126 ParameterSourceDeclaration, *SourceParamIt, OriginalDeclaration);
127
128 DifferingParams.emplace_back(SourceParamName, OtherParamName,
129 OtherParamNameRange, GenerateFixItHint);
130 }
131
132 ++SourceParamIt;
133 ++OtherParamIt;
134 }
135
136 return DifferingParams;
137}
138
139static InconsistentDeclarationsContainer
140findInconsistentDeclarations(const FunctionDecl *OriginalDeclaration,
141 const FunctionDecl *ParameterSourceDeclaration,
142 SourceManager &SM, bool Strict) {
143 InconsistentDeclarationsContainer InconsistentDeclarations;
144 const SourceLocation ParameterSourceLocation =
145 ParameterSourceDeclaration->getLocation();
146
147 for (const FunctionDecl *OtherDeclaration : OriginalDeclaration->redecls()) {
148 const SourceLocation OtherLocation = OtherDeclaration->getLocation();
149 if (OtherLocation != ParameterSourceLocation) { // Skip self.
150 DifferingParamsContainer DifferingParams =
151 findDifferingParamsInDeclaration(ParameterSourceDeclaration,
152 OtherDeclaration,
153 OriginalDeclaration, Strict);
154 if (!DifferingParams.empty()) {
155 InconsistentDeclarations.emplace_back(OtherDeclaration->getLocation(),
156 std::move(DifferingParams));
157 }
158 }
159 }
160
161 // Sort in order of appearance in translation unit to generate clear
162 // diagnostics.
163 llvm::sort(InconsistentDeclarations,
164 [&SM](const InconsistentDeclarationInfo &Info1,
165 const InconsistentDeclarationInfo &Info2) {
166 return SM.isBeforeInTranslationUnit(Info1.DeclarationLocation,
167 Info2.DeclarationLocation);
168 });
169 return InconsistentDeclarations;
170}
171
172static const FunctionDecl *
173getParameterSourceDeclaration(const FunctionDecl *OriginalDeclaration) {
174 const FunctionTemplateDecl *PrimaryTemplate =
175 OriginalDeclaration->getPrimaryTemplate();
176 if (PrimaryTemplate != nullptr) {
177 // In case of template specializations, use primary template declaration as
178 // the source of parameter names.
179 return PrimaryTemplate->getTemplatedDecl();
180 }
181
182 // In other cases, try to change to function definition, if available.
183
184 if (OriginalDeclaration->isThisDeclarationADefinition())
185 return OriginalDeclaration;
186
187 for (const FunctionDecl *OtherDeclaration : OriginalDeclaration->redecls())
188 if (OtherDeclaration->isThisDeclarationADefinition())
189 return OtherDeclaration;
190
191 // No definition found, so return original declaration.
192 return OriginalDeclaration;
193}
194
195static std::string joinParameterNames(
196 const DifferingParamsContainer &DifferingParams,
197 llvm::function_ref<StringRef(const DifferingParamInfo &)> ChooseParamName) {
198 llvm::SmallString<40> Str;
199 bool First = true;
200 for (const DifferingParamInfo &ParamInfo : DifferingParams) {
201 if (First)
202 First = false;
203 else
204 Str += ", ";
205 Str.append({"'", ChooseParamName(ParamInfo), "'"});
206 }
207 return std::string(Str);
208}
209
212 StringRef OtherDeclarationDescription,
213 const DifferingParamsContainer &DifferingParams) {
214 auto ChooseOtherName = [](const DifferingParamInfo &ParamInfo) {
215 return ParamInfo.OtherName;
216 };
217 auto ChooseSourceName = [](const DifferingParamInfo &ParamInfo) {
218 return ParamInfo.SourceName;
219 };
220
221 auto ParamDiag =
222 Check->diag(Location,
223 "differing parameters are named here: (%0), in %1: (%2)",
224 DiagnosticIDs::Level::Note)
225 << joinParameterNames(DifferingParams, ChooseOtherName)
226 << OtherDeclarationDescription
227 << joinParameterNames(DifferingParams, ChooseSourceName);
228
229 for (const DifferingParamInfo &ParamInfo : DifferingParams) {
230 if (ParamInfo.GenerateFixItHint) {
231 ParamDiag << FixItHint::CreateReplacement(
232 CharSourceRange::getTokenRange(ParamInfo.OtherNameRange),
233 ParamInfo.SourceName);
234 }
235 }
236}
237
240 const FunctionDecl *ParameterSourceDeclaration,
241 const FunctionDecl *OriginalDeclaration,
242 const InconsistentDeclarationsContainer &InconsistentDeclarations) {
243 Check->diag(
244 OriginalDeclaration->getLocation(),
245 "function %q0 has %1 other declaration%s1 with different parameter names")
246 << OriginalDeclaration
247 << static_cast<int>(InconsistentDeclarations.size());
248 int Count = 1;
249 for (const InconsistentDeclarationInfo &InconsistentDeclaration :
250 InconsistentDeclarations) {
251 Check->diag(InconsistentDeclaration.DeclarationLocation,
252 "the %ordinal0 inconsistent declaration seen here",
253 DiagnosticIDs::Level::Note)
254 << Count;
255
257 Check, InconsistentDeclaration.DeclarationLocation,
258 "the other declaration", InconsistentDeclaration.DifferingParams);
259
260 ++Count;
261 }
262}
263
266 const FunctionDecl *ParameterSourceDeclaration,
267 const FunctionDecl *OriginalDeclaration,
268 const InconsistentDeclarationsContainer &InconsistentDeclarations,
269 StringRef FunctionDescription, StringRef ParameterSourceDescription) {
270 for (const InconsistentDeclarationInfo &InconsistentDeclaration :
271 InconsistentDeclarations) {
272 Check->diag(InconsistentDeclaration.DeclarationLocation,
273 "%0 %q1 has a %2 with different parameter names")
274 << FunctionDescription << OriginalDeclaration
275 << ParameterSourceDescription;
276
277 Check->diag(ParameterSourceDeclaration->getLocation(), "the %0 seen here",
278 DiagnosticIDs::Level::Note)
279 << ParameterSourceDescription;
280
282 Check, InconsistentDeclaration.DeclarationLocation,
283 ParameterSourceDescription, InconsistentDeclaration.DifferingParams);
284 }
285}
286
289 Options.store(Opts, "IgnoreMacros", IgnoreMacros);
290 Options.store(Opts, "Strict", Strict);
291}
292
294 MatchFinder *Finder) {
295 Finder->addMatcher(functionDecl(hasOtherDeclarations()).bind("functionDecl"),
296 this);
297}
298
300 const MatchFinder::MatchResult &Result) {
301 const auto *OriginalDeclaration =
302 Result.Nodes.getNodeAs<FunctionDecl>("functionDecl");
303
304 if (VisitedDeclarations.contains(OriginalDeclaration))
305 return; // Avoid multiple warnings.
306
307 const FunctionDecl *ParameterSourceDeclaration =
308 getParameterSourceDeclaration(OriginalDeclaration);
309
310 const InconsistentDeclarationsContainer InconsistentDeclarations =
311 findInconsistentDeclarations(OriginalDeclaration,
312 ParameterSourceDeclaration,
313 *Result.SourceManager, Strict);
314 if (InconsistentDeclarations.empty()) {
315 // Avoid unnecessary further visits.
316 markRedeclarationsAsVisited(OriginalDeclaration);
317 return;
318 }
319
320 const SourceLocation StartLoc = OriginalDeclaration->getBeginLoc();
321 if (StartLoc.isMacroID() && IgnoreMacros) {
322 markRedeclarationsAsVisited(OriginalDeclaration);
323 return;
324 }
325
326 if (OriginalDeclaration->getTemplatedKind() ==
327 FunctionDecl::TK_FunctionTemplateSpecialization) {
328 formatDiagnostics(this, ParameterSourceDeclaration, OriginalDeclaration,
329 InconsistentDeclarations,
330 "function template specialization",
331 "primary template declaration");
332 } else if (ParameterSourceDeclaration->isThisDeclarationADefinition()) {
333 formatDiagnostics(this, ParameterSourceDeclaration, OriginalDeclaration,
334 InconsistentDeclarations, "function", "definition");
335 } else {
336 formatDiagnosticsForDeclarations(this, ParameterSourceDeclaration,
337 OriginalDeclaration,
338 InconsistentDeclarations);
339 }
340
341 markRedeclarationsAsVisited(OriginalDeclaration);
342}
343
344void InconsistentDeclarationParameterNameCheck::markRedeclarationsAsVisited(
345 const FunctionDecl *OriginalDeclaration) {
346 VisitedDeclarations.insert_range(OriginalDeclaration->redecls());
347}
348
349} // namespace clang::tidy::readability
Checks for declarations of functions which differ in parameter names.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
AST_MATCHER(BinaryOperator, isRelationalOperator)
static InconsistentDeclarationsContainer findInconsistentDeclarations(const FunctionDecl *OriginalDeclaration, const FunctionDecl *ParameterSourceDeclaration, SourceManager &SM, bool Strict)
static const FunctionDecl * getParameterSourceDeclaration(const FunctionDecl *OriginalDeclaration)
static void formatDiagnosticsForDeclarations(InconsistentDeclarationParameterNameCheck *Check, const FunctionDecl *ParameterSourceDeclaration, const FunctionDecl *OriginalDeclaration, const InconsistentDeclarationsContainer &InconsistentDeclarations)
static void formatDifferingParamsDiagnostic(InconsistentDeclarationParameterNameCheck *Check, SourceLocation Location, StringRef OtherDeclarationDescription, const DifferingParamsContainer &DifferingParams)
static bool nameMatch(StringRef L, StringRef R, bool Strict)
static void formatDiagnostics(InconsistentDeclarationParameterNameCheck *Check, const FunctionDecl *ParameterSourceDeclaration, const FunctionDecl *OriginalDeclaration, const InconsistentDeclarationsContainer &InconsistentDeclarations, StringRef FunctionDescription, StringRef ParameterSourceDescription)
static std::string joinParameterNames(const DifferingParamsContainer &DifferingParams, llvm::function_ref< StringRef(const DifferingParamInfo &)> ChooseParamName)
static bool checkIfFixItHintIsApplicable(const FunctionDecl *ParameterSourceDeclaration, const ParmVarDecl *SourceParam, const FunctionDecl *OriginalDeclaration)
static DifferingParamsContainer findDifferingParamsInDeclaration(const FunctionDecl *ParameterSourceDeclaration, const FunctionDecl *OtherDeclaration, const FunctionDecl *OriginalDeclaration, bool Strict)
llvm::StringMap< ClangTidyValue > OptionMap