[clang] [clang] Fix-it hint for `++this` -> `++*this` when deref is modifiable (PR #94159)

via cfe-commits cfe-commits at lists.llvm.org
Thu Jun 6 06:27:13 PDT 2024


================
@@ -13587,10 +13602,47 @@ static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
   SourceRange Assign;
   if (Loc != OrigLoc)
     Assign = SourceRange(OrigLoc, OrigLoc);
-  if (NeedType)
+  if (NeedType) {
     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
-  else
+  } else {
+    ExprResult Deref;
+    {
+      Sema::TentativeAnalysisScope Trap(S);
+      Deref = S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, E);
+    }
     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
+    if (Deref.isUsable() &&
+        Deref.get()->isModifiableLvalue(S.Context, &Loc) == Expr::MLV_Valid) {
+      std::string exprType;
+      switch (E->getStmtClass()) {
+      case Stmt::CStyleCastExprClass: {
+        const auto *CSC = cast<CStyleCastExpr>(E);
+        exprType = CSC->getType().getAsString();
+        break;
+      }
+      case Stmt::CXXConstCastExprClass: {
+        const auto *CXXCCE = cast<CXXConstCastExpr>(E);
+        exprType = CXXCCE->getTypeAsWritten().getAsString();
+        break;
+      }
+      case Stmt::CXXReinterpretCastExprClass: {
+        const auto *CXXRCE = cast<CXXReinterpretCastExpr>(E);
+        exprType = CXXRCE->getTypeAsWritten().getAsString();
+        break;
+      }
+      case Stmt::CXXThisExprClass: {
+        exprType = "this";
+        break;
+      }
+      default: {
+      }
+      }
+      S.Diag(Loc, diag::note_typecheck_expression_not_modifiable_lvalue)
+          << E->getSourceRange() << Assign
+          << FixItHint::CreateInsertion(E->getBeginLoc(),
+                                        "*(" + exprType + ")");
+    }
----------------
Sirraide wrote:

Er, maybe I’m missing something, but what is all of this for exactly? I think just suggesting inserting `*` (and, yeah, instead `*(` ... `)` if this is the argument to postfix `++` or `--`; I was thinking of maybe handling postfix operators in a different pr, but if you want to include them in this pr, then that’s also fine) should be fine because operator precedence should work out to where that just does the right thing. 

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


More information about the cfe-commits mailing list