[clang-tools-extra] [clang-tidy] Enhance container-data-pointer-check to suggest `c_str` for consts (PR #190590)

Gaurav Dhingra via cfe-commits cfe-commits at lists.llvm.org
Mon Apr 6 04:23:49 PDT 2026


================
@@ -99,6 +102,46 @@ void ContainerDataPointerCheck::check(const MatchFinder::MatchResult &Result) {
   else if (ACE)
     CE = ACE;
 
+  SourceRange ReplacementRange = UO->getSourceRange();
+  bool UseCStr = false;
+  if (CStrDecl) {
+    auto Parents = Result.Context->getParents(*UO);
+
+    if (!Parents.empty()) {
+      if (const auto *VD = Parents[0].get<VarDecl>()) {
+        QualType VarType = VD->getType();
+        if (VarType->isPointerType()) {
+          QualType PointeeType = VarType->getPointeeType();
+          UseCStr = PointeeType.isConstQualified();
+        }
+      } else if (const auto *ICE = Parents[0].get<ImplicitCastExpr>()) {
+        QualType CastType = ICE->getType();
+        if (CastType->isPointerType()) {
+          QualType PointeeType = CastType->getPointeeType();
+          UseCStr = PointeeType.isConstQualified();
+        }
+      } else if (const auto *Cast = Parents[0].get<CastExpr>()) {
+        QualType CastType = Cast->getType();
+        if (CastType->isPointerType()) {
+          QualType PointeeType = CastType->getPointeeType();
+          UseCStr = PointeeType.isConstQualified();
+          if (UseCStr) {
+            // if it's a const cast, use the Cast range as replacement range
+            // e.g. (const char*)&s[0] -> s.c_str()
+            ReplacementRange = Cast->getSourceRange();
+          }
+        }
----------------
gxyd wrote:

You're right about that, I've merged them into a `get<CastExpr>` check, and deleted the code related to removal of redundant casting.

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


More information about the cfe-commits mailing list