clang-tools 22.0.0git
SuspiciousCallArgumentCheck.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/AST/Type.h"
13#include "clang/ASTMatchers/ASTMatchFinder.h"
14#include <optional>
15
16using namespace clang::ast_matchers;
18
20
21namespace {
22struct DefaultHeuristicConfiguration {
23 /// Whether the heuristic is to be enabled by default.
24 const bool Enabled;
25
26 /// The upper bound of % of similarity the two strings might have to be
27 /// considered dissimilar.
28 /// (For purposes of configuration, -1 if the heuristic is not configurable
29 /// with bounds.)
30 const int8_t DissimilarBelow;
31
32 /// The lower bound of % of similarity the two string must have to be
33 /// considered similar.
34 /// (For purposes of configuration, -1 if the heuristic is not configurable
35 /// with bounds.)
36 const int8_t SimilarAbove;
37
38 /// Can the heuristic be configured with bounds?
39 bool hasBounds() const { return DissimilarBelow > -1 && SimilarAbove > -1; }
40};
41} // namespace
42
43static constexpr std::size_t DefaultMinimumIdentifierNameLength = 3;
44
45static constexpr StringRef HeuristicToString[] = {
46 "Equality", "Abbreviation", "Prefix", "Suffix",
47 "Substring", "Levenshtein", "JaroWinkler", "Dice"};
48
49static constexpr DefaultHeuristicConfiguration Defaults[] = {
50 {true, -1, -1}, // Equality.
51 {true, -1, -1}, // Abbreviation.
52 {true, 25, 30}, // Prefix.
53 {true, 25, 30}, // Suffix.
54 {true, 40, 50}, // Substring.
55 {true, 50, 66}, // Levenshtein.
56 {true, 75, 85}, // Jaro-Winkler.
57 {true, 60, 70}, // Dice.
58};
59
60static_assert(
61 sizeof(HeuristicToString) / sizeof(HeuristicToString[0]) ==
63 "Ensure that every heuristic has a corresponding stringified name");
64static_assert(sizeof(Defaults) / sizeof(Defaults[0]) ==
66 "Ensure that every heuristic has a default configuration.");
67
68namespace {
69template <std::size_t I> struct HasWellConfiguredBounds {
70 static constexpr bool Value =
71 !((Defaults[I].DissimilarBelow == -1) ^ (Defaults[I].SimilarAbove == -1));
72 static_assert(Value, "A heuristic must either have a dissimilarity and "
73 "similarity bound, or neither!");
74};
75
76template <std::size_t I> struct HasWellConfiguredBoundsFold {
77 static constexpr bool Value = HasWellConfiguredBounds<I>::Value &&
78 HasWellConfiguredBoundsFold<I - 1>::Value;
79};
80
81template <> struct HasWellConfiguredBoundsFold<0> {
82 static constexpr bool Value = HasWellConfiguredBounds<0>::Value;
83};
84
85struct AllHeuristicsBoundsWellConfigured {
86 static constexpr bool Value =
87 HasWellConfiguredBoundsFold<SuspiciousCallArgumentCheck::HeuristicCount -
88 1>::Value;
89};
90
91static_assert(AllHeuristicsBoundsWellConfigured::Value);
92} // namespace
93
94static constexpr llvm::StringLiteral DefaultAbbreviations = "addr=address;"
95 "arr=array;"
96 "attr=attribute;"
97 "buf=buffer;"
98 "cl=client;"
99 "cnt=count;"
100 "col=column;"
101 "cpy=copy;"
102 "dest=destination;"
103 "dist=distance"
104 "dst=distance;"
105 "elem=element;"
106 "hght=height;"
107 "i=index;"
108 "idx=index;"
109 "len=length;"
110 "ln=line;"
111 "lst=list;"
112 "nr=number;"
113 "num=number;"
114 "pos=position;"
115 "ptr=pointer;"
116 "ref=reference;"
117 "src=source;"
118 "srv=server;"
119 "stmt=statement;"
120 "str=string;"
121 "val=value;"
122 "var=variable;"
123 "vec=vector;"
124 "wdth=width";
125
126static constexpr std::size_t SmallVectorSize =
128
129/// Returns how many % X is of Y.
130static inline double percentage(double X, double Y) { return X / Y * 100.0; }
131
132static bool applyEqualityHeuristic(StringRef Arg, StringRef Param) {
133 return Arg.equals_insensitive(Param);
134}
135
137 const llvm::StringMap<std::string> &AbbreviationDictionary, StringRef Arg,
138 StringRef Param) {
139 if (AbbreviationDictionary.contains(Arg) &&
140 Param == AbbreviationDictionary.lookup(Arg))
141 return true;
142
143 if (AbbreviationDictionary.contains(Param) &&
144 Arg == AbbreviationDictionary.lookup(Param))
145 return true;
146
147 return false;
148}
149
150/// Check whether the shorter String is a prefix of the longer String.
151static bool applyPrefixHeuristic(StringRef Arg, StringRef Param,
152 int8_t Threshold) {
153 StringRef Shorter = Arg.size() < Param.size() ? Arg : Param;
154 StringRef Longer = Arg.size() >= Param.size() ? Arg : Param;
155
156 if (Longer.starts_with_insensitive(Shorter))
157 return percentage(Shorter.size(), Longer.size()) > Threshold;
158
159 return false;
160}
161
162/// Check whether the shorter String is a suffix of the longer String.
163static bool applySuffixHeuristic(StringRef Arg, StringRef Param,
164 int8_t Threshold) {
165 StringRef Shorter = Arg.size() < Param.size() ? Arg : Param;
166 StringRef Longer = Arg.size() >= Param.size() ? Arg : Param;
167
168 if (Longer.ends_with_insensitive(Shorter))
169 return percentage(Shorter.size(), Longer.size()) > Threshold;
170
171 return false;
172}
173
174static bool applySubstringHeuristic(StringRef Arg, StringRef Param,
175 int8_t Threshold) {
176
177 std::size_t MaxLength = 0;
178 SmallVector<std::size_t, SmallVectorSize> Current(Param.size());
179 SmallVector<std::size_t, SmallVectorSize> Previous(Param.size());
180 std::string ArgLower = Arg.lower();
181 std::string ParamLower = Param.lower();
182
183 for (std::size_t I = 0; I < Arg.size(); ++I) {
184 for (std::size_t J = 0; J < Param.size(); ++J) {
185 if (ArgLower[I] == ParamLower[J]) {
186 if (I == 0 || J == 0)
187 Current[J] = 1;
188 else
189 Current[J] = 1 + Previous[J - 1];
190
191 MaxLength = std::max(MaxLength, Current[J]);
192 } else
193 Current[J] = 0;
194 }
195
196 Current.swap(Previous);
197 }
198
199 size_t LongerLength = std::max(Arg.size(), Param.size());
200 return percentage(MaxLength, LongerLength) > Threshold;
201}
202
203static bool applyLevenshteinHeuristic(StringRef Arg, StringRef Param,
204 int8_t Threshold) {
205 std::size_t LongerLength = std::max(Arg.size(), Param.size());
206 double Dist = Arg.edit_distance(Param);
207 Dist = (1.0 - Dist / LongerLength) * 100.0;
208 return Dist > Threshold;
209}
210
211// Based on https://en.wikipedia.org/wiki/Jaro–Winkler_distance.
212static bool applyJaroWinklerHeuristic(StringRef Arg, StringRef Param,
213 int8_t Threshold) {
214 std::size_t Match = 0, Transpos = 0;
215 std::ptrdiff_t ArgLen = Arg.size();
216 std::ptrdiff_t ParamLen = Param.size();
217 SmallVector<int, SmallVectorSize> ArgFlags(ArgLen);
218 SmallVector<int, SmallVectorSize> ParamFlags(ParamLen);
219 std::ptrdiff_t Range =
220 std::max(std::ptrdiff_t{0}, (std::max(ArgLen, ParamLen) / 2) - 1);
221
222 // Calculate matching characters.
223 for (std::ptrdiff_t I = 0; I < ParamLen; ++I)
224 for (std::ptrdiff_t J = std::max(I - Range, std::ptrdiff_t{0}),
225 L = std::min(I + Range + 1, ArgLen);
226 J < L; ++J)
227 if (tolower(Param[I]) == tolower(Arg[J]) && !ArgFlags[J]) {
228 ArgFlags[J] = 1;
229 ParamFlags[I] = 1;
230 ++Match;
231 break;
232 }
233
234 if (!Match)
235 return false;
236
237 // Calculate character transpositions.
238 std::ptrdiff_t L = 0;
239 for (std::ptrdiff_t I = 0; I < ParamLen; ++I) {
240 if (ParamFlags[I] == 1) {
241 std::ptrdiff_t J = 0;
242 for (J = L; J < ArgLen; ++J)
243 if (ArgFlags[J] == 1) {
244 L = J + 1;
245 break;
246 }
247
248 if (tolower(Param[I]) != tolower(Arg[J]))
249 ++Transpos;
250 }
251 }
252 Transpos /= 2;
253
254 // Jaro distance.
255 double MatchD = Match;
256 double Dist = ((MatchD / ArgLen) + (MatchD / ParamLen) +
257 ((MatchD - Transpos) / Match)) /
258 3.0;
259
260 // Calculate common string prefix up to 4 chars.
261 L = 0;
262 for (std::ptrdiff_t I = 0;
263 I < std::min({ArgLen, ParamLen, std::ptrdiff_t{4}}); ++I)
264 if (tolower(Arg[I]) == tolower(Param[I]))
265 ++L;
266
267 // Jaro-Winkler distance.
268 Dist = (Dist + (L * 0.1 * (1.0 - Dist))) * 100.0;
269 return Dist > Threshold;
270}
271
272// Based on https://en.wikipedia.org/wiki/Sørensen–Dice_coefficient
273static bool applyDiceHeuristic(StringRef Arg, StringRef Param,
274 int8_t Threshold) {
275 llvm::StringSet<> ArgBigrams;
276 llvm::StringSet<> ParamBigrams;
277
278 // Extract character bigrams from Arg.
279 for (std::ptrdiff_t I = 0; I < static_cast<std::ptrdiff_t>(Arg.size()) - 1;
280 ++I)
281 ArgBigrams.insert(Arg.substr(I, 2).lower());
282
283 // Extract character bigrams from Param.
284 for (std::ptrdiff_t I = 0; I < static_cast<std::ptrdiff_t>(Param.size()) - 1;
285 ++I)
286 ParamBigrams.insert(Param.substr(I, 2).lower());
287
288 std::size_t Intersection = 0;
289
290 // Find the intersection between the two sets.
291 for (auto IT = ParamBigrams.begin(); IT != ParamBigrams.end(); ++IT)
292 Intersection += ArgBigrams.count((IT->getKey()));
293
294 // Calculate Dice coefficient.
295 return percentage(Intersection * 2.0,
296 ArgBigrams.size() + ParamBigrams.size()) > Threshold;
297}
298
299/// Checks if ArgType binds to ParamType regarding reference-ness and
300/// cv-qualifiers.
301static bool areRefAndQualCompatible(QualType ArgType, QualType ParamType,
302 const ASTContext &Ctx) {
303 return !ParamType->isReferenceType() ||
304 ParamType.getNonReferenceType().isAtLeastAsQualifiedAs(
305 ArgType.getNonReferenceType(), Ctx);
306}
307
308static bool isPointerOrArray(QualType TypeToCheck) {
309 return TypeToCheck->isPointerType() || TypeToCheck->isArrayType();
310}
311
312/// Checks whether ArgType is an array type identical to ParamType's array type.
313/// Enforces array elements' qualifier compatibility as well.
314static bool isCompatibleWithArrayReference(QualType ArgType, QualType ParamType,
315 const ASTContext &Ctx) {
316 if (!ArgType->isArrayType())
317 return false;
318 // Here, qualifiers belong to the elements of the arrays.
319 if (!ParamType.isAtLeastAsQualifiedAs(ArgType, Ctx))
320 return false;
321
322 return ParamType.getUnqualifiedType() == ArgType.getUnqualifiedType();
323}
324
325static QualType convertToPointeeOrArrayElementQualType(QualType TypeToConvert) {
326 unsigned CVRqualifiers = 0;
327 // Save array element qualifiers, since getElementType() removes qualifiers
328 // from array elements.
329 if (TypeToConvert->isArrayType())
330 CVRqualifiers = TypeToConvert.getLocalQualifiers().getCVRQualifiers();
331 TypeToConvert = TypeToConvert->isPointerType()
332 ? TypeToConvert->getPointeeType()
333 : TypeToConvert->getAsArrayTypeUnsafe()->getElementType();
334 TypeToConvert = TypeToConvert.withCVRQualifiers(CVRqualifiers);
335 return TypeToConvert;
336}
337
338/// Checks if multilevel pointers' qualifiers compatibility continues on the
339/// current pointer level. For multilevel pointers, C++ permits conversion, if
340/// every cv-qualifier in ArgType also appears in the corresponding position in
341/// ParamType, and if PramType has a cv-qualifier that's not in ArgType, then
342/// every * in ParamType to the right of that cv-qualifier, except the last
343/// one, must also be const-qualified.
344static bool arePointersStillQualCompatible(QualType ArgType, QualType ParamType,
345 bool &IsParamContinuouslyConst,
346 const ASTContext &Ctx) {
347 // The types are compatible, if the parameter is at least as qualified as the
348 // argument, and if it is more qualified, it has to be const on upper pointer
349 // levels.
350 bool AreTypesQualCompatible =
351 ParamType.isAtLeastAsQualifiedAs(ArgType, Ctx) &&
352 (!ParamType.hasQualifiers() || IsParamContinuouslyConst);
353 // Check whether the parameter's constness continues at the current pointer
354 // level.
355 IsParamContinuouslyConst &= ParamType.isConstQualified();
356
357 return AreTypesQualCompatible;
358}
359
360/// Checks whether multilevel pointers are compatible in terms of levels,
361/// qualifiers and pointee type.
362static bool arePointerTypesCompatible(QualType ArgType, QualType ParamType,
363 bool IsParamContinuouslyConst,
364 const ASTContext &Ctx) {
365 if (!arePointersStillQualCompatible(ArgType, ParamType,
366 IsParamContinuouslyConst, Ctx))
367 return false;
368
369 do {
370 // Step down one pointer level.
372 ParamType = convertToPointeeOrArrayElementQualType(ParamType);
373
374 // Check whether cv-qualifiers permit compatibility on
375 // current level.
376 if (!arePointersStillQualCompatible(ArgType, ParamType,
377 IsParamContinuouslyConst, Ctx))
378 return false;
379
380 if (ParamType.getUnqualifiedType() == ArgType.getUnqualifiedType())
381 return true;
382
383 } while (ParamType->isPointerType() && ArgType->isPointerType());
384 // The final type does not match, or pointer levels differ.
385 return false;
386}
387
388/// Checks whether ArgType converts implicitly to ParamType.
389static bool areTypesCompatible(QualType ArgType, QualType ParamType,
390 const ASTContext &Ctx) {
391 if (ArgType.isNull() || ParamType.isNull())
392 return false;
393
394 ArgType = ArgType.getCanonicalType();
395 ParamType = ParamType.getCanonicalType();
396
397 if (ArgType == ParamType)
398 return true;
399
400 // Check for constness and reference compatibility.
401 if (!areRefAndQualCompatible(ArgType, ParamType, Ctx))
402 return false;
403
404 bool IsParamReference = ParamType->isReferenceType();
405
406 // Reference-ness has already been checked and should be removed
407 // before further checking.
408 ArgType = ArgType.getNonReferenceType();
409 ParamType = ParamType.getNonReferenceType();
410
411 if (ParamType.getUnqualifiedType() == ArgType.getUnqualifiedType())
412 return true;
413
414 // Arithmetic types are interconvertible, except scoped enums.
415 if (ParamType->isArithmeticType() && ArgType->isArithmeticType()) {
416 if ((ParamType->isEnumeralType() && ParamType->castAsCanonical<EnumType>()
417 ->getOriginalDecl()
418 ->isScoped()) ||
419 (ArgType->isEnumeralType() &&
420 ArgType->castAsCanonical<EnumType>()->getOriginalDecl()->isScoped()))
421 return false;
422
423 return true;
424 }
425
426 // Check if the argument and the param are both function types (the parameter
427 // decayed to a function pointer).
428 if (ArgType->isFunctionType() && ParamType->isFunctionPointerType()) {
429 ParamType = ParamType->getPointeeType();
430 return ArgType == ParamType;
431 }
432
433 // Arrays or pointer arguments convert to array or pointer parameters.
434 if (!(isPointerOrArray(ArgType) && isPointerOrArray(ParamType)))
435 return false;
436
437 // When ParamType is an array reference, ArgType has to be of the same-sized
438 // array-type with cv-compatible element type.
439 if (IsParamReference && ParamType->isArrayType())
440 return isCompatibleWithArrayReference(ArgType, ParamType, Ctx);
441
442 bool IsParamContinuouslyConst =
443 !IsParamReference || ParamType.getNonReferenceType().isConstQualified();
444
445 // Remove the first level of indirection.
447 ParamType = convertToPointeeOrArrayElementQualType(ParamType);
448
449 // Check qualifier compatibility on the next level.
450 if (!ParamType.isAtLeastAsQualifiedAs(ArgType, Ctx))
451 return false;
452
453 if (ParamType.getUnqualifiedType() == ArgType.getUnqualifiedType())
454 return true;
455
456 // At this point, all possible C language implicit conversion were checked.
457 if (!Ctx.getLangOpts().CPlusPlus)
458 return false;
459
460 // Check whether ParamType and ArgType were both pointers to a class or a
461 // struct, and check for inheritance.
462 if (ParamType->isStructureOrClassType() &&
463 ArgType->isStructureOrClassType()) {
464 const auto *ArgDecl = ArgType->getAsCXXRecordDecl();
465 const auto *ParamDecl = ParamType->getAsCXXRecordDecl();
466 if (!ArgDecl || !ArgDecl->hasDefinition() || !ParamDecl ||
467 !ParamDecl->hasDefinition())
468 return false;
469
470 return ArgDecl->isDerivedFrom(ParamDecl);
471 }
472
473 // Unless argument and param are both multilevel pointers, the types are not
474 // convertible.
475 if (!(ParamType->isAnyPointerType() && ArgType->isAnyPointerType()))
476 return false;
477
478 return arePointerTypesCompatible(ArgType, ParamType, IsParamContinuouslyConst,
479 Ctx);
480}
481
482static bool isOverloadedUnaryOrBinarySymbolOperator(const FunctionDecl *FD) {
483 switch (FD->getOverloadedOperator()) {
484 case OO_None:
485 case OO_Call:
486 case OO_Subscript:
487 case OO_New:
488 case OO_Delete:
489 case OO_Array_New:
490 case OO_Array_Delete:
491 case OO_Conditional:
492 case OO_Coawait:
493 return false;
494
495 default:
496 return FD->getNumParams() <= 2;
497 }
498}
499
501 StringRef Name, ClangTidyContext *Context)
502 : ClangTidyCheck(Name, Context),
503 MinimumIdentifierNameLength(Options.get(
504 "MinimumIdentifierNameLength", DefaultMinimumIdentifierNameLength)) {
505 auto GetToggleOpt = [this](Heuristic H) -> bool {
506 auto Idx = static_cast<std::size_t>(H);
507 assert(Idx < HeuristicCount);
508 return Options.get(HeuristicToString[Idx], Defaults[Idx].Enabled);
509 };
510 auto GetBoundOpt = [this](Heuristic H, BoundKind BK) -> int8_t {
511 auto Idx = static_cast<std::size_t>(H);
512 assert(Idx < HeuristicCount);
513
514 SmallString<32> Key = HeuristicToString[Idx];
515 Key.append(BK == BoundKind::DissimilarBelow ? "DissimilarBelow"
516 : "SimilarAbove");
517 int8_t Default = BK == BoundKind::DissimilarBelow
518 ? Defaults[Idx].DissimilarBelow
519 : Defaults[Idx].SimilarAbove;
520 return Options.get(Key, Default);
521 };
522 for (std::size_t Idx = 0; Idx < HeuristicCount; ++Idx) {
523 auto H = static_cast<Heuristic>(Idx);
524 if (GetToggleOpt(H))
525 AppliedHeuristics.emplace_back(H);
526 ConfiguredBounds.emplace_back(
527 std::make_pair(GetBoundOpt(H, BoundKind::DissimilarBelow),
528 GetBoundOpt(H, BoundKind::SimilarAbove)));
529 }
530
531 for (StringRef Abbreviation : optutils::parseStringList(
532 Options.get("Abbreviations", DefaultAbbreviations))) {
533 auto KeyAndValue = Abbreviation.split("=");
534 assert(!KeyAndValue.first.empty() && !KeyAndValue.second.empty());
535 AbbreviationDictionary.insert(
536 std::make_pair(KeyAndValue.first, KeyAndValue.second.str()));
537 }
538}
539
542 Options.store(Opts, "MinimumIdentifierNameLength",
543 MinimumIdentifierNameLength);
544 const auto &SetToggleOpt = [this, &Opts](Heuristic H) -> void {
545 auto Idx = static_cast<std::size_t>(H);
546 Options.store(Opts, HeuristicToString[Idx], isHeuristicEnabled(H));
547 };
548 const auto &SetBoundOpt = [this, &Opts](Heuristic H, BoundKind BK) -> void {
549 auto Idx = static_cast<std::size_t>(H);
550 assert(Idx < HeuristicCount);
551 if (!Defaults[Idx].hasBounds())
552 return;
553
554 SmallString<32> Key = HeuristicToString[Idx];
555 Key.append(BK == BoundKind::DissimilarBelow ? "DissimilarBelow"
556 : "SimilarAbove");
557 Options.store(Opts, Key, *getBound(H, BK));
558 };
559
560 for (std::size_t Idx = 0; Idx < HeuristicCount; ++Idx) {
561 auto H = static_cast<Heuristic>(Idx);
562 SetToggleOpt(H);
563 SetBoundOpt(H, BoundKind::DissimilarBelow);
564 SetBoundOpt(H, BoundKind::SimilarAbove);
565 }
566
567 SmallVector<std::string, 32> Abbreviations;
568 for (const auto &Abbreviation : AbbreviationDictionary) {
569 SmallString<32> EqualSignJoined;
570 EqualSignJoined.append(Abbreviation.first());
571 EqualSignJoined.append("=");
572 EqualSignJoined.append(Abbreviation.second);
573
574 if (!Abbreviation.second.empty())
575 Abbreviations.emplace_back(EqualSignJoined.str());
576 }
577 Options.store(Opts, "Abbreviations",
578 optutils::serializeStringList(std::vector<StringRef>(
579 Abbreviations.begin(), Abbreviations.end())));
580}
581
582bool SuspiciousCallArgumentCheck::isHeuristicEnabled(Heuristic H) const {
583 return llvm::is_contained(AppliedHeuristics, H);
584}
585
586std::optional<int8_t>
587SuspiciousCallArgumentCheck::getBound(Heuristic H, BoundKind BK) const {
588 auto Idx = static_cast<std::size_t>(H);
589 assert(Idx < HeuristicCount);
590
591 if (!Defaults[Idx].hasBounds())
592 return std::nullopt;
593
594 switch (BK) {
595 case BoundKind::DissimilarBelow:
596 return ConfiguredBounds[Idx].first;
597 case BoundKind::SimilarAbove:
598 return ConfiguredBounds[Idx].second;
599 }
600 llvm_unreachable("Unhandled Bound kind.");
601}
602
604 // Only match calls with at least 2 arguments.
605 Finder->addMatcher(
606 functionDecl(forEachDescendant(callExpr(unless(anyOf(argumentCountIs(0),
607 argumentCountIs(1))))
608 .bind("functionCall")))
609 .bind("callingFunc"),
610 this);
611}
612
614 const MatchFinder::MatchResult &Result) {
615 const auto *MatchedCallExpr =
616 Result.Nodes.getNodeAs<CallExpr>("functionCall");
617 const auto *Caller = Result.Nodes.getNodeAs<FunctionDecl>("callingFunc");
618 assert(MatchedCallExpr && Caller);
619
620 const Decl *CalleeDecl = MatchedCallExpr->getCalleeDecl();
621 if (!CalleeDecl)
622 return;
623
624 const FunctionDecl *CalleeFuncDecl = CalleeDecl->getAsFunction();
625 if (!CalleeFuncDecl)
626 return;
627 if (CalleeFuncDecl == Caller)
628 // Ignore recursive calls.
629 return;
630 if (isOverloadedUnaryOrBinarySymbolOperator(CalleeFuncDecl))
631 return;
632
633 // Get param attributes.
634 setParamNamesAndTypes(CalleeFuncDecl);
635
636 if (ParamNames.empty())
637 return;
638
639 // Get Arg attributes.
640 std::size_t InitialArgIndex = 0;
641
642 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(CalleeFuncDecl)) {
643 if (MethodDecl->getParent()->isLambda())
644 // Lambda functions' first Arg are the lambda object.
645 InitialArgIndex = 1;
646 else if (MethodDecl->getOverloadedOperator() == OO_Call)
647 // For custom operator()s, the first Arg is the called object.
648 InitialArgIndex = 1;
649 }
650
651 setArgNamesAndTypes(MatchedCallExpr, InitialArgIndex);
652
653 if (ArgNames.empty())
654 return;
655
656 std::size_t ParamCount = ParamNames.size();
657
658 // Check similarity.
659 for (std::size_t I = 0; I < ParamCount; ++I) {
660 for (std::size_t J = I + 1; J < ParamCount; ++J) {
661 // Do not check if param or arg names are short, or not convertible.
662 if (!areParamAndArgComparable(I, J, *Result.Context))
663 continue;
664 if (!areArgsSwapped(I, J))
665 continue;
666
667 // Warning at the call itself.
668 diag(MatchedCallExpr->getExprLoc(),
669 "%ordinal0 argument '%1' (passed to '%2') looks like it might be "
670 "swapped with the %ordinal3, '%4' (passed to '%5')")
671 << static_cast<unsigned>(I + 1) << ArgNames[I] << ParamNames[I]
672 << static_cast<unsigned>(J + 1) << ArgNames[J] << ParamNames[J]
673 << MatchedCallExpr->getArg(I)->getSourceRange()
674 << MatchedCallExpr->getArg(J)->getSourceRange();
675
676 // Note at the functions declaration.
677 SourceLocation IParNameLoc =
678 CalleeFuncDecl->getParamDecl(I)->getLocation();
679 SourceLocation JParNameLoc =
680 CalleeFuncDecl->getParamDecl(J)->getLocation();
681
682 diag(CalleeFuncDecl->getLocation(), "in the call to %0, declared here",
683 DiagnosticIDs::Note)
684 << CalleeFuncDecl
685 << CharSourceRange::getTokenRange(IParNameLoc, IParNameLoc)
686 << CharSourceRange::getTokenRange(JParNameLoc, JParNameLoc);
687 }
688 }
689}
690
691void SuspiciousCallArgumentCheck::setParamNamesAndTypes(
692 const FunctionDecl *CalleeFuncDecl) {
693 // Reset vectors, and fill them with the currently checked function's
694 // parameters' data.
695 ParamNames.clear();
696 ParamTypes.clear();
697
698 for (const ParmVarDecl *Param : CalleeFuncDecl->parameters()) {
699 ParamTypes.push_back(Param->getType());
700
701 if (IdentifierInfo *II = Param->getIdentifier())
702 ParamNames.push_back(II->getName());
703 else
704 ParamNames.push_back(StringRef());
705 }
706}
707
708void SuspiciousCallArgumentCheck::setArgNamesAndTypes(
709 const CallExpr *MatchedCallExpr, std::size_t InitialArgIndex) {
710 // Reset vectors, and fill them with the currently checked function's
711 // arguments' data.
712 ArgNames.clear();
713 ArgTypes.clear();
714
715 for (std::size_t I = InitialArgIndex, J = MatchedCallExpr->getNumArgs();
716 I < J; ++I) {
717 assert(ArgTypes.size() == I - InitialArgIndex &&
718 ArgNames.size() == ArgTypes.size() &&
719 "Every iteration must put an element into the vectors!");
720
721 if (const auto *ArgExpr = dyn_cast<DeclRefExpr>(
722 MatchedCallExpr->getArg(I)->IgnoreUnlessSpelledInSource())) {
723 if (const auto *Var = dyn_cast<VarDecl>(ArgExpr->getDecl())) {
724 ArgTypes.push_back(Var->getType());
725 ArgNames.push_back(Var->getName());
726 continue;
727 }
728 if (const auto *FCall = dyn_cast<FunctionDecl>(ArgExpr->getDecl())) {
729 if (FCall->getNameInfo().getName().isIdentifier()) {
730 ArgTypes.push_back(FCall->getType());
731 ArgNames.push_back(FCall->getName());
732 continue;
733 }
734 }
735 }
736
737 ArgTypes.push_back(QualType());
738 ArgNames.push_back(StringRef());
739 }
740}
741
742bool SuspiciousCallArgumentCheck::areParamAndArgComparable(
743 std::size_t Position1, std::size_t Position2, const ASTContext &Ctx) const {
744 if (Position1 >= ArgNames.size() || Position2 >= ArgNames.size())
745 return false;
746
747 // Do not report for too short strings.
748 if (ArgNames[Position1].size() < MinimumIdentifierNameLength ||
749 ArgNames[Position2].size() < MinimumIdentifierNameLength ||
750 ParamNames[Position1].size() < MinimumIdentifierNameLength ||
751 ParamNames[Position2].size() < MinimumIdentifierNameLength)
752 return false;
753
754 if (!areTypesCompatible(ArgTypes[Position1], ParamTypes[Position2], Ctx) ||
755 !areTypesCompatible(ArgTypes[Position2], ParamTypes[Position1], Ctx))
756 return false;
757
758 return true;
759}
760
761bool SuspiciousCallArgumentCheck::areArgsSwapped(std::size_t Position1,
762 std::size_t Position2) const {
763 for (Heuristic H : AppliedHeuristics) {
764 bool A1ToP2Similar = areNamesSimilar(
765 ArgNames[Position2], ParamNames[Position1], H, BoundKind::SimilarAbove);
766 bool A2ToP1Similar = areNamesSimilar(
767 ArgNames[Position1], ParamNames[Position2], H, BoundKind::SimilarAbove);
768
769 bool A1ToP1Dissimilar =
770 !areNamesSimilar(ArgNames[Position1], ParamNames[Position1], H,
771 BoundKind::DissimilarBelow);
772 bool A2ToP2Dissimilar =
773 !areNamesSimilar(ArgNames[Position2], ParamNames[Position2], H,
774 BoundKind::DissimilarBelow);
775
776 if ((A1ToP2Similar || A2ToP1Similar) && A1ToP1Dissimilar &&
777 A2ToP2Dissimilar)
778 return true;
779 }
780 return false;
781}
782
783bool SuspiciousCallArgumentCheck::areNamesSimilar(StringRef Arg,
784 StringRef Param, Heuristic H,
785 BoundKind BK) const {
786 int8_t Threshold = -1;
787 if (std::optional<int8_t> GotBound = getBound(H, BK))
788 Threshold = *GotBound;
789
790 switch (H) {
791 case Heuristic::Equality:
792 return applyEqualityHeuristic(Arg, Param);
793 case Heuristic::Abbreviation:
794 return applyAbbreviationHeuristic(AbbreviationDictionary, Arg, Param);
795 case Heuristic::Prefix:
796 return applyPrefixHeuristic(Arg, Param, Threshold);
797 case Heuristic::Suffix:
798 return applySuffixHeuristic(Arg, Param, Threshold);
799 case Heuristic::Substring:
800 return applySubstringHeuristic(Arg, Param, Threshold);
801 case Heuristic::Levenshtein:
802 return applyLevenshteinHeuristic(Arg, Param, Threshold);
803 case Heuristic::JaroWinkler:
804 return applyJaroWinklerHeuristic(Arg, Param, Threshold);
805 case Heuristic::Dice:
806 return applyDiceHeuristic(Arg, Param, Threshold);
807 }
808 llvm_unreachable("Unhandled heuristic kind");
809}
810
811} // namespace clang::tidy::readability
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
SuspiciousCallArgumentCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
static bool isPointerOrArray(QualType TypeToCheck)
static bool isCompatibleWithArrayReference(QualType ArgType, QualType ParamType, const ASTContext &Ctx)
Checks whether ArgType is an array type identical to ParamType's array type.
static bool arePointerTypesCompatible(QualType ArgType, QualType ParamType, bool IsParamContinuouslyConst, const ASTContext &Ctx)
Checks whether multilevel pointers are compatible in terms of levels, qualifiers and pointee type.
static ClangTidyModuleRegistry::Add< ReadabilityModule > X("readability-module", "Adds readability-related checks.")
static bool areRefAndQualCompatible(QualType ArgType, QualType ParamType, const ASTContext &Ctx)
Checks if ArgType binds to ParamType regarding reference-ness and cv-qualifiers.
static constexpr llvm::StringLiteral DefaultAbbreviations
static bool applyDiceHeuristic(StringRef Arg, StringRef Param, int8_t Threshold)
static QualType convertToPointeeOrArrayElementQualType(QualType TypeToConvert)
static bool applyLevenshteinHeuristic(StringRef Arg, StringRef Param, int8_t Threshold)
static constexpr std::size_t SmallVectorSize
static bool applyJaroWinklerHeuristic(StringRef Arg, StringRef Param, int8_t Threshold)
static bool applySubstringHeuristic(StringRef Arg, StringRef Param, int8_t Threshold)
static double percentage(double X, double Y)
Returns how many % X is of Y.
static bool areTypesCompatible(QualType ArgType, QualType ParamType, const ASTContext &Ctx)
Checks whether ArgType converts implicitly to ParamType.
static constexpr StringRef HeuristicToString[]
static constexpr DefaultHeuristicConfiguration Defaults[]
static bool applyAbbreviationHeuristic(const llvm::StringMap< std::string > &AbbreviationDictionary, StringRef Arg, StringRef Param)
static bool isOverloadedUnaryOrBinarySymbolOperator(const FunctionDecl *FD)
static bool applySuffixHeuristic(StringRef Arg, StringRef Param, int8_t Threshold)
Check whether the shorter String is a suffix of the longer String.
static bool applyEqualityHeuristic(StringRef Arg, StringRef Param)
static constexpr std::size_t DefaultMinimumIdentifierNameLength
static bool arePointersStillQualCompatible(QualType ArgType, QualType ParamType, bool &IsParamContinuouslyConst, const ASTContext &Ctx)
Checks if multilevel pointers' qualifiers compatibility continues on the current pointer level.
static bool applyPrefixHeuristic(StringRef Arg, StringRef Param, int8_t Threshold)
Check whether the shorter String is a prefix of the longer String.
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
std::vector< StringRef > parseStringList(StringRef Option)
Parse a semicolon separated list of strings.
llvm::StringMap< ClangTidyValue > OptionMap