diagnostics: fix let x: vec![] suggestion pointing into stdlib#158934
diagnostics: fix let x: vec![] suggestion pointing into stdlib#158934Rohan-Singla wants to merge 1 commit into
let x: vec![] suggestion pointing into stdlib#158934Conversation
|
HIR ty lowering was modified cc @fmease |
|
r? @jackh726 rustbot has assigned @jackh726. Use Why was this reviewer chosen?The reviewer was selected based on:
|
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
let x: vec![] suggestion pointing into stdlib
|
This PR was rebased onto a different main commit. Here's a range-diff highlighting what actually changed. Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers. |
This comment has been minimized.
This comment has been minimized.
|
Hi, can you please take a look at this review #158509 (review). |
Thanks for the feedback! Switched from source_callsite() to find_ancestor_in_same_ctxt the old approach jumped too far back in the expansion chain. Added a helper eq_ctxt_suggestion_span that tries to find ancestors of pat and ty in each other's syntax context, only emitting the suggestion when both spans can be reconciled in the same context. Also added a test for the macro case which was pointed out it now correctly emits no suggestion instead of make!( = ). |
When a macro call like `vec![]` appears in type position, the compiler's "use `=` if you meant to assign" suggestion was pointing into the macro definition in stdlib instead of the user's own code. Use `hir_ty.span.source_callsite()` to get the original macro call site in user code when computing the suggestion span.
Fixes #158492
When a macro call like vec![] appears in type position (let x: vec![];), the compiler correctly detects the likely typo (: instead of =) but emitted a broken suggestion pointing into the standard library (library/alloc/src/macros.rs:44) instead of the user's own code.
Root cause: After macro expansion, vec![] becomes Vec::new(). The HIR type node's span points to the expanded code inside the macro definition (in stdlib), not the original vec![] call site. The suggestion span was computed as stmt.pat.span.between(hir_ty.span) a cross-file span from user code into stdlib which caused the suggestion renderer to display the stdlib location.
Fix: Use hir_ty.span.source_callsite() instead of hir_ty.span when computing the suggestion span. This walks up the macro expansion chain to the original call site in user code, keeping the suggestion span within the user's file.
Before:
help: use
=if you meant to assign--> library/alloc/src/macros.rs:44:9
|
44 - $crate::vec::Vec::new()
44 + =
After:
help: use
=if you meant to assign|
LL - let x: vec![];
LL + let x = vec![];
A test case was added to tests/ui/suggestions/let-binding-init-expr-as-ty.rs, which already covers the related let x: Vec::new() and let x: S::new(()) cases.