Skip to content

Commit 08e21c0

Browse files
Rollup merge of rust-lang#119397 - ShE3py:pat-range-paren-recovery, r=fmease
Recover parentheses in range patterns Before: ```rs match n { (0).. => (), _ => () } ``` ``` error: expected one of `=>`, `if`, or `|`, found `..` --> src/lib.rs:3:12 | 3 | (0).. => (), | ^^ expected one of `=>`, `if`, or `|` ``` After: ``` error: range pattern bounds cannot have parentheses --> main.rs:3:5 | 3 | (0).. => (), | ^ ^ | help: remove these parentheses | 3 - (0).. => (), 3 + 0.. => (), | ``` This sets the groundwork for rust-lang#118625, which will extend the recovery to expressions like `(0 + 1)..` where users may tend to add parentheses to avoid dealing with precedence. --- ``@rustbot`` label +A-parser +A-patterns +A-diagnostics
2 parents e42e16d + 4e0badd commit 08e21c0

File tree

7 files changed

+151
-18
lines changed

7 files changed

+151
-18
lines changed

compiler/rustc_parse/messages.ftl

+3
Original file line numberDiff line numberDiff line change
@@ -767,6 +767,9 @@ parse_unexpected_if_with_if = unexpected `if` in the condition expression
767767
parse_unexpected_lifetime_in_pattern = unexpected lifetime `{$symbol}` in pattern
768768
.suggestion = remove the lifetime
769769
770+
parse_unexpected_paren_in_range_pat = range pattern bounds cannot have parentheses
771+
parse_unexpected_paren_in_range_pat_sugg = remove these parentheses
772+
770773
parse_unexpected_parentheses_in_for_head = unexpected parentheses surrounding `for` loop head
771774
.suggestion = remove parentheses in `for` loop
772775

compiler/rustc_parse/src/errors.rs

+21
Original file line numberDiff line numberDiff line change
@@ -2378,6 +2378,27 @@ pub(crate) struct ExpectedCommaAfterPatternField {
23782378
pub span: Span,
23792379
}
23802380

2381+
#[derive(Diagnostic)]
2382+
#[diag(parse_unexpected_paren_in_range_pat)]
2383+
pub(crate) struct UnexpectedParenInRangePat {
2384+
#[primary_span]
2385+
pub span: Vec<Span>,
2386+
#[subdiagnostic]
2387+
pub sugg: UnexpectedParenInRangePatSugg,
2388+
}
2389+
2390+
#[derive(Subdiagnostic)]
2391+
#[multipart_suggestion(
2392+
parse_unexpected_paren_in_range_pat_sugg,
2393+
applicability = "machine-applicable"
2394+
)]
2395+
pub(crate) struct UnexpectedParenInRangePatSugg {
2396+
#[suggestion_part(code = "")]
2397+
pub start_span: Span,
2398+
#[suggestion_part(code = "")]
2399+
pub end_span: Span,
2400+
}
2401+
23812402
#[derive(Diagnostic)]
23822403
#[diag(parse_return_types_use_thin_arrow)]
23832404
pub(crate) struct ReturnTypesUseThinArrow {

compiler/rustc_parse/src/parser/pat.rs

+53-3
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ use crate::errors::{
66
InclusiveRangeExtraEquals, InclusiveRangeMatchArrow, InclusiveRangeNoEnd, InvalidMutInPattern,
77
PatternOnWrongSideOfAt, RefMutOrderIncorrect, RemoveLet, RepeatedMutInPattern,
88
SwitchRefBoxOrder, TopLevelOrPatternNotAllowed, TopLevelOrPatternNotAllowedSugg,
9-
TrailingVertNotAllowed, UnexpectedLifetimeInPattern, UnexpectedVertVertBeforeFunctionParam,
9+
TrailingVertNotAllowed, UnexpectedLifetimeInPattern, UnexpectedParenInRangePat,
10+
UnexpectedParenInRangePatSugg, UnexpectedVertVertBeforeFunctionParam,
1011
UnexpectedVertVertInPattern,
1112
};
1213
use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
@@ -579,6 +580,8 @@ impl<'a> Parser<'a> {
579580

580581
/// Parse a tuple or parenthesis pattern.
581582
fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
583+
let open_paren = self.token.span;
584+
582585
let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| {
583586
p.parse_pat_allow_top_alt(
584587
None,
@@ -591,7 +594,29 @@ impl<'a> Parser<'a> {
591594
// Here, `(pat,)` is a tuple pattern.
592595
// For backward compatibility, `(..)` is a tuple pattern as well.
593596
Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
594-
PatKind::Paren(fields.into_iter().next().unwrap())
597+
let pat = fields.into_iter().next().unwrap();
598+
let close_paren = self.prev_token.span;
599+
600+
match &pat.kind {
601+
// recover ranges with parentheses around the `(start)..`
602+
PatKind::Lit(begin)
603+
if self.may_recover()
604+
&& let Some(form) = self.parse_range_end() =>
605+
{
606+
self.dcx().emit_err(UnexpectedParenInRangePat {
607+
span: vec![open_paren, close_paren],
608+
sugg: UnexpectedParenInRangePatSugg {
609+
start_span: open_paren,
610+
end_span: close_paren,
611+
},
612+
});
613+
614+
self.parse_pat_range_begin_with(begin.clone(), form)?
615+
}
616+
617+
// (pat) with optional parentheses
618+
_ => PatKind::Paren(pat),
619+
}
595620
} else {
596621
PatKind::Tuple(fields)
597622
})
@@ -794,11 +819,21 @@ impl<'a> Parser<'a> {
794819
|| t.can_begin_literal_maybe_minus() // e.g. `42`.
795820
|| t.is_whole_expr()
796821
|| t.is_lifetime() // recover `'a` instead of `'a'`
822+
|| (self.may_recover() // recover leading `(`
823+
&& t.kind == token::OpenDelim(Delimiter::Parenthesis)
824+
&& self.look_ahead(dist + 1, |t| t.kind != token::OpenDelim(Delimiter::Parenthesis))
825+
&& self.is_pat_range_end_start(dist + 1))
797826
})
798827
}
799828

829+
/// Parse a range pattern end bound
800830
fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
801-
if self.check_inline_const(0) {
831+
// recover leading `(`
832+
let open_paren = (self.may_recover()
833+
&& self.eat_noexpect(&token::OpenDelim(Delimiter::Parenthesis)))
834+
.then_some(self.prev_token.span);
835+
836+
let bound = if self.check_inline_const(0) {
802837
self.parse_const_block(self.token.span, true)
803838
} else if self.check_path() {
804839
let lo = self.token.span;
@@ -814,7 +849,22 @@ impl<'a> Parser<'a> {
814849
Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path)))
815850
} else {
816851
self.parse_literal_maybe_minus()
852+
}?;
853+
854+
// recover trailing `)`
855+
if let Some(open_paren) = open_paren {
856+
self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
857+
858+
self.dcx().emit_err(UnexpectedParenInRangePat {
859+
span: vec![open_paren, self.prev_token.span],
860+
sugg: UnexpectedParenInRangePatSugg {
861+
start_span: open_paren,
862+
end_span: self.prev_token.span,
863+
},
864+
});
817865
}
866+
867+
Ok(bound)
818868
}
819869

820870
/// Is this the start of a pattern beginning with a path?

tests/ui/half-open-range-patterns/range_pat_interactions2.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@ fn main() {
88
for x in -9 + 1..=(9 - 2) {
99
match x as i32 {
1010
0..=(5+1) => errors_only.push(x),
11-
//~^ error: inclusive range with no end
12-
//~| error: expected one of `=>`, `if`, or `|`, found `(`
11+
//~^ error: expected `)`, found `+`
1312
1 | -3..0 => first_or.push(x),
1413
y @ (0..5 | 6) => or_two.push(y),
1514
y @ 0..const { 5 + 1 } => assert_eq!(y, 5),
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,8 @@
1-
error[E0586]: inclusive range with no end
2-
--> $DIR/range_pat_interactions2.rs:10:14
1+
error: expected `)`, found `+`
2+
--> $DIR/range_pat_interactions2.rs:10:19
33
|
44
LL | 0..=(5+1) => errors_only.push(x),
5-
| ^^^ help: use `..` instead
6-
|
7-
= note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`)
8-
9-
error: expected one of `=>`, `if`, or `|`, found `(`
10-
--> $DIR/range_pat_interactions2.rs:10:17
11-
|
12-
LL | 0..=(5+1) => errors_only.push(x),
13-
| ^ expected one of `=>`, `if`, or `|`
5+
| ^ expected `)`
146

15-
error: aborting due to 2 previous errors
7+
error: aborting due to 1 previous error
168

17-
For more information about this error, try `rustc --explain E0586`.

tests/ui/parser/pat-recover-ranges.rs

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
fn main() {
2+
match -1 {
3+
0..=1 => (),
4+
0..=(1) => (),
5+
//~^ error: range pattern bounds cannot have parentheses
6+
(-12)..=4 => (),
7+
//~^ error: range pattern bounds cannot have parentheses
8+
(0)..=(-4) => (),
9+
//~^ error: range pattern bounds cannot have parentheses
10+
//~| error: range pattern bounds cannot have parentheses
11+
};
12+
}
13+
14+
macro_rules! m {
15+
($pat:pat) => {};
16+
(($s:literal)..($e:literal)) => {};
17+
}
18+
19+
m!((7)..(7));
+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
error: range pattern bounds cannot have parentheses
2+
--> $DIR/pat-recover-ranges.rs:4:13
3+
|
4+
LL | 0..=(1) => (),
5+
| ^ ^
6+
|
7+
help: remove these parentheses
8+
|
9+
LL - 0..=(1) => (),
10+
LL + 0..=1 => (),
11+
|
12+
13+
error: range pattern bounds cannot have parentheses
14+
--> $DIR/pat-recover-ranges.rs:6:9
15+
|
16+
LL | (-12)..=4 => (),
17+
| ^ ^
18+
|
19+
help: remove these parentheses
20+
|
21+
LL - (-12)..=4 => (),
22+
LL + -12..=4 => (),
23+
|
24+
25+
error: range pattern bounds cannot have parentheses
26+
--> $DIR/pat-recover-ranges.rs:8:9
27+
|
28+
LL | (0)..=(-4) => (),
29+
| ^ ^
30+
|
31+
help: remove these parentheses
32+
|
33+
LL - (0)..=(-4) => (),
34+
LL + 0..=(-4) => (),
35+
|
36+
37+
error: range pattern bounds cannot have parentheses
38+
--> $DIR/pat-recover-ranges.rs:8:15
39+
|
40+
LL | (0)..=(-4) => (),
41+
| ^ ^
42+
|
43+
help: remove these parentheses
44+
|
45+
LL - (0)..=(-4) => (),
46+
LL + (0)..=-4 => (),
47+
|
48+
49+
error: aborting due to 4 previous errors
50+

0 commit comments

Comments
 (0)