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 (
auto IT = ParamBigrams.begin(); IT != ParamBigrams.end(); ++IT)
292 Intersection += ArgBigrams.count((IT->getKey()));
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() && ParamType->castAsCanonical<EnumType>()
419 (ArgType->isEnumeralType() &&
420 ArgType->castAsCanonical<EnumType>()->getOriginalDecl()->isScoped()))
428 if (ArgType->isFunctionType() && ParamType->isFunctionPointerType()) {
429 ParamType = ParamType->getPointeeType();
430 return ArgType == ParamType;
439 if (IsParamReference && ParamType->isArrayType())
442 bool IsParamContinuouslyConst =
443 !IsParamReference || ParamType.getNonReferenceType().isConstQualified();
450 if (!ParamType.isAtLeastAsQualifiedAs(ArgType, Ctx))
453 if (ParamType.getUnqualifiedType() == ArgType.getUnqualifiedType())
457 if (!Ctx.getLangOpts().CPlusPlus)
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())
470 return ArgDecl->isDerivedFrom(ParamDecl);
475 if (!(ParamType->isAnyPointerType() && ArgType->isAnyPointerType()))
483 switch (FD->getOverloadedOperator()) {
490 case OO_Array_Delete:
496 return FD->getNumParams() <= 2;
503 MinimumIdentifierNameLength(Options.get(
505 auto GetToggleOpt = [
this](Heuristic H) ->
bool {
506 auto Idx =
static_cast<std::size_t
>(H);
510 auto GetBoundOpt = [
this](Heuristic H, BoundKind BK) -> int8_t {
511 auto Idx =
static_cast<std::size_t
>(H);
515 Key.append(BK == BoundKind::DissimilarBelow ?
"DissimilarBelow"
517 int8_t Default = BK == BoundKind::DissimilarBelow
520 return Options.get(Key, Default);
523 auto H =
static_cast<Heuristic
>(Idx);
525 AppliedHeuristics.emplace_back(H);
526 ConfiguredBounds.emplace_back(
527 std::make_pair(GetBoundOpt(H, BoundKind::DissimilarBelow),
528 GetBoundOpt(H, BoundKind::SimilarAbove)));
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()));
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);
548 const auto &SetBoundOpt = [
this, &Opts](Heuristic H, BoundKind BK) ->
void {
549 auto Idx =
static_cast<std::size_t
>(H);
555 Key.append(BK == BoundKind::DissimilarBelow ?
"DissimilarBelow"
557 Options.store(Opts, Key, *getBound(H, BK));
561 auto H =
static_cast<Heuristic
>(Idx);
563 SetBoundOpt(H, BoundKind::DissimilarBelow);
564 SetBoundOpt(H, BoundKind::SimilarAbove);
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);
574 if (!Abbreviation.second.empty())
575 Abbreviations.emplace_back(EqualSignJoined.str());
577 Options.store(Opts,
"Abbreviations",
579 Abbreviations.begin(), Abbreviations.end())));
582bool SuspiciousCallArgumentCheck::isHeuristicEnabled(Heuristic H)
const {
583 return llvm::is_contained(AppliedHeuristics, H);
587SuspiciousCallArgumentCheck::getBound(Heuristic H, BoundKind BK)
const {
588 auto Idx =
static_cast<std::size_t
>(H);
595 case BoundKind::DissimilarBelow:
596 return ConfiguredBounds[Idx].first;
597 case BoundKind::SimilarAbove:
598 return ConfiguredBounds[Idx].second;
600 llvm_unreachable(
"Unhandled Bound kind.");
606 functionDecl(forEachDescendant(callExpr(unless(anyOf(argumentCountIs(0),
607 argumentCountIs(1))))
608 .bind(
"functionCall")))
609 .bind(
"callingFunc"),
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);
620 const Decl *CalleeDecl = MatchedCallExpr->getCalleeDecl();
624 const FunctionDecl *CalleeFuncDecl = CalleeDecl->getAsFunction();
627 if (CalleeFuncDecl == Caller)
634 setParamNamesAndTypes(CalleeFuncDecl);
636 if (ParamNames.empty())
640 std::size_t InitialArgIndex = 0;
642 if (
const auto *MethodDecl = dyn_cast<CXXMethodDecl>(CalleeFuncDecl)) {
643 if (MethodDecl->getParent()->isLambda())
646 else if (MethodDecl->getOverloadedOperator() == OO_Call)
651 setArgNamesAndTypes(MatchedCallExpr, InitialArgIndex);
653 if (ArgNames.empty())
656 std::size_t ParamCount = ParamNames.size();
659 for (std::size_t I = 0; I < ParamCount; ++I) {
660 for (std::size_t J = I + 1; J < ParamCount; ++J) {
662 if (!areParamAndArgComparable(I, J, *Result.Context))
664 if (!areArgsSwapped(I, J))
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();
677 SourceLocation IParNameLoc =
678 CalleeFuncDecl->getParamDecl(I)->getLocation();
679 SourceLocation JParNameLoc =
680 CalleeFuncDecl->getParamDecl(J)->getLocation();
682 diag(CalleeFuncDecl->getLocation(),
"in the call to %0, declared here",
685 << CharSourceRange::getTokenRange(IParNameLoc, IParNameLoc)
686 << CharSourceRange::getTokenRange(JParNameLoc, JParNameLoc);
691void SuspiciousCallArgumentCheck::setParamNamesAndTypes(
692 const FunctionDecl *CalleeFuncDecl) {
698 for (
const ParmVarDecl *Param : CalleeFuncDecl->parameters()) {
699 ParamTypes.push_back(Param->getType());
701 if (IdentifierInfo *II = Param->getIdentifier())
702 ParamNames.push_back(II->getName());
704 ParamNames.push_back(StringRef());
708void SuspiciousCallArgumentCheck::setArgNamesAndTypes(
709 const CallExpr *MatchedCallExpr, std::size_t InitialArgIndex) {
715 for (std::size_t I = InitialArgIndex, J = MatchedCallExpr->getNumArgs();
717 assert(ArgTypes.size() == I - InitialArgIndex &&
718 ArgNames.size() == ArgTypes.size() &&
719 "Every iteration must put an element into the vectors!");
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());
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());
737 ArgTypes.push_back(QualType());
738 ArgNames.push_back(StringRef());
742bool SuspiciousCallArgumentCheck::areParamAndArgComparable(
743 std::size_t Position1, std::size_t Position2,
const ASTContext &Ctx)
const {
744 if (Position1 >= ArgNames.size() || Position2 >= ArgNames.size())
748 if (ArgNames[Position1].size() < MinimumIdentifierNameLength ||
749 ArgNames[Position2].size() < MinimumIdentifierNameLength ||
750 ParamNames[Position1].size() < MinimumIdentifierNameLength ||
751 ParamNames[Position2].size() < MinimumIdentifierNameLength)
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);
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);
776 if ((A1ToP2Similar || A2ToP1Similar) && A1ToP1Dissimilar &&
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;
791 case Heuristic::Equality:
793 case Heuristic::Abbreviation:
795 case Heuristic::Prefix:
797 case Heuristic::Suffix:
799 case Heuristic::Substring:
801 case Heuristic::Levenshtein:
803 case Heuristic::JaroWinkler:
805 case Heuristic::Dice:
808 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