11#include "clang/AST/ASTContext.h"
12#include "clang/AST/Type.h"
13#include "clang/ASTMatchers/ASTMatchFinder.h"
22struct DefaultHeuristicConfiguration {
30 const int8_t DissimilarBelow;
36 const int8_t SimilarAbove;
39 bool hasBounds()
const {
return DissimilarBelow > -1 && SimilarAbove > -1; }
46 "Equality",
"Abbreviation",
"Prefix",
"Suffix",
47 "Substring",
"Levenshtein",
"JaroWinkler",
"Dice"};
49static constexpr DefaultHeuristicConfiguration
Defaults[] = {
63 "Ensure that every heuristic has a corresponding stringified name");
66 "Ensure that every heuristic has a default configuration.");
69template <std::
size_t I>
struct HasWellConfiguredBounds {
70 static constexpr bool Value =
72 static_assert(Value,
"A heuristic must either have a dissimilarity and "
73 "similarity bound, or neither!");
76template <std::
size_t I>
struct HasWellConfiguredBoundsFold {
77 static constexpr bool Value = HasWellConfiguredBounds<I>::Value &&
78 HasWellConfiguredBoundsFold<I - 1>::Value;
81template <>
struct HasWellConfiguredBoundsFold<0> {
82 static constexpr bool Value = HasWellConfiguredBounds<0>::Value;
85struct AllHeuristicsBoundsWellConfigured {
86 static constexpr bool Value =
91static_assert(AllHeuristicsBoundsWellConfigured::Value);
130static inline double percentage(
double X,
double Y) {
return X / Y * 100.0; }
133 return Arg.equals_insensitive(Param);
137 const llvm::StringMap<std::string> &AbbreviationDictionary, StringRef Arg,
139 if (AbbreviationDictionary.contains(Arg) &&
140 Param == AbbreviationDictionary.lookup(Arg))
143 if (AbbreviationDictionary.contains(Param) &&
144 Arg == AbbreviationDictionary.lookup(Param))
153 StringRef Shorter = Arg.size() < Param.size() ? Arg : Param;
154 StringRef Longer = Arg.size() >= Param.size() ? Arg : Param;
156 if (Longer.starts_with_insensitive(Shorter))
157 return percentage(Shorter.size(), Longer.size()) > Threshold;
165 StringRef Shorter = Arg.size() < Param.size() ? Arg : Param;
166 StringRef Longer = Arg.size() >= Param.size() ? Arg : Param;
168 if (Longer.ends_with_insensitive(Shorter))
169 return percentage(Shorter.size(), Longer.size()) > Threshold;
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();
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)
189 Current[J] = 1 + Previous[J - 1];
191 MaxLength = std::max(MaxLength, Current[J]);
196 Current.swap(Previous);
199 size_t LongerLength = std::max(Arg.size(), Param.size());
200 return percentage(MaxLength, LongerLength) > 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;
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);
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);
227 if (tolower(Param[I]) == tolower(Arg[J]) && !ArgFlags[J]) {
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) {
248 if (tolower(Param[I]) != tolower(Arg[J]))
255 double MatchD = Match;
256 double Dist = ((MatchD / ArgLen) + (MatchD / ParamLen) +
257 ((MatchD - Transpos) / Match)) /
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]))
268 Dist = (Dist + (L * 0.1 * (1.0 - Dist))) * 100.0;
269 return Dist > Threshold;
275 llvm::StringSet<> ArgBigrams;
276 llvm::StringSet<> ParamBigrams;
279 for (std::ptrdiff_t I = 0; I < static_cast<std::ptrdiff_t>(Arg.size()) - 1;
281 ArgBigrams.insert(Arg.substr(I, 2).lower());
284 for (std::ptrdiff_t I = 0; I < static_cast<std::ptrdiff_t>(Param.size()) - 1;
286 ParamBigrams.insert(Param.substr(I, 2).lower());
288 std::size_t Intersection = 0;
291 for (
const auto &[Key, _] : ParamBigrams)
292 Intersection += ArgBigrams.count(Key);
296 ArgBigrams.size() + ParamBigrams.size()) > Threshold;
302 const ASTContext &Ctx) {
303 return !ParamType->isReferenceType() ||
304 ParamType.getNonReferenceType().isAtLeastAsQualifiedAs(
305 ArgType.getNonReferenceType(), Ctx);
309 return TypeToCheck->isPointerType() || TypeToCheck->isArrayType();
315 const ASTContext &Ctx) {
316 if (!ArgType->isArrayType())
319 if (!ParamType.isAtLeastAsQualifiedAs(ArgType, Ctx))
322 return ParamType.getUnqualifiedType() == ArgType.getUnqualifiedType();
326 unsigned CVRqualifiers = 0;
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;
345 bool &IsParamContinuouslyConst,
346 const ASTContext &Ctx) {
350 bool AreTypesQualCompatible =
351 ParamType.isAtLeastAsQualifiedAs(ArgType, Ctx) &&
352 (!ParamType.hasQualifiers() || IsParamContinuouslyConst);
355 IsParamContinuouslyConst &= ParamType.isConstQualified();
357 return AreTypesQualCompatible;
363 bool IsParamContinuouslyConst,
364 const ASTContext &Ctx) {
366 IsParamContinuouslyConst, Ctx))
377 IsParamContinuouslyConst, Ctx))
380 if (ParamType.getUnqualifiedType() == ArgType.getUnqualifiedType())
383 }
while (ParamType->isPointerType() && ArgType->isPointerType());
390 const ASTContext &Ctx) {
391 if (ArgType.isNull() || ParamType.isNull())
394 ArgType = ArgType.getCanonicalType();
395 ParamType = ParamType.getCanonicalType();
397 if (ArgType == ParamType)
404 bool IsParamReference = ParamType->isReferenceType();
408 ArgType = ArgType.getNonReferenceType();
409 ParamType = ParamType.getNonReferenceType();
411 if (ParamType.getUnqualifiedType() == ArgType.getUnqualifiedType())
415 if (ParamType->isArithmeticType() && ArgType->isArithmeticType()) {
416 if ((ParamType->isEnumeralType() &&
417 ParamType->castAsCanonical<EnumType>()->getDecl()->isScoped()) ||
418 (ArgType->isEnumeralType() &&
419 ArgType->castAsCanonical<EnumType>()->getDecl()->isScoped()))
427 if (ArgType->isFunctionType() && ParamType->isFunctionPointerType()) {
428 ParamType = ParamType->getPointeeType();
429 return ArgType == ParamType;
438 if (IsParamReference && ParamType->isArrayType())
441 bool IsParamContinuouslyConst =
442 !IsParamReference || ParamType.getNonReferenceType().isConstQualified();
449 if (!ParamType.isAtLeastAsQualifiedAs(ArgType, Ctx))
452 if (ParamType.getUnqualifiedType() == ArgType.getUnqualifiedType())
456 if (!Ctx.getLangOpts().CPlusPlus)
461 if (ParamType->isStructureOrClassType() &&
462 ArgType->isStructureOrClassType()) {
463 const auto *ArgDecl = ArgType->getAsCXXRecordDecl();
464 const auto *ParamDecl = ParamType->getAsCXXRecordDecl();
465 if (!ArgDecl || !ArgDecl->hasDefinition() || !ParamDecl ||
466 !ParamDecl->hasDefinition())
469 return ArgDecl->isDerivedFrom(ParamDecl);
474 if (!(ParamType->isAnyPointerType() && ArgType->isAnyPointerType()))
482 switch (FD->getOverloadedOperator()) {
489 case OO_Array_Delete:
495 return FD->getNumParams() <= 2;
502 MinimumIdentifierNameLength(Options.get(
504 auto GetToggleOpt = [
this](Heuristic H) ->
bool {
505 auto Idx =
static_cast<std::size_t
>(H);
509 auto GetBoundOpt = [
this](Heuristic H, BoundKind BK) -> int8_t {
510 auto Idx =
static_cast<std::size_t
>(H);
514 Key.append(BK == BoundKind::DissimilarBelow ?
"DissimilarBelow"
516 int8_t Default = BK == BoundKind::DissimilarBelow
519 return Options.get(Key, Default);
522 auto H =
static_cast<Heuristic
>(Idx);
524 AppliedHeuristics.emplace_back(H);
525 ConfiguredBounds.emplace_back(
526 std::make_pair(GetBoundOpt(H, BoundKind::DissimilarBelow),
527 GetBoundOpt(H, BoundKind::SimilarAbove)));
532 auto KeyAndValue = Abbreviation.split(
"=");
533 assert(!KeyAndValue.first.empty() && !KeyAndValue.second.empty());
534 AbbreviationDictionary.insert(
535 std::make_pair(KeyAndValue.first, KeyAndValue.second.str()));
541 Options.store(Opts,
"MinimumIdentifierNameLength",
542 MinimumIdentifierNameLength);
543 const auto &SetToggleOpt = [
this, &Opts](Heuristic H) ->
void {
544 auto Idx =
static_cast<std::size_t
>(H);
547 const auto &SetBoundOpt = [
this, &Opts](Heuristic H, BoundKind BK) ->
void {
548 auto Idx =
static_cast<std::size_t
>(H);
554 Key.append(BK == BoundKind::DissimilarBelow ?
"DissimilarBelow"
556 Options.store(Opts, Key, *getBound(H, BK));
560 auto H =
static_cast<Heuristic
>(Idx);
562 SetBoundOpt(H, BoundKind::DissimilarBelow);
563 SetBoundOpt(H, BoundKind::SimilarAbove);
566 SmallVector<std::string, 32> Abbreviations;
567 for (
const auto &Abbreviation : AbbreviationDictionary) {
568 SmallString<32> EqualSignJoined;
569 EqualSignJoined.append(Abbreviation.first());
570 EqualSignJoined.append(
"=");
571 EqualSignJoined.append(Abbreviation.second);
573 if (!Abbreviation.second.empty())
574 Abbreviations.emplace_back(EqualSignJoined.str());
576 Options.store(Opts,
"Abbreviations",
578 Abbreviations.begin(), Abbreviations.end())));
581bool SuspiciousCallArgumentCheck::isHeuristicEnabled(Heuristic H)
const {
582 return llvm::is_contained(AppliedHeuristics, H);
586SuspiciousCallArgumentCheck::getBound(Heuristic H, BoundKind BK)
const {
587 auto Idx =
static_cast<std::size_t
>(H);
594 case BoundKind::DissimilarBelow:
595 return ConfiguredBounds[Idx].first;
596 case BoundKind::SimilarAbove:
597 return ConfiguredBounds[Idx].second;
599 llvm_unreachable(
"Unhandled Bound kind.");
605 functionDecl(forEachDescendant(callExpr(unless(anyOf(argumentCountIs(0),
606 argumentCountIs(1))))
607 .bind(
"functionCall")))
608 .bind(
"callingFunc"),
613 const MatchFinder::MatchResult &Result) {
614 const auto *MatchedCallExpr =
615 Result.Nodes.getNodeAs<CallExpr>(
"functionCall");
616 const auto *Caller = Result.Nodes.getNodeAs<FunctionDecl>(
"callingFunc");
617 assert(MatchedCallExpr && Caller);
619 const Decl *CalleeDecl = MatchedCallExpr->getCalleeDecl();
623 const FunctionDecl *CalleeFuncDecl = CalleeDecl->getAsFunction();
626 if (CalleeFuncDecl == Caller)
633 setParamNamesAndTypes(CalleeFuncDecl);
635 if (ParamNames.empty())
639 std::size_t InitialArgIndex = 0;
641 if (
const auto *MethodDecl = dyn_cast<CXXMethodDecl>(CalleeFuncDecl)) {
642 if (MethodDecl->getParent()->isLambda())
645 else if (MethodDecl->getOverloadedOperator() == OO_Call)
650 setArgNamesAndTypes(MatchedCallExpr, InitialArgIndex);
652 if (ArgNames.empty())
655 std::size_t ParamCount = ParamNames.size();
658 for (std::size_t I = 0; I < ParamCount; ++I) {
659 for (std::size_t J = I + 1; J < ParamCount; ++J) {
661 if (!areParamAndArgComparable(I, J, *Result.Context))
663 if (!areArgsSwapped(I, J))
667 diag(MatchedCallExpr->getExprLoc(),
668 "%ordinal0 argument '%1' (passed to '%2') looks like it might be "
669 "swapped with the %ordinal3, '%4' (passed to '%5')")
670 <<
static_cast<unsigned>(I + 1) << ArgNames[I] << ParamNames[I]
671 <<
static_cast<unsigned>(J + 1) << ArgNames[J] << ParamNames[J]
672 << MatchedCallExpr->getArg(I)->getSourceRange()
673 << MatchedCallExpr->getArg(J)->getSourceRange();
676 SourceLocation IParNameLoc =
677 CalleeFuncDecl->getParamDecl(I)->getLocation();
678 SourceLocation JParNameLoc =
679 CalleeFuncDecl->getParamDecl(J)->getLocation();
681 diag(CalleeFuncDecl->getLocation(),
"in the call to %0, declared here",
684 << CharSourceRange::getTokenRange(IParNameLoc, IParNameLoc)
685 << CharSourceRange::getTokenRange(JParNameLoc, JParNameLoc);
690void SuspiciousCallArgumentCheck::setParamNamesAndTypes(
691 const FunctionDecl *CalleeFuncDecl) {
697 for (
const ParmVarDecl *Param : CalleeFuncDecl->parameters()) {
698 ParamTypes.push_back(Param->getType());
700 if (IdentifierInfo *II = Param->getIdentifier())
701 ParamNames.push_back(II->getName());
703 ParamNames.push_back(StringRef());
707void SuspiciousCallArgumentCheck::setArgNamesAndTypes(
708 const CallExpr *MatchedCallExpr, std::size_t InitialArgIndex) {
714 for (std::size_t I = InitialArgIndex, J = MatchedCallExpr->getNumArgs();
716 assert(ArgTypes.size() == I - InitialArgIndex &&
717 ArgNames.size() == ArgTypes.size() &&
718 "Every iteration must put an element into the vectors!");
720 if (
const auto *ArgExpr = dyn_cast<DeclRefExpr>(
721 MatchedCallExpr->getArg(I)->IgnoreUnlessSpelledInSource())) {
722 if (
const auto *Var = dyn_cast<VarDecl>(ArgExpr->getDecl())) {
723 ArgTypes.push_back(Var->getType());
724 ArgNames.push_back(Var->getName());
727 if (
const auto *FCall = dyn_cast<FunctionDecl>(ArgExpr->getDecl())) {
728 if (FCall->getNameInfo().getName().isIdentifier()) {
729 ArgTypes.push_back(FCall->getType());
730 ArgNames.push_back(FCall->getName());
736 ArgTypes.push_back(QualType());
737 ArgNames.push_back(StringRef());
741bool SuspiciousCallArgumentCheck::areParamAndArgComparable(
742 std::size_t Position1, std::size_t Position2,
const ASTContext &Ctx)
const {
743 if (Position1 >= ArgNames.size() || Position2 >= ArgNames.size())
747 if (ArgNames[Position1].size() < MinimumIdentifierNameLength ||
748 ArgNames[Position2].size() < MinimumIdentifierNameLength ||
749 ParamNames[Position1].size() < MinimumIdentifierNameLength ||
750 ParamNames[Position2].size() < MinimumIdentifierNameLength)
760bool SuspiciousCallArgumentCheck::areArgsSwapped(std::size_t Position1,
761 std::size_t Position2)
const {
762 for (Heuristic H : AppliedHeuristics) {
763 bool A1ToP2Similar = areNamesSimilar(
764 ArgNames[Position2], ParamNames[Position1], H, BoundKind::SimilarAbove);
765 bool A2ToP1Similar = areNamesSimilar(
766 ArgNames[Position1], ParamNames[Position2], H, BoundKind::SimilarAbove);
768 bool A1ToP1Dissimilar =
769 !areNamesSimilar(ArgNames[Position1], ParamNames[Position1], H,
770 BoundKind::DissimilarBelow);
771 bool A2ToP2Dissimilar =
772 !areNamesSimilar(ArgNames[Position2], ParamNames[Position2], H,
773 BoundKind::DissimilarBelow);
775 if ((A1ToP2Similar || A2ToP1Similar) && A1ToP1Dissimilar &&
782bool SuspiciousCallArgumentCheck::areNamesSimilar(StringRef Arg,
783 StringRef Param, Heuristic H,
784 BoundKind BK)
const {
785 int8_t Threshold = -1;
786 if (std::optional<int8_t> GotBound = getBound(H, BK))
787 Threshold = *GotBound;
790 case Heuristic::Equality:
792 case Heuristic::Abbreviation:
794 case Heuristic::Prefix:
796 case Heuristic::Suffix:
798 case Heuristic::Substring:
800 case Heuristic::Levenshtein:
802 case Heuristic::JaroWinkler:
804 case Heuristic::Dice:
807 llvm_unreachable(
"Unhandled heuristic kind");
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
static constexpr std::size_t HeuristicCount
SuspiciousCallArgumentCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
static constexpr std::size_t SmallVectorSize
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