[clang] [-Wunsafe-buffer-usage] Minimize fixit range for pointer variables (PR #81935)

Ziqing Luo via cfe-commits cfe-commits at lists.llvm.org
Fri Feb 16 14:19:41 PST 2024


================
@@ -2326,15 +2312,21 @@ static FixItList fixLocalVarDeclWithSpan(const VarDecl *D, ASTContext &Ctx,
       return {};
     FixIts.insert(FixIts.end(), std::make_move_iterator(InitFixIts->begin()),
                   std::make_move_iterator(InitFixIts->end()));
-    // If the declaration has the form `T *ident = init`, we want to replace
-    // `T *ident = ` with `std::span<T> ident`:
-    EndLocForReplacement = Init->getBeginLoc().getLocWithOffset(-1);
   }
-  SS << " " << IdentText->str();
+  // For declaration of the form `T * ident = init;`, we want to replace
+  // `T * ` with `std::span<T>`.
+  // We ignore CV-qualifiers so for `T * const ident;` we also want to replace
+  // just `T *` with `std::span<T>`.
+  const SourceLocation EndLocForReplacement = D->getTypeSpecEndLoc();
   if (!EndLocForReplacement.isValid()) {
     DEBUG_NOTE_DECL_FAIL(D, " : failed to locate the end of the declaration");
     return {};
   }
+  // The only exception is that for `T *ident` we'll add a single space between
+  // "std::span<T>" and "ident".
+  if (EndLocForReplacement.getLocWithOffset(1) == getVarDeclIdentifierLoc(D))
----------------
ziqingluo-90 wrote:

In case the identifier is a macro expansion, e.g., 
```
#define IDENT ident
T *IDENT;
```
, the if-condition will evaluate to false because the files of the two source locations are different.  
But this is rare and the fix-it is still correct.

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


More information about the cfe-commits mailing list