Files
rust/tests
Jacob Pratt 813d288d88 Rollup merge of #158934 - Rohan-Singla:fix/158492, r=jackh726
diagnostics: fix `let x: vec![]` suggestion pointing into stdlib

# Fixes rust-lang/rust#158492

When a macro call like `vec![]` appears in type position (`let x: vec![];`), the compiler correctly detects the likely typo (`:` instead of `=`), but emits 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 therefore points to the expanded code inside the macro definition rather than the original `vec![]` call site.

The suggestion span was computed as:

`stmt.pat.span.between(hir_ty.span)`

This creates a span crossing from the user's code into the standard library, causing the suggestion renderer to display the standard library location.

## Fix

Compute the span using `find_ancestor_in_same_ctxt` so that the pattern and type are resolved into a common syntax context before calling `between`.

For `let x: vec![];`, this walks the type's span up the expansion chain until it reaches the user's file, keeping the suggestion within a single file.

This also handles the reverse case, which `source_callsite` alone does not: when the `let` itself comes from a macro body while the pattern is a call-site metavariable, there is no common context. In that case, no suggestion is emitted rather than producing a nonsensical one.

## Before

```text
help: use `=` if you meant to assign
  --> library/alloc/src/macros.rs:44:9
   |
44 -         $crate::vec::Vec::new()
44 +          =
```

## After

```text
help: use `=` if you meant to assign
   |
LL -     let x: vec![];
LL +     let x = vec![];
```

## Tests

Two test cases were 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:

1. The `vec![]` case described above.
2. A `let` inside a `macro_rules!` body where no suggestion should be emitted.

## Note on file layout

The new `eq_ctxt_suggestion_span` helper lives in `hir_ty_lowering/errors.rs` rather than next to its callers in `mod.rs`.

`mod.rs` was already within a few lines of tidy's 3000-line limit, so keeping the helper there caused the style check to fail.

This is pure code motion with no behavior change.
2026-08-20 21:34:21 -04:00
..
2026-08-17 00:38:40 -05:00