Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions compiler/rustc_resolve/src/late/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,7 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {

self.detect_missing_binding_available_from_pattern(&mut err, path, following_seg);
self.suggest_at_operator_in_slice_pat_with_range(&mut err, path);
self.suggest_range_struct_destructuring(&mut err, path, source);
self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);

if let Some((span, label)) = base_error.span_label {
Expand Down Expand Up @@ -1383,6 +1384,41 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
}
}

fn suggest_range_struct_destructuring(
&self,
err: &mut Diag<'_>,
path: &[Segment],
source: PathSource<'_, '_, '_>,
) {
// We accept Expr here because range bounds (start..end) are parsed as expressions
if !matches!(source, PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..)) {
return;
}

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
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.

&& let (ast::ExprKind::Path(None, start_path), ast::ExprKind::Path(None, end_path)) =
(&start_expr.kind, &end_expr.kind)
Comment on lines +1400 to +1401
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.

&& 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)
Comment on lines +1402 to +1407
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.

{
let start_name = start_path.segments[0].ident;
let end_name = end_path.segments[0].ident;
Comment on lines +1409 to +1410
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).


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.

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
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
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).

Applicability::MaybeIncorrect,
);
}
}
}

fn suggest_swapping_misplaced_self_ty_and_trait(
&mut self,
err: &mut Diag<'_>,
Expand Down
15 changes: 15 additions & 0 deletions tests/ui/resolve/suggest-range-struct-destructuring.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
use std::ops::Range;

fn test_basic_range(r: Range<u32>) {
let start..end = r;
//~^ ERROR cannot find value `start` in this scope
//~| ERROR cannot find value `end` in this scope
}

fn test_different_names(r: Range<u32>) {
let min..max = r;
//~^ ERROR cannot find value `min` in this scope
//~| ERROR cannot find value `max` in this scope
}

fn main() {}
66 changes: 66 additions & 0 deletions tests/ui/resolve/suggest-range-struct-destructuring.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
error[E0425]: cannot find value `start` in this scope
--> $DIR/suggest-range-struct-destructuring.rs:4:9
|
LL | let start..end = r;
| ^^^^^ not found in this scope
|
help: if you meant to destructure a `Range`, use a struct pattern
|
LL - let start..end = r;
LL + let std::ops::Range { start: start, end: end } = r;
|

error[E0425]: cannot find value `end` in this scope
--> $DIR/suggest-range-struct-destructuring.rs:4:16
|
LL | let start..end = r;
| ^^^ not found in this scope
|
help: if you meant to destructure a `Range`, use a struct pattern
|
LL - let start..end = r;
LL + let std::ops::Range { start: start, end: end } = r;
|

error[E0425]: cannot find value `min` in this scope
--> $DIR/suggest-range-struct-destructuring.rs:10:9
|
LL | let min..max = r;
| ^^^
...
LL | fn main() {}
| --------- similarly named function `main` defined here
|
help: if you meant to destructure a `Range`, use a struct pattern
|
LL - let min..max = r;
LL + let std::ops::Range { start: min, end: max } = r;
|
help: a function with a similar name exists
|
LL | let main..max = r;
| +
help: consider importing this function
|
LL + use std::cmp::min;
|

error[E0425]: cannot find value `max` in this scope
--> $DIR/suggest-range-struct-destructuring.rs:10:14
|
LL | let min..max = r;
| ^^^ not found in this scope
|
help: if you meant to destructure a `Range`, use a struct pattern
|
LL - let min..max = r;
LL + let std::ops::Range { start: min, end: max } = r;
|
help: consider importing this function
|
LL + use std::cmp::max;
|

error: aborting due to 4 previous errors

For more information about this error, try `rustc --explain E0425`.
Loading