Skip to content

Commit e65c060

Browse files
committed
Detect Python-like slicing and suggest how to fix
Fix #108215
1 parent b29a1e0 commit e65c060

File tree

4 files changed

+47
-0
lines changed

4 files changed

+47
-0
lines changed

Diff for: compiler/rustc_ast/src/token.rs

+5
Original file line numberDiff line numberDiff line change
@@ -756,6 +756,11 @@ impl Token {
756756
)
757757
}
758758

759+
/// Returns `true` if the token is the integer literal.
760+
pub fn is_integer_lit(&self) -> bool {
761+
matches!(self.kind, Literal(Lit { kind: LitKind::Integer, .. }))
762+
}
763+
759764
/// Returns `true` if the token is a non-raw identifier for which `pred` holds.
760765
pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool {
761766
match self.ident() {

Diff for: compiler/rustc_parse/src/parser/stmt.rs

+16
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,22 @@ impl<'a> Parser<'a> {
567567
snapshot.recover_diff_marker();
568568
}
569569
if self.token == token::Colon {
570+
// if a previous and next token of the current one is
571+
// integer literal (e.g. `1:42`), it's likely a range
572+
// expression for Pythonistas and we can suggest so.
573+
if self.prev_token.is_integer_lit()
574+
&& self.look_ahead(1, |token| token.is_integer_lit())
575+
{
576+
// TODO(hkmatsumoto): Might be better to trigger
577+
// this only when parsing an index expression.
578+
err.span_suggestion_verbose(
579+
self.token.span,
580+
"you might have meant to make a slice with range index",
581+
"..",
582+
Applicability::MaybeIncorrect,
583+
);
584+
}
585+
570586
// if next token is following a colon, it's likely a path
571587
// and we can suggest a path separator
572588
self.bump();

Diff for: tests/ui/suggestions/range-index-instead-of-colon.rs

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// edition:2021
2+
3+
fn main() {
4+
&[1, 2, 3][1:2];
5+
//~^ ERROR: expected one of
6+
//~| HELP: you might have meant to make a slice with range index
7+
//~| HELP: maybe write a path separator here
8+
}
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
error: expected one of `.`, `?`, `]`, or an operator, found `:`
2+
--> $DIR/range-index-instead-of-colon.rs:4:17
3+
|
4+
LL | &[1, 2, 3][1:2];
5+
| ^ expected one of `.`, `?`, `]`, or an operator
6+
|
7+
= note: type ascription syntax has been removed, see issue #101728 <https://github.com/rust-lang/rust/issues/101728>
8+
help: you might have meant to make a slice with range index
9+
|
10+
LL | &[1, 2, 3][1..2];
11+
| ~~
12+
help: maybe write a path separator here
13+
|
14+
LL | &[1, 2, 3][1::2];
15+
| ~~
16+
17+
error: aborting due to previous error
18+

0 commit comments

Comments
 (0)