-
-
Notifications
You must be signed in to change notification settings - Fork 14.2k
Suggest struct pattern when destructuring Range with .. syntax #149952
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Suggest struct pattern when destructuring Range with .. syntax #149952
Conversation
|
r? @Alexendoo |
|
I'm not part of the compiler team so I'll pass it back over to r? @lcnr |
| 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), |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
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).
| 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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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", |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| "if you meant to destructure a `Range`, use a struct pattern", | |
| "if you meant to destructure a range, use a struct pattern", |
or
| "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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
used range
| && let (ast::ExprKind::Path(None, start_path), ast::ExprKind::Path(None, end_path)) = | ||
| (&start_expr.kind, &end_expr.kind) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| let start_name = start_path.segments[0].ident; | ||
| let end_name = end_path.segments[0].ident; |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
done
| && 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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
done
|
Reminder, once the PR becomes ready for a review, use |
37fa028 to
e3f2dc4
Compare
This comment has been minimized.
This comment has been minimized.
|
@rustbot ready |
|
@fmease anything else that needs to be changed? |
|
I'll approve in a sec ;) |
There was a problem hiding this 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" :)
| path: &[Segment], | ||
| source: PathSource<'_, '_, '_>, | ||
| ) { | ||
| if !matches!(source, PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..)) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| let mut resolve_short_name = |short: &str, full: &str| -> String { | ||
| let ident = Ident::from_str(short); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| 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…
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
done
| 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"), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
… the following 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"), |
There was a problem hiding this comment.
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(), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| 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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good catch! updated
| 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()); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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"), |
There was a problem hiding this comment.
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"), |
There was a problem hiding this comment.
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,
| 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 🤷
There was a problem hiding this comment.
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
e3f2dc4 to
54ee7a3
Compare
|
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. |
54ee7a3 to
6fac0fa
Compare
|
Thanks! @bors r+ rollup |
|
🌲 The tree is currently closed for pull requests below priority 1000. This pull request will be tested once the tree is reopened. |
…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
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
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