Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,9 @@ void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) {
ReplacementFunction->getName());

// Replace arguments and everything after the function call.
if (FindExpr->getNumArgs() == 0) {
return;
}
Diag << FixItHint::CreateReplacement(
CharSourceRange::getTokenRange(FindExpr->getArg(0)->getBeginLoc(),
ComparisonExpr->getEndLoc()),
Expand All @@ -248,7 +251,6 @@ void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) {
// Add negation if necessary.
if (Neg)
Diag << FixItHint::CreateInsertion(FindExpr->getBeginLoc(), "!");

}

} // namespace clang::tidy::modernize
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Checks for common roundabout ways to express ``starts_with`` and ``ends_with``
and suggests replacing with the simpler method when it is available. Notably,
this will work with ``std::string`` and ``std::string_view``.

The check handles the following expressions:
Covered scenarios:

==================================================== =====================
Expression Replacement
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,10 @@ void test_substr() {
// CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of substr() == [modernize-use-starts-ends-with]
// CHECK-FIXES: str.starts_with(prefix);

str.substr(0, prefix.length()) == prefix;
// CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of substr() == [modernize-use-starts-ends-with]
// CHECK-FIXES: str.starts_with(prefix);

// Tests to verify macro behavior
#define STARTS_WITH(X, Y) (X).substr(0, (Y).size()) == (Y)
STARTS_WITH(str, prefix);
Expand All @@ -308,4 +312,6 @@ void test_substr() {
#define STR() str
SUBSTR(STR(), 0, 6) == "prefix";
"prefix" == SUBSTR(STR(), 0, 6);

str.substr(0, strlen("hello123")) == "hello";
}
Loading