[clang] [clang][Sema] Simplify err_init_conversion_failed diagnostic message for const variables (PR #82109)

Aaron Ballman via cfe-commits cfe-commits at lists.llvm.org
Thu Jan 16 10:11:55 PST 2025


================
@@ -9804,12 +9804,22 @@ bool InitializationSequence::Diagnose(Sema &S,
 
   case FK_ConversionFailed: {
     QualType FromType = OnlyArg->getType();
-    PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
-      << (int)Entity.getKind()
-      << DestType
-      << OnlyArg->isLValue()
-      << FromType
-      << Args[0]->getSourceRange();
+
+    // NOTE: need to be in sync with err_init_conversion_failed
+    const auto TotalSpecialKinds = 1;
+
+    PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed);
+    if (Entity.getKind() == InitializedEntity::EK_Variable &&
+        DestType.isConstQualified()) {
+      QualType NonConstDestType = DestType;
+      NonConstDestType.removeLocalConst();
+      PDiag << 0 /* a constant */
+            << NonConstDestType;
+    } else {
+      PDiag << (TotalSpecialKinds + (int)Entity.getKind()) << DestType;
+    }
+    PDiag << OnlyArg->isLValue() << FromType << Args[0]->getSourceRange();
----------------
AaronBallman wrote:

How about something along these lines (with comments)?
```
PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed);
{
  llvm::SaveAndRestore _(DestType);
  unsigned EKind = (unsigned)Entity.getKind() + 1;
  if (Entity.getKind() == InitializedEntity::EK_Variable &&
        DestType.isConstQualified()) {
    EKind = 0;
    DestType.removeLocalConst();
  }

  PDiag << EKind << DestType << ...;
}
S.HandleFunctionTypeMismatch(PDiag, ...);
```

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


More information about the cfe-commits mailing list