10#include "../utils/OptionsUtils.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/AST/Type.h"
13#include "clang/ASTMatchers/ASTMatchFinder.h"
23struct DefaultHeuristicConfiguration {
47 "Equality",
"Abbreviation",
"Prefix",
"Suffix",
48 "Substring",
"Levenshtein",
"JaroWinkler",
"Dice"};
50static constexpr DefaultHeuristicConfiguration
Defaults[] = {
64 "Ensure that every heuristic has a corresponding stringified name");
67 "Ensure that every heuristic has a default configuration.");
70template <std::
size_t I>
struct HasWellConfiguredBounds {
71 static constexpr bool Value =
73 static_assert(Value,
"A heuristic must either have a dissimilarity and "
74 "similarity bound, or neither!");
77template <std::
size_t I>
struct HasWellConfiguredBoundsFold {
78 static constexpr bool Value = HasWellConfiguredBounds<I>::Value &&
79 HasWellConfiguredBoundsFold<I - 1>::Value;
82template <>
struct HasWellConfiguredBoundsFold<0> {
83 static constexpr bool Value = HasWellConfiguredBounds<0>::Value;
86struct AllHeuristicsBoundsWellConfigured {
87 static constexpr bool Value =
92static_assert(AllHeuristicsBoundsWellConfigured::Value);
131static inline double percentage(
double X,
double Y) {
return X / Y * 100.0; }
134 return Arg.equals_insensitive(Param);
138 const llvm::StringMap<std::string> &AbbreviationDictionary, StringRef Arg,
140 if (AbbreviationDictionary.contains(Arg) &&
141 Param == AbbreviationDictionary.lookup(Arg))
144 if (AbbreviationDictionary.contains(Param) &&
145 Arg == AbbreviationDictionary.lookup(Param))
154 StringRef Shorter = Arg.size() < Param.size() ? Arg : Param;
155 StringRef Longer = Arg.size() >= Param.size() ? Arg : Param;
157 if (Longer.starts_with_insensitive(Shorter))
158 return percentage(Shorter.size(), Longer.size()) > Threshold;
166 StringRef Shorter = Arg.size() < Param.size() ? Arg : Param;
167 StringRef Longer = Arg.size() >= Param.size() ? Arg : Param;
169 if (Longer.ends_with_insensitive(Shorter))
170 return percentage(Shorter.size(), Longer.size()) > Threshold;
178 std::size_t MaxLength = 0;
179 SmallVector<std::size_t, SmallVectorSize> Current(Param.size());
180 SmallVector<std::size_t, SmallVectorSize> Previous(Param.size());
181 std::string ArgLower = Arg.lower();
182 std::string ParamLower = Param.lower();
184 for (std::size_t I = 0; I < Arg.size(); ++I) {
185 for (std::size_t J = 0; J < Param.size(); ++J) {
186 if (ArgLower[I] == ParamLower[J]) {
187 if (I == 0 || J == 0)
190 Current[J] = 1 + Previous[J - 1];
192 MaxLength = std::max(MaxLength, Current[J]);
197 Current.swap(Previous);
200 size_t LongerLength = std::max(Arg.size(), Param.size());
201 return percentage(MaxLength, LongerLength) > Threshold;
206 std::size_t LongerLength = std::max(Arg.size(), Param.size());
207 double Dist = Arg.edit_distance(Param);
208 Dist = (1.0 -
Dist / LongerLength) * 100.0;
209 return Dist > Threshold;
215 std::size_t Match = 0, Transpos = 0;
216 std::ptrdiff_t ArgLen = Arg.size();
217 std::ptrdiff_t ParamLen = Param.size();
218 SmallVector<int, SmallVectorSize> ArgFlags(ArgLen);
219 SmallVector<int, SmallVectorSize> ParamFlags(ParamLen);
220 std::ptrdiff_t
Range =
221 std::max(std::ptrdiff_t{0}, std::max(ArgLen, ParamLen) / 2 - 1);
224 for (std::ptrdiff_t I = 0; I < ParamLen; ++I)
225 for (std::ptrdiff_t J = std::max(I -
Range, std::ptrdiff_t{0}),
226 L = std::min(I +
Range + 1, ArgLen);
228 if (tolower(Param[I]) == tolower(Arg[J]) && !ArgFlags[J]) {
239 std::ptrdiff_t L = 0;
240 for (std::ptrdiff_t I = 0; I < ParamLen; ++I) {
241 if (ParamFlags[I] == 1) {
242 std::ptrdiff_t J = 0;
243 for (J = L; J < ArgLen; ++J)
244 if (ArgFlags[J] == 1) {
249 if (tolower(Param[I]) != tolower(Arg[J]))
256 double MatchD = Match;
257 double Dist = ((MatchD / ArgLen) + (MatchD / ParamLen) +
258 ((MatchD - Transpos) / Match)) /
263 for (std::ptrdiff_t I = 0;
264 I < std::min(std::min(ArgLen, ParamLen), std::ptrdiff_t{4}); ++I)
265 if (tolower(Arg[I]) == tolower(Param[I]))
270 return Dist > Threshold;
276 llvm::StringSet<> ArgBigrams;
277 llvm::StringSet<> ParamBigrams;
280 for (std::ptrdiff_t I = 0; I < static_cast<std::ptrdiff_t>(Arg.size()) - 1;
282 ArgBigrams.insert(Arg.substr(I, 2).lower());
285 for (std::ptrdiff_t I = 0; I < static_cast<std::ptrdiff_t>(Param.size()) - 1;
287 ParamBigrams.insert(Param.substr(I, 2).lower());
289 std::size_t Intersection = 0;
292 for (
auto IT = ParamBigrams.begin(); IT != ParamBigrams.end(); ++IT)
293 Intersection += ArgBigrams.count((IT->getKey()));
297 ArgBigrams.size() + ParamBigrams.size()) > Threshold;
303 const ASTContext &Ctx) {
304 return !ParamType->isReferenceType() ||
305 ParamType.getNonReferenceType().isAtLeastAsQualifiedAs(
306 ArgType.getNonReferenceType(), Ctx);
310 return TypeToCheck->isPointerType() || TypeToCheck->isArrayType();
316 const ASTContext &Ctx) {
317 if (!ArgType->isArrayType())
320 if (!ParamType.isAtLeastAsQualifiedAs(ArgType, Ctx))
323 return ParamType.getUnqualifiedType() == ArgType.getUnqualifiedType();
327 unsigned CVRqualifiers = 0;
330 if (TypeToConvert->isArrayType())
331 CVRqualifiers = TypeToConvert.getLocalQualifiers().getCVRQualifiers();
332 TypeToConvert = TypeToConvert->isPointerType()
333 ? TypeToConvert->getPointeeType()
334 : TypeToConvert->getAsArrayTypeUnsafe()->getElementType();
335 TypeToConvert = TypeToConvert.withCVRQualifiers(CVRqualifiers);
336 return TypeToConvert;
346 bool &IsParamContinuouslyConst,
347 const ASTContext &Ctx) {
351 bool AreTypesQualCompatible =
352 ParamType.isAtLeastAsQualifiedAs(ArgType, Ctx) &&
353 (!ParamType.hasQualifiers() || IsParamContinuouslyConst);
356 IsParamContinuouslyConst &= ParamType.isConstQualified();
358 return AreTypesQualCompatible;
364 bool IsParamContinuouslyConst,
365 const ASTContext &Ctx) {
367 IsParamContinuouslyConst, Ctx))
378 IsParamContinuouslyConst, Ctx))
381 if (ParamType.getUnqualifiedType() == ArgType.getUnqualifiedType())
384 }
while (ParamType->isPointerType() && ArgType->isPointerType());
391 const ASTContext &Ctx) {
392 if (ArgType.isNull() || ParamType.isNull())
395 ArgType = ArgType.getCanonicalType();
396 ParamType = ParamType.getCanonicalType();
398 if (ArgType == ParamType)
405 bool IsParamReference = ParamType->isReferenceType();
409 ArgType = ArgType.getNonReferenceType();
410 ParamType = ParamType.getNonReferenceType();
412 if (ParamType.getUnqualifiedType() == ArgType.getUnqualifiedType())
416 if (ParamType->isArithmeticType() && ArgType->isArithmeticType()) {
417 if ((ParamType->isEnumeralType() &&
418 ParamType->castAs<EnumType>()->getDecl()->isScoped()) ||
419 (ArgType->isEnumeralType() &&
420 ArgType->castAs<EnumType>()->getDecl()->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
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()));
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"
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());
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");
const FunctionDecl * Decl
llvm::SmallString< 256U > Name
CharSourceRange Range
SourceRange for the file name.
const int8_t SimilarAbove
The lower bound of % of similarity the two string must have to be considered similar.
const bool Enabled
Whether the heuristic is to be enabled by default.
const int8_t DissimilarBelow
The upper bound of % of similarity the two strings might have to be considered dissimilar.
std::optional< StringRef > get(StringRef LocalName) const
Read a named option from the Context.
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
static constexpr std::size_t HeuristicCount
SuspiciousCallArgumentCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
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 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