Author: Haojian Wu Date: 2025-12-31T14:52:10+01:00 New Revision: 5c2a8117ac12c455d69df61dd6a2f5f3fa07f964
URL: https://github.com/llvm/llvm-project/commit/5c2a8117ac12c455d69df61dd6a2f5f3fa07f964 DIFF: https://github.com/llvm/llvm-project/commit/5c2a8117ac12c455d69df61dd6a2f5f3fa07f964.diff LOG: [clang] Preserve the initializer when variable declaration deduction fails (#173546) Fix https://github.com/clangd/clangd/issues/2572. Added: Modified: clang/docs/ReleaseNotes.rst clang/lib/Sema/SemaDecl.cpp clang/test/AST/ast-dump-recovery.cpp Removed: ################################################################################ diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 2319ff13f7864..ecdbbc05cdef4 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -875,6 +875,7 @@ Improvements including diagnosing when the array-section's base is not a named-variable. - Handling of ``use_device_addr`` and ``use_device_ptr`` in the presence of other maps with the same base-pointer/variable, was improved. +- Preserve the initializer when variable declaration dedution fails for better error recovery. Additional Information ====================== diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index 11323803e1910..f636e8e35a3d5 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -13840,8 +13840,15 @@ void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { return; } - if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) + if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) { + assert(VDecl->isInvalidDecl() && + "decl should be invalidated when deduce fails"); + if (auto *RecoveryExpr = + CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init}) + .get()) + VDecl->setInit(RecoveryExpr); return; + } } this->CheckAttributesOnDeducedType(RealDecl); diff --git a/clang/test/AST/ast-dump-recovery.cpp b/clang/test/AST/ast-dump-recovery.cpp index 060ae3b62b6f8..80ec0a449d556 100644 --- a/clang/test/AST/ast-dump-recovery.cpp +++ b/clang/test/AST/ast-dump-recovery.cpp @@ -301,3 +301,11 @@ void foo() { U g{}; } } // namespace GH112560 + +// CHECK: VarDecl {{.*}} invalid x 'auto *' cinit +// CHECK-NEXT: `-RecoveryExpr {{.*}} '<dependent type>' contains-errors lvalue +// CHECK-NEXT: `-CallExpr {{.*}} 'int' +// DISABLED-NOT: -RecoveryExpr {{.*}} contains-errors +void brokenDeducedVarDecl() { + auto* x = some_func(nullptr); +} _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
