Skip to content

Conversation

@Delta17920
Copy link
Contributor

@Delta17920 Delta17920 commented Dec 13, 2025

implemented a new diagnostic in rustc_resolve to detect invalid range destructuring attempts (e.g., let start..end = range). The fix identifies when resolution fails for identifiers acting as range bounds specifically handling cases where bounds are parsed as expressions and suggests the correct struct pattern syntax (std::ops::Range { start, end }). This replaces confusing "cannot find value" errors with actionable help, verified by a new UI test covering various identifier names.

Fixes #149777

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Dec 13, 2025
@rustbot
Copy link
Collaborator

rustbot commented Dec 13, 2025

r? @lcnr

rustbot has assigned @lcnr.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

@Delta17920
Copy link
Contributor Author

r? @Alexendoo

@rustbot rustbot assigned Alexendoo and unassigned lcnr Dec 13, 2025
@Alexendoo
Copy link
Member

I'm not part of the compiler team so I'll pass it back over to r? @lcnr

@rustbot rustbot assigned lcnr and unassigned Alexendoo Dec 13, 2025
err.span_suggestion_verbose(
pat.span,
"if you meant to destructure a `Range`, use the struct pattern",
format!("std::ops::Range {{ start: {}, end: {} }}", start_name, end_name),
Copy link
Contributor

@PatchMixolydic PatchMixolydic Dec 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It'd be helpful if this suggested std::range::Range/core::range::Range when #![feature(new_range)] is enabled (might not be necessary since new_range is still unstable).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regarding new_range: I'm sticking with std::ops::Range for now since it's the stable default, but we can revisit that once the feature stabilizes.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please add a // FIXME(new_range): Also account for new range types?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

err.span_suggestion_verbose(
pat.span,
"if you meant to destructure a `Range`, use a struct pattern",
format!("std::ops::Range {{ start: {}, end: {} }}", start_name, end_name),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of unconditionally suggesting a qualified path, IINM you should be able to take advantage of path trimming (that's a machinery that shortens paths according to what's in scope / imported).

Suggested change
format!("std::ops::Range {{ start: {}, end: {} }}", start_name, end_name),
format!("{path} {{ start: {}, end: {} }}", start_name, end_name),

where path is tcx.def_path_str(range_struct) where range_struct comes from tcx.lang_items().range_struct() (for RangeEnd::Excluded; it should he range_inclusive_struct() for RangeEnd::Included(RangeSyntax::DotDotEq)) if it's Some(_) (bail out if it's None).

I hope this works in rustc_resolve 🤞. If these queries hang, dead-lock or crash, then they obv can't be used in the resolver since the info isn't available yet. If it comes to that, there might be alternative Resolver APIs you could use, not sure. Check what other resolver code is doing about lang items.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried implementing path trimming using tcx.lang_items() and def_path_str as suggested, but it caused a cycle detected [E0391] error exactly as you warned (since resolution info isn't ready yet).

Instead, I implemented a safe manual check using self.resolve_path. It checks if the short name (e.g., Range) is visible in the current scope. If it is, I use it; otherwise, I fall back to the fully qualified path (std::ops::Range). Tests confirm this works correctly!

}

if let Some(pat) = self.diag_metadata.current_pat
&& let ast::PatKind::Range(Some(start_expr), Some(end_expr), _) = &pat.kind
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As alluded to in another review comment of mine, you can't ignore the RangeEnd of the PatKind::Range, it's crucial for suggesting the right struct!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I'm now matching on end_kind.node to distinguish between RangeEnd::Excluded (suggesting Range) and RangeEnd::Included (suggesting RangeInclusive)

}

if let Some(pat) = self.diag_metadata.current_pat
&& let ast::PatKind::Range(Some(start_expr), Some(end_expr), _) = &pat.kind
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be very nice to also handle the open ranges, RangeTo (..b) and RangeFrom (a..) & suggest the appropriate structs.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


err.span_suggestion_verbose(
pat.span,
"if you meant to destructure a `Range`, use a struct pattern",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"if you meant to destructure a `Range`, use a struct pattern",
"if you meant to destructure a range, use a struct pattern",

or

Suggested change
"if you meant to destructure a `Range`, use a struct pattern",
"if you meant to destructure a `{name}`, use a struct pattern",

where name is tcx.item_name(range_struct) (see other comments about accounting for RangeInclusive & open ranges). The query item_name might not work in rustc_resolve (it might hang or crash since the data isn't available) but then there should be alternative Resolver APIs for obtaining that.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

used range

Comment on lines 1400 to 1401
&& let (ast::ExprKind::Path(None, start_path), ast::ExprKind::Path(None, end_path)) =
(&start_expr.kind, &end_expr.kind)
Copy link
Member

@fmease fmease Dec 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that you're disqualifying cases like if let 1..x = my_range {}. Personally speaking I'm not sure if we want to disqualify this or not 🤔. Note that you're including cases like if let path::to::CONST..x = my_range {} OTOH, so it's a bit inconsistent at the moment.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I addressed this by switching to span_to_snippet, so the logic now treats literals 1..x and variables exactly the same way.

However, I cannot verify this with a UI test case because writing let 1..x = my_range triggers a hard Type Mismatch error (E0308) the compiler complains that a literal pattern 1 doesn't match the Range struct type which masks the resolution error/suggestion. But the logic to handle it is definitely in place now.

Comment on lines 1409 to 1410
let start_name = start_path.segments[0].ident;
let end_name = end_path.segments[0].ident;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is incorrect since you're using an || above. Meaning it's possible that either start_path or end_path has more than one segment but you're still merely retrieving the first segment.

Concretely, it means that you're suggesting std::ops::Range { start: path, end: y } given path::to::x..y (printing path instead of path::to::x).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I completely removed the segments[0] logic. I replaced it with span_to_snippet

err.span_suggestion_verbose(
pat.span,
"if you meant to destructure a `Range`, use a struct pattern",
format!("std::ops::Range {{ start: {}, end: {} }}", start_name, end_name),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(low priority) in the special case of start..y or x..end (etc.) it would be nice to suggest std::ops::Range { start, end: y } and std::ops::Range { start: x, end } respectively (i.e., leveraging field shorthands).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment on lines 1402 to 1407
&& path.len() == 1
{
let ident = path[0].ident;

if (start_path.segments.len() == 1 && start_path.segments[0].ident == ident)
|| (end_path.segments.len() == 1 && end_path.segments[0].ident == ident)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use slice pattern [x] to express xs.len() == 1 && let x = xs[0] in one go. It's more robust, too.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Dec 14, 2025
@rustbot
Copy link
Collaborator

rustbot commented Dec 14, 2025

Reminder, once the PR becomes ready for a review, use @rustbot ready.

@fmease fmease assigned fmease and unassigned lcnr Dec 14, 2025
@Delta17920 Delta17920 force-pushed the fix/149777-range-destructuring branch from 37fa028 to e3f2dc4 Compare December 14, 2025 15:09
@rustbot

This comment has been minimized.

@Delta17920
Copy link
Contributor Author

@rustbot ready

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Dec 14, 2025
@Delta17920 Delta17920 requested a review from fmease December 14, 2025 17:00
@Delta17920
Copy link
Contributor Author

@fmease anything else that needs to be changed?

@fmease
Copy link
Member

fmease commented Dec 16, 2025

I'll approve in a sec ;)

Copy link
Member

@fmease fmease left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, some super tiny nits then I'll approve! Nice idea to use resolve_path for the ad hoc "path trimming" :)

View changes since this review

path: &[Segment],
source: PathSource<'_, '_, '_>,
) {
if !matches!(source, PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When do we care about PathSource::Expr? Can't be destructuring assignments. I'm probably missing something obvious.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tested removing PathSource::Expr, but it broke few tests. It turns out range bounds inside patterns (like the _y in [_y..]) are resolved as expressions, so we need this check to ensure the suggestion appears for those cases.

Comment on lines 1419 to 1420
let mut resolve_short_name = |short: &str, full: &str| -> String {
let ident = Ident::from_str(short);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let mut resolve_short_name = |short: &str, full: &str| -> String {
let ident = Ident::from_str(short);
let mut resolve_short_name = |short: Symbol, full: &str| -> String {
let ident = Ident::with_dummy_span(short);

(minor) Slightly "cleaner" since avoids needless interning & shields from typos.
Together with…

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment on lines 1431 to 1446
resolve_short_name("Range", "std::ops::Range"),
vec![field("start", start), field("end", end)],
),
(Some(start), Some(end), ast::RangeEnd::Included(_)) => (
resolve_short_name("RangeInclusive", "std::ops::RangeInclusive"),
vec![field("start", start), field("end", end)],
),
(Some(start), None, _) => (
resolve_short_name("RangeFrom", "std::ops::RangeFrom"),
vec![field("start", start)],
),
(None, Some(end), ast::RangeEnd::Excluded) => {
(resolve_short_name("RangeTo", "std::ops::RangeTo"), vec![field("end", end)])
}
(None, Some(end), ast::RangeEnd::Included(_)) => (
resolve_short_name("RangeToInclusive", "std::ops::RangeToInclusive"),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

… the following change.

Suggested change
resolve_short_name("Range", "std::ops::Range"),
vec![field("start", start), field("end", end)],
),
(Some(start), Some(end), ast::RangeEnd::Included(_)) => (
resolve_short_name("RangeInclusive", "std::ops::RangeInclusive"),
vec![field("start", start), field("end", end)],
),
(Some(start), None, _) => (
resolve_short_name("RangeFrom", "std::ops::RangeFrom"),
vec![field("start", start)],
),
(None, Some(end), ast::RangeEnd::Excluded) => {
(resolve_short_name("RangeTo", "std::ops::RangeTo"), vec![field("end", end)])
}
(None, Some(end), ast::RangeEnd::Included(_)) => (
resolve_short_name("RangeToInclusive", "std::ops::RangeToInclusive"),
resolve_short_name(sym::Range, "std::ops::Range"),
vec![field("start", start), field("end", end)],
),
(Some(start), Some(end), ast::RangeEnd::Included(_)) => (
resolve_short_name(sym::RangeInclusive, "std::ops::RangeInclusive"),
vec![field("start", start), field("end", end)],
),
(Some(start), None, _) => (
resolve_short_name(sym::RangeFrom, "std::ops::RangeFrom"),
vec![field("start", start)],
),
(None, Some(end), ast::RangeEnd::Excluded) => {
(resolve_short_name(sym::RangeTo, "std::ops::RangeTo"), vec![field("end", end)])
}
(None, Some(end), ast::RangeEnd::Included(_)) => (
resolve_short_name(sym::RangeToInclusive, "std::ops::RangeToInclusive"),

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

let path = Segment::from_path(&Path::from_ident(ident));

match self.resolve_path(&path, Some(TypeNS), None, PathSource::Type) {
PathResult::Module(..) | PathResult::NonModule(..) => short.to_string(),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
PathResult::Module(..) | PathResult::NonModule(..) => short.to_string(),
PathResult::NonModule(..) => short.to_string(),

Don't we want to exclude modules? If Range were to resolve to a module, we shouldn't use it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch! updated

Comment on lines 1403 to 1406
let start_snippet =
start.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
let end_snippet =
end.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you move these span_to_snippet calls below the if !in_start && !in_end { return } to reduce the amount of throwaway work.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

// FIXME(new_range): Also account for new range types
let (struct_path, fields) = match (start_snippet, end_snippet, &end_kind.node) {
(Some(start), Some(end), ast::RangeEnd::Excluded) => (
resolve_short_name("Range", "std::ops::Range"),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(ignore) Suggesting std:: isn't correct in #![no_std] crates but it's not worth addressing. We probably have a bunch of diagnostics that don't account for that.

vec![field("start", start), field("end", end)],
),
(Some(start), Some(end), ast::RangeEnd::Included(_)) => (
resolve_short_name("RangeInclusive", "std::ops::RangeInclusive"),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could get rid of the whole closure resolve_short_name if you just return these two things as is,

Suggested change
resolve_short_name("RangeInclusive", "std::ops::RangeInclusive"),
"RangeInclusive", "std::ops::RangeInclusive",

since you're then able to look up the name inline below the match. Ultimately, it doesn't matter though and the closure approach could be more legible 🤷

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I decided to keep the closure approach

@fmease fmease added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Dec 16, 2025
@Delta17920 Delta17920 force-pushed the fix/149777-range-destructuring branch from e3f2dc4 to 54ee7a3 Compare December 17, 2025 14:19
@rustbot
Copy link
Collaborator

rustbot commented Dec 17, 2025

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.

@Delta17920 Delta17920 force-pushed the fix/149777-range-destructuring branch from 54ee7a3 to 6fac0fa Compare December 17, 2025 14:53
@fmease
Copy link
Member

fmease commented Dec 18, 2025

Thanks! @bors r+ rollup

@bors
Copy link
Collaborator

bors commented Dec 18, 2025

📌 Commit 6fac0fa has been approved by fmease

It is now in the queue for this repository.

@bors
Copy link
Collaborator

bors commented Dec 18, 2025

🌲 The tree is currently closed for pull requests below priority 1000. This pull request will be tested once the tree is reopened.

@bors bors added S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Dec 18, 2025
bors added a commit that referenced this pull request Dec 18, 2025
…uwer

Rollup of 12 pull requests

Successful merges:

 - #145933 (Expand `str_as_str` to more types)
 - #148849 (Set -Cpanic=abort in windows-msvc stack protector tests)
 - #149925 (`cfg_select!`: parse unused branches)
 - #149952 (Suggest struct pattern when destructuring Range with .. syntax)
 - #150022 (Generate macro expansion for rust compiler crates docs)
 - #150024 (Support recursive delegation)
 - #150048 (std_detect: AArch64 Darwin: expose SME F16F16 and B16B16 features)
 - #150083 (tests/run-make-cargo/same-crate-name-and-macro-name: New regression test)
 - #150102 (Fixed ICE for EII with multiple defaults due to duplicate definition in nameres)
 - #150124 (unstable.rs: fix typos in comments (implementatble -> implementable))
 - #150125 (Port `#[rustc_lint_opt_deny_field_access]` to attribute parser)
 - #150126 (Subtree sync for rustc_codegen_cranelift)

Failed merges:

 - #150127 (Port `#[rustc_lint_untracked_query_information]` and `#[rustc_lint_diagnostics]` to using attribute parsers)

r? `@ghost`
`@rustbot` modify labels: rollup
@bors bors merged commit b17df9b into rust-lang:main Dec 18, 2025
11 checks passed
@rustbot rustbot added this to the 1.94.0 milestone Dec 18, 2025
rust-timer added a commit that referenced this pull request Dec 18, 2025
Rollup merge of #149952 - Delta17920:fix/149777-range-destructuring, r=fmease

Suggest struct pattern when destructuring Range with .. syntax

implemented a new diagnostic in rustc_resolve to detect invalid range destructuring attempts (e.g., let start..end = range). The fix identifies when resolution fails for identifiers acting as range bounds specifically handling cases where bounds are parsed as expressions and suggests the correct struct pattern syntax (std::ops::Range { start, end }). This replaces confusing "cannot find value" errors with actionable help, verified by a new UI test covering various identifier names.

Fixes #149777
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Suggest struct destructuring when attempting to destructure using range syntax

8 participants