[clang-tools-extra] [clang-tidy] Add modernize-substr-to-starts-with check (PR #116033)

via cfe-commits cfe-commits at lists.llvm.org
Thu Nov 14 07:39:25 PST 2024


================
@@ -173,7 +222,80 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) {
       this);
 }
 
+void UseStartsEndsWithCheck::handleSubstrMatch(const MatchFinder::MatchResult &Result) {
+  const auto *SubstrCall = Result.Nodes.getNodeAs<CXXMemberCallExpr>("substr_fun");
+  const auto *PositiveComparison = Result.Nodes.getNodeAs<Expr>("positiveComparison");
+  const auto *NegativeComparison = Result.Nodes.getNodeAs<Expr>("negativeComparison");
+  
+  if (!SubstrCall || (!PositiveComparison && !NegativeComparison))
+    return;
+
+  bool Negated = NegativeComparison != nullptr;
+  const auto *Comparison = Negated ? NegativeComparison : PositiveComparison;
+  
+  if (SubstrCall->getBeginLoc().isMacroID())
+    return;
+
+  const auto *Str = Result.Nodes.getNodeAs<Expr>("str");
+  const auto *Literal = Result.Nodes.getNodeAs<StringLiteral>("literal");
+  const auto *Length = Result.Nodes.getNodeAs<Expr>("length");
+
+  if (!Str || !Literal || !Length)
+    return;
+
+  // Check if Length is an integer literal and compare with string length
+  if (const auto *LengthInt = dyn_cast<IntegerLiteral>(Length)) {
+    unsigned LitLength = Literal->getLength();
+    unsigned SubstrLength = LengthInt->getValue().getZExtValue();
+    
+    // Only proceed if the lengths match
+    if (SubstrLength != LitLength) {
+      return;
+    }
+  } else {
+    return;  // Non-constant length
+  }
+
+  // Get the string expression
+  std::string StrText = Lexer::getSourceText(
+      CharSourceRange::getTokenRange(Str->getSourceRange()),
+      *Result.SourceManager, getLangOpts()).str();
+
+  // Get the literal text
+  std::string LiteralText = Lexer::getSourceText(
+      CharSourceRange::getTokenRange(Literal->getSourceRange()),
+      *Result.SourceManager, getLangOpts()).str();
+
+  // Build the replacement
+  std::string ReplacementText = (Negated ? "!" : "") + StrText + ".starts_with(" + 
----------------
EugeneZelenko wrote:

```suggestion
  const std::string ReplacementText = (Negated ? "!" : "") + StrText + ".starts_with(" + 
```

https://github.com/llvm/llvm-project/pull/116033


More information about the cfe-commits mailing list