Skip to content

Commit 93ecfab

Browse files
committed
Detect Python-like slicing and suggest how to fix
Fix #108215
1 parent 76e79ca commit 93ecfab

File tree

4 files changed

+47
-0
lines changed

4 files changed

+47
-0
lines changed

compiler/rustc_ast/src/token.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -709,6 +709,11 @@ impl Token {
709709
)
710710
}
711711

712+
/// Returns `true` if the token is the integer literal.
713+
pub fn is_integer_lit(&self) -> bool {
714+
matches!(self.kind, Literal(Lit { kind: LitKind::Integer, .. }))
715+
}
716+
712717
/// Returns `true` if the token is a non-raw identifier for which `pred` holds.
713718
pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool {
714719
match self.ident() {

compiler/rustc_parse/src/parser/stmt.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -563,6 +563,22 @@ impl<'a> Parser<'a> {
563563
snapshot.recover_diff_marker();
564564
}
565565
if self.token == token::Colon {
566+
// if a previous and next token of the current one is
567+
// integer literal (e.g. `1:42`), it's likely a range
568+
// expression for Pythonistas and we can suggest so.
569+
if self.prev_token.is_integer_lit()
570+
&& self.look_ahead(1, |token| token.is_integer_lit())
571+
{
572+
// TODO(hkmatsumoto): Might be better to trigger
573+
// this only when parsing an index expression.
574+
err.span_suggestion_verbose(
575+
self.token.span,
576+
"you might have meant to make a slice with range index",
577+
"..",
578+
Applicability::MaybeIncorrect,
579+
);
580+
}
581+
566582
// if next token is following a colon, it's likely a path
567583
// and we can suggest a path separator
568584
self.bump();
Lines changed: 8 additions & 0 deletions
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+
}
Lines changed: 18 additions & 0 deletions
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)