-
Notifications
You must be signed in to change notification settings - Fork 14.9k
[clang-tidy] Enhance modernize-use-starts-ends-with to handle substr patterns #116033
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Thank you for submitting a Pull Request (PR) to the LLVM Project! This PR will be automatically labeled and the relevant teams will be notified. If you wish to, you can add reviewers by using the "Reviewers" section on this page. If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers. If you have further questions, they may be answered by the LLVM GitHub User Guide. You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums. |
@llvm/pr-subscribers-clang-tools-extra @llvm/pr-subscribers-clang-tidy Author: Helmut Januschka (hjanuschka) ChangesAdds a new check that finds calls to substr when its first argument is a zero-equivalent expression and can be replaced with starts_with() (introduced in C++20). This modernization improves code readability by making the intent clearer and can be more efficient as it avoids creating temporary strings. Converts patterns like: The check:
Full diff: https://github.com/llvm/llvm-project/pull/116033.diff 6 Files Affected:
diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index c919d49b42873a..ed1ba2ab62a90f 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -49,6 +49,7 @@ add_clang_library(clangTidyModernizeModule STATIC
UseTransparentFunctorsCheck.cpp
UseUncaughtExceptionsCheck.cpp
UseUsingCheck.cpp
+ SubstrToStartsWithCheck.cpp
LINK_LIBS
clangTidy
diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
index 18607593320635..7569211d2552ea 100644
--- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -50,6 +50,7 @@
#include "UseTransparentFunctorsCheck.h"
#include "UseUncaughtExceptionsCheck.h"
#include "UseUsingCheck.h"
+#include "SubstrToStartsWithCheck.h"
using namespace clang::ast_matchers;
@@ -122,6 +123,8 @@ class ModernizeModule : public ClangTidyModule {
CheckFactories.registerCheck<UseUncaughtExceptionsCheck>(
"modernize-use-uncaught-exceptions");
CheckFactories.registerCheck<UseUsingCheck>("modernize-use-using");
+ CheckFactories.registerCheck<SubstrToStartsWithCheck>(
+ "modernize-substr-to-starts-with");
}
};
diff --git a/clang-tools-extra/clang-tidy/modernize/SubstrToStartsWithCheck.cpp b/clang-tools-extra/clang-tidy/modernize/SubstrToStartsWithCheck.cpp
new file mode 100644
index 00000000000000..b185a2a3b0afc2
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/SubstrToStartsWithCheck.cpp
@@ -0,0 +1,121 @@
+//===--- SubstrToStartsWithCheck.cpp - clang-tidy ------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "SubstrToStartsWithCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+void SubstrToStartsWithCheck::registerMatchers(MatchFinder *Finder) {
+ // Helper matcher to identify expressions that evaluate to 0
+ auto isZeroExpr = expr(anyOf(
+ integerLiteral(equals(0)),
+ ignoringParenImpCasts(declRefExpr(
+ to(varDecl(hasInitializer(integerLiteral(equals(0))))))),
+ binaryOperator(hasOperatorName("-"), hasLHS(expr()), hasRHS(expr()))));
+
+ // Match string literals or string variables
+ auto isStringLike = expr(anyOf(
+ stringLiteral().bind("literal"),
+ implicitCastExpr(hasSourceExpression(stringLiteral().bind("literal"))),
+ declRefExpr(to(varDecl(hasType(qualType(hasDeclaration(
+ namedDecl(hasAnyName("::std::string", "::std::basic_string")))))))).bind("strvar")));
+
+ // Match substr with zero first argument
+ auto isSubstrCall =
+ cxxMemberCallExpr(
+ callee(memberExpr(hasDeclaration(cxxMethodDecl(
+ hasName("substr"),
+ ofClass(hasAnyName("basic_string", "string", "u16string")))))),
+ hasArgument(0, isZeroExpr),
+ hasArgument(1, expr().bind("length")))
+ .bind("substr");
+
+ // Match comparison operations
+ Finder->addMatcher(
+ binaryOperator(
+ anyOf(hasOperatorName("=="), hasOperatorName("!=")),
+ hasEitherOperand(isSubstrCall),
+ hasEitherOperand(isStringLike),
+ unless(hasType(isAnyCharacter())))
+ .bind("comparison"),
+ this);
+
+ // Also match direct substr calls that could be starts_with
+ Finder->addMatcher(
+ cxxMemberCallExpr(
+ callee(memberExpr(hasDeclaration(cxxMethodDecl(
+ hasName("substr"),
+ ofClass(hasAnyName("basic_string", "string", "u16string")))))),
+ hasArgument(0, isZeroExpr),
+ hasArgument(1, expr().bind("direct_length")))
+ .bind("direct_substr"),
+ this);
+}
+
+void SubstrToStartsWithCheck::check(const MatchFinder::MatchResult &Result) {
+ const auto *Comparison = Result.Nodes.getNodeAs<BinaryOperator>("comparison");
+ const auto *DirectSubstr =
+ Result.Nodes.getNodeAs<CXXMemberCallExpr>("direct_substr");
+
+ // Handle comparison cases
+ if (Comparison) {
+ const auto *SubstrCall = Result.Nodes.getNodeAs<CXXMemberCallExpr>("substr");
+ const auto *LengthArg = Result.Nodes.getNodeAs<Expr>("length");
+ const auto *Literal = Result.Nodes.getNodeAs<StringLiteral>("literal");
+ const auto *StrVar = Result.Nodes.getNodeAs<DeclRefExpr>("strvar");
+
+ if (!SubstrCall || !LengthArg || (!Literal && !StrVar))
+ return;
+
+ std::string CompareStr;
+ if (Literal) {
+ CompareStr = Literal->getString().str();
+ } else if (StrVar) {
+ CompareStr = Lexer::getSourceText(
+ CharSourceRange::getTokenRange(StrVar->getSourceRange()),
+ *Result.SourceManager, Result.Context->getLangOpts())
+ .str();
+ }
+
+ // Check if the length matches the string literal length
+ if (Literal) {
+ if (const auto *LengthLiteral = dyn_cast<IntegerLiteral>(LengthArg)) {
+ if (LengthLiteral->getValue() != Literal->getLength())
+ return;
+ }
+ }
+
+ // Build replacement
+ std::string Replacement;
+ if (Comparison->getOpcode() == BO_EQ) {
+ Replacement = "starts_with(" + CompareStr + ")";
+ } else { // BO_NE
+ Replacement = "!starts_with(" + CompareStr + ")";
+ }
+
+ diag(Comparison->getBeginLoc(),
+ "use starts_with() instead of substring comparison")
+ << FixItHint::CreateReplacement(Comparison->getSourceRange(),
+ Replacement);
+ }
+
+ // Handle direct substr calls
+ if (DirectSubstr) {
+ diag(DirectSubstr->getBeginLoc(),
+ "consider using starts_with() if this substr is used for prefix "
+ "checking");
+ }
+}
+
+} // namespace clang::tidy::modernize
\ No newline at end of file
diff --git a/clang-tools-extra/clang-tidy/modernize/SubstrToStartsWithCheck.h b/clang-tools-extra/clang-tidy/modernize/SubstrToStartsWithCheck.h
new file mode 100644
index 00000000000000..fdb157ca0a24fb
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/SubstrToStartsWithCheck.h
@@ -0,0 +1,30 @@
+//===--- SubstrToStartsWithCheck.h - clang-tidy ------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_SUBSTRTOSTARTSWITHCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_SUBSTRTOSTARTSWITHCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang::tidy::modernize {
+
+/// Finds calls to substr(0, n) that can be replaced with starts_with().
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/modernize/substr-to-starts-with.html
+class SubstrToStartsWithCheck : public ClangTidyCheck {
+public:
+ SubstrToStartsWithCheck(StringRef Name, ClangTidyContext *Context)
+ : ClangTidyCheck(Name, Context) {}
+ void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+ void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+};
+
+} // namespace clang::tidy::modernize
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_SUBSTRTOSTARTSWITHCHECK_H
diff --git a/clang-tools-extra/docs/clang-tidy/checks/modernize/substr-to-starts-with.rst b/clang-tools-extra/docs/clang-tidy/checks/modernize/substr-to-starts-with.rst
new file mode 100644
index 00000000000000..88a9c311eb6737
--- /dev/null
+++ b/clang-tools-extra/docs/clang-tidy/checks/modernize/substr-to-starts-with.rst
@@ -0,0 +1,38 @@
+modernize-substr-to-starts-with
+==============================
+
+Finds calls to ``substr(0, n)`` that can be replaced with ``starts_with()`` (introduced in C++20).
+This makes the code's intent clearer and can be more efficient as it avoids creating temporary strings.
+
+For example:
+
+.. code-block:: c++
+
+ str.substr(0, 3) == "foo" // before
+ str.starts_with("foo") // after
+
+ "bar" == str.substr(0, 3) // before
+ str.starts_with("bar") // after
+
+ str.substr(0, n) == prefix // before
+ str.starts_with(prefix) // after
+
+The check handles various ways of expressing zero as the start index:
+
+.. code-block:: c++
+
+ const int zero = 0;
+ str.substr(zero, n) == prefix // converted
+ str.substr(x - x, n) == prefix // converted
+
+The check will only convert cases where:
+* The substr call starts at index 0 (or equivalent)
+* When comparing with string literals, the length matches exactly
+* The comparison is with == or !=
+
+The check will also warn about standalone substr calls that might be candidates
+for conversion to starts_with:
+
+.. code-block:: c++
+
+ auto prefix = str.substr(0, n); // warns about possible use of starts_with
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/substr-to-starts-with.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/substr-to-starts-with.cpp
new file mode 100644
index 00000000000000..41b59903e605d7
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/substr-to-starts-with.cpp
@@ -0,0 +1,41 @@
+// RUN: %check_clang_tidy %s modernize-substr-to-starts-with %t
+
+#include <string>
+
+void test() {
+ std::string str = "hello world";
+ if (str.substr(0, 5) == "hello") {}
+ // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use starts_with() instead of substring comparison
+ // CHECK-FIXES: if (str.starts_with("hello")) {}
+
+ if ("hello" == str.substr(0, 5)) {}
+ // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: use starts_with() instead of substring comparison
+ // CHECK-FIXES: if (str.starts_with("hello")) {}
+
+ bool b = str.substr(0, 5) != "hello";
+ // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: use starts_with() instead of substring comparison
+ // CHECK-FIXES: bool b = !str.starts_with("hello");
+
+ // Variable length and string refs
+ std::string prefix = "hello";
+ size_t len = 5;
+ if (str.substr(0, len) == prefix) {}
+ // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use starts_with() instead of substring comparison
+ // CHECK-FIXES: if (str.starts_with(prefix)) {}
+
+ // Various zero expressions
+ const int zero = 0;
+ int i = 0;
+ if (str.substr(zero, 5) == "hello") {}
+ // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use starts_with() instead of substring comparison
+ // CHECK-FIXES: if (str.starts_with("hello")) {}
+
+ if (str.substr(i-i, 5) == "hello") {}
+ // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use starts_with() instead of substring comparison
+ // CHECK-FIXES: if (str.starts_with("hello")) {}
+
+ // Should not convert these
+ if (str.substr(1, 5) == "hello") {} // Non-zero start
+ if (str.substr(0, 4) == "hello") {} // Length mismatch
+ if (str.substr(0, 6) == "hello") {} // Length mismatch
+}
|
9df25db
to
adafcce
Compare
I think |
Agreed! |
ok will refactor the PR
…--
Helmut Januschka
Am 13. November 2024 um 16:28:52, Carlos Galvez ***@***.*** ***@***.***> ) schrieb:
I think modernize-use-starts-ends-with should be extended instead.
Agreed!
—
Reply to this email directly, view it on GitHub <#116033 (comment)> , or unsubscribe <https://github.com/notifications/unsubscribe-auth/AAWB7NRJGYC5TMVUAHJNLTL2ANV3JAVCNFSM6AAAAABRWJ3CJOVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDINZTHE2DQOJZGA> .
You are receiving this because you authored the thread. <https://github.com/notifications/beacon/AAWB7NV5DUBN3ZC3JFXW7T32ANV3JA5CNFSM6AAAAABRWJ3CJOWGG33NNVSW45C7OR4XAZNMJFZXG5LFINXW23LFNZ2KUY3PNVWWK3TUL5UWJTUTOV3T4.gif> Message ID: ***@***.***>
|
clang-tools-extra/docs/clang-tidy/checks/modernize/substr-to-starts-with.rst
Outdated
Show resolved
Hide resolved
…or message In one of the cases recently added to this check in llvm#110448, the error message is no longer accurate as the comparison is not with zero. llvm#116033 brought my attention to this as it may add another comparison without zero. Remove the `[!=] 0` part of the diagnostic. This is in line with some other checks e.g. modernize-use-emplace. ``` > cat tmp.cpp #include <string> bool f(std::string u, std::string v) { return u.rfind(v) == u.size() - v.size(); } # Before. > ./build/bin/clang-tidy -checks="-*,modernize-use-starts-ends-with" tmp.cpp -- -std=c++20 tmp.cpp:3:12: warning: use ends_with instead of rfind() == 0 [modernize-use-starts-ends-with] 3 | return u.rfind(v) == u.size() - v.size(); | ^~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~ | ends_with( ) # After. > ./build/bin/clang-tidy -checks="-*,modernize-use-starts-ends-with" tmp.cpp -- -std=c++20 tmp.cpp:3:12: warning: use ends_with instead of rfind [modernize-use-starts-ends-with] 3 | return u.rfind(v) == u.size() - v.size(); | ^~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~ | ends_with( ) ```
refactored and integrated into existing checker. seems to work, with my local test.cpp files. .substr() is undefined.
any advice? or sample where i can take a look how to get a real std::string or how to mock it? |
Tests use mock-up header ( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please mention changes in Release Notes.
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.h
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.h
Outdated
Show resolved
Hide resolved
clang-tools-extra/docs/clang-tidy/checks/modernize/use-starts-ends-with.rst
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This feels very intrusive, a lot should be able to be re-used from things already used in the matcher. I expect something like this would be sufficient:
Finder->addMatcher(
cxxOperatorCallExpr(
hasAnyOperatorName("==", "!="),
hasOperands(
expr().bind("needle"),
cxxMemberCallExpr(
argumentCountIs(2), hasArgument(0, ZeroLiteral),
hasArgument(1, lengthExprForStringNode("needle")),
callee(cxxMethodDecl(hasName("substr"),
ofClass(OnClassWithStartsWithFunction))
.bind("find_fun")))
.bind("find_expr")))
.bind("expr"),
this);
I expect that the only change in check
would be related to the negation since this will cause some segmentation fault from always getting it as a BinaryOperator
.
Please change pull request title. |
e549c1a
to
caddb82
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@EugeneZelenko @nicovank
thank you for your feedback, addressed what's possible.
- added tests
- release notes
- various const's
@nicovank about your suggestion, played around few hours with it, but could make a sense out of it, that was initially the reason why i started it as a standalone new check.
also, is it "ok" to change existing tidy's? like people opted in for one, and that changes now without them knowing?
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/docs/clang-tidy/checks/modernize/use-starts-ends-with.rst
Outdated
Show resolved
Hide resolved
@HerrCai0907 about the fixit. its strange, using the llvm-lit test case it emits a warning, and even shows where the substr() comes from:
to reduce the complexity and test it tried to: // RUN: %check_clang_tidy -std=c++20 %s modernize-use-starts-ends-with %t -- -debug
#include <string>
void test_macro_case() {
std::string str("hello world");
#define SUBSTR(X, A, B) (X).substr((A), (B))
#define STR() str
"prefix" == SUBSTR(STR(), 0, 6);
} ./bin/clang-tidy test.cpp -checks="-*, modernize-use-starts-ends-with" --extra-arg=-std=c++20 - doesnt even come up with a warning. i dont know whats "right" now, warning and showing root cause, seems to be fairly good, fixing a macro might be even a bad idea? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good minus nits and IMO ignore any macro issues as commented.
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
@nicovank feedback addressed, except macro exclusion, not sure about it, it breaks alot of pre-existing tests |
clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM! Thanks!
…s-ends-with.cpp Co-authored-by: Nicolas van Kempen <[email protected]>
@EugeneZelenko your comments have been resolved, but i am unable to mark them due to force push |
Great! Anyway, I look mostly on documentation and minor coding style issues, so developers with more knowledge should approve this merge request. Maybe @5chmidti (who is active recently) should take a look too. |
@nicovank hows the protocol to get the other reviewers in?, should i ping them - or should i just practice patience? |
@hjanuschka Let's give it another day or so then I’ll go ahead and click merge if there are no other comments 👍 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Current version looks fine.
Take a look into comments, if something could be improved.
Ping once you finish (looking and/or fixing), so it could be merged.
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/docs/clang-tidy/checks/modernize/use-starts-ends-with.rst
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp
Show resolved
Hide resolved
clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
// Retrieve the source text of the search expression. | ||
const auto SearchExprText = Lexer::getSourceText( | ||
CharSourceRange::getTokenRange(SearchExpr->getSourceRange()), | ||
*Result.SourceManager, Result.Context->getLangOpts()); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Getting the source text is a bit unfortunate, as this will expand macros, but I don't think it can be avoided because it is needed to be able to swap the operator sides. E.g.: needle == haystack.substr(0, 6)
-> haystack.starts_with(needle)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
so we can keep it?
if (ComparisonExpr->getBeginLoc().isMacroID() ||
FindExpr->getBeginLoc().isMacroID())
return;
shouldn't that skip macros?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There are probably edge cases which I don't expect to be present in real code but maybe I'll be proven wrong. I also think grabbing source text of either the haystack or needle is necessary here because of the possible swap.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
shouldn't that skip macros?
Only at the checked positions. E.g., the needle may still be a macro (as per the test you've added from my comment).
clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
feedback addressed, not sure how to proceed with output format changes
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
Co-authored-by: Nicolas van Kempen <[email protected]>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
feedback addressed
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM minus 1 nit. Thanks!
clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM, thanks
@nicovank all good now? |
Thanks for the ping. Great! Thanks a lot for the improvement 🙏 Merging now. This is a clear performance bad pattern, and seems pretty widespread (25k matches, minus of course some false positives in the regex search). I think |
@hjanuschka Congratulations on having your first Pull Request (PR) merged into the LLVM Project! Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR. Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues. How to do this, and the rest of the post-merge process, is covered in detail here. If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again. If you don't get any reports, no action is required from you. Your changes are working as expected, well done! |
awesome! thanks to everyone involved for the patience with me and the great guidance! |
@hjanuschka: Thank you for helping all poor souls like me with looming C++20/23 migration in some code bases :-) |
Enhances the modernize-use-starts-ends-with check to detect additional patterns using substr that can be replaced with starts_with() (C++20). This enhancement improves code readability and can be more efficient by avoiding temporary string creation.
New patterns detected:
The enhancement:
This builds upon the existing modernize-use-starts-ends-with check, adding more patterns while maintaining the existing functionality for find(), rfind(), and compare() based patterns.