-
Notifications
You must be signed in to change notification settings - Fork 13.1k
/
Copy pathpat.rs
1742 lines (1575 loc) · 70.6 KB
/
pat.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::ops::Bound;
use rustc_ast::mut_visit::{self, MutVisitor};
use rustc_ast::ptr::P;
use rustc_ast::token::{self, BinOpToken, Delimiter, IdentIsRaw, Token};
use rustc_ast::util::parser::ExprPrecedence;
use rustc_ast::visit::{self, Visitor};
use rustc_ast::{
self as ast, Arm, AttrVec, BindingMode, ByRef, Expr, ExprKind, LocalKind, MacCall, Mutability,
Pat, PatField, PatFieldsRest, PatKind, Path, QSelf, RangeEnd, RangeSyntax, Stmt, StmtKind,
};
use rustc_ast_pretty::pprust;
use rustc_errors::{Applicability, Diag, DiagArgValue, PResult, StashKey};
use rustc_session::errors::ExprParenthesesNeeded;
use rustc_span::source_map::{Spanned, respan};
use rustc_span::{BytePos, ErrorGuaranteed, Ident, Span, kw, sym};
use thin_vec::{ThinVec, thin_vec};
use super::{ForceCollect, Parser, PathStyle, Restrictions, Trailing, UsePreAttrPos};
use crate::errors::{
self, AmbiguousRangePattern, AtDotDotInStructPattern, AtInStructPattern,
DotDotDotForRemainingFields, DotDotDotRangeToPatternNotAllowed, DotDotDotRestPattern,
EnumPatternInsteadOfIdentifier, ExpectedBindingLeftOfAt, ExpectedCommaAfterPatternField,
GenericArgsInPatRequireTurbofishSyntax, InclusiveRangeExtraEquals, InclusiveRangeMatchArrow,
InclusiveRangeNoEnd, InvalidMutInPattern, ParenRangeSuggestion, PatternOnWrongSideOfAt,
RemoveLet, RepeatedMutInPattern, SwitchRefBoxOrder, TopLevelOrPatternNotAllowed,
TopLevelOrPatternNotAllowedSugg, TrailingVertNotAllowed, UnexpectedExpressionInPattern,
UnexpectedExpressionInPatternSugg, UnexpectedLifetimeInPattern, UnexpectedParenInRangePat,
UnexpectedParenInRangePatSugg, UnexpectedVertVertBeforeFunctionParam,
UnexpectedVertVertInPattern, WrapInParens,
};
use crate::parser::expr::{DestructuredFloat, could_be_unclosed_char_literal};
use crate::{exp, maybe_recover_from_interpolated_ty_qpath, maybe_whole};
#[derive(PartialEq, Copy, Clone)]
pub enum Expected {
ParameterName,
ArgumentName,
Identifier,
BindingPattern,
}
impl Expected {
// FIXME(#100717): migrate users of this to proper localization
fn to_string_or_fallback(expected: Option<Expected>) -> &'static str {
match expected {
Some(Expected::ParameterName) => "parameter name",
Some(Expected::ArgumentName) => "argument name",
Some(Expected::Identifier) => "identifier",
Some(Expected::BindingPattern) => "binding pattern",
None => "pattern",
}
}
}
const WHILE_PARSING_OR_MSG: &str = "while parsing this or-pattern starting here";
/// Whether or not to recover a `,` when parsing or-patterns.
#[derive(PartialEq, Copy, Clone)]
pub enum RecoverComma {
Yes,
No,
}
/// Whether or not to recover a `:` when parsing patterns that were meant to be paths.
#[derive(PartialEq, Copy, Clone)]
pub enum RecoverColon {
Yes,
No,
}
/// Whether or not to recover a `a, b` when parsing patterns as `(a, b)` or that *and* `a | b`.
#[derive(PartialEq, Copy, Clone)]
pub enum CommaRecoveryMode {
LikelyTuple,
EitherTupleOrPipe,
}
/// The result of `eat_or_separator`. We want to distinguish which case we are in to avoid
/// emitting duplicate diagnostics.
#[derive(Debug, Clone, Copy)]
enum EatOrResult {
/// We recovered from a trailing vert.
TrailingVert,
/// We ate an `|` (or `||` and recovered).
AteOr,
/// We did not eat anything (i.e. the current token is not `|` or `||`).
None,
}
/// The syntax location of a given pattern. Used for diagnostics.
#[derive(Clone, Copy)]
pub enum PatternLocation {
LetBinding,
FunctionParameter,
}
impl<'a> Parser<'a> {
/// Parses a pattern.
///
/// Corresponds to `Pattern` in RFC 3637 and admits guard patterns at the top level.
/// Used when parsing patterns in all cases where neither `PatternNoTopGuard` nor
/// `PatternNoTopAlt` (see below) are used.
pub fn parse_pat_allow_top_guard(
&mut self,
expected: Option<Expected>,
rc: RecoverComma,
ra: RecoverColon,
rt: CommaRecoveryMode,
) -> PResult<'a, P<Pat>> {
let pat = self.parse_pat_no_top_guard(expected, rc, ra, rt)?;
if self.eat_keyword(exp!(If)) {
let cond = self.parse_expr()?;
// Feature-gate guard patterns
self.psess.gated_spans.gate(sym::guard_patterns, cond.span);
let span = pat.span.to(cond.span);
Ok(self.mk_pat(span, PatKind::Guard(pat, cond)))
} else {
Ok(pat)
}
}
/// Parses a pattern.
///
/// Corresponds to `PatternNoTopAlt` in RFC 3637 and does not admit or-patterns
/// or guard patterns at the top level. Used when parsing the parameters of lambda
/// expressions, functions, function pointers, and `pat_param` macro fragments.
pub fn parse_pat_no_top_alt(
&mut self,
expected: Option<Expected>,
syntax_loc: Option<PatternLocation>,
) -> PResult<'a, P<Pat>> {
self.parse_pat_with_range_pat(true, expected, syntax_loc)
}
/// Parses a pattern.
///
/// Corresponds to `PatternNoTopGuard` in RFC 3637 and allows or-patterns, but not
/// guard patterns, at the top level. Used for parsing patterns in `pat` fragments (until
/// the next edition) and `let`, `if let`, and `while let` expressions.
///
/// Note that after the FCP in <https://github.com/rust-lang/rust/issues/81415>,
/// a leading vert is allowed in nested or-patterns, too. This allows us to
/// simplify the grammar somewhat.
pub fn parse_pat_no_top_guard(
&mut self,
expected: Option<Expected>,
rc: RecoverComma,
ra: RecoverColon,
rt: CommaRecoveryMode,
) -> PResult<'a, P<Pat>> {
self.parse_pat_no_top_guard_inner(expected, rc, ra, rt, None).map(|(pat, _)| pat)
}
/// Returns the pattern and a bool indicating whether we recovered from a trailing vert (true =
/// recovered).
fn parse_pat_no_top_guard_inner(
&mut self,
expected: Option<Expected>,
rc: RecoverComma,
ra: RecoverColon,
rt: CommaRecoveryMode,
syntax_loc: Option<PatternLocation>,
) -> PResult<'a, (P<Pat>, bool)> {
// Keep track of whether we recovered from a trailing vert so that we can avoid duplicated
// suggestions (which bothers rustfix).
//
// Allow a '|' before the pats (RFCs 1925, 2530, and 2535).
let (leading_vert_span, mut trailing_vert) = match self.eat_or_separator(None) {
EatOrResult::AteOr => (Some(self.prev_token.span), false),
EatOrResult::TrailingVert => (None, true),
EatOrResult::None => (None, false),
};
// Parse the first pattern (`p_0`).
let mut first_pat = match self.parse_pat_no_top_alt(expected, syntax_loc) {
Ok(pat) => pat,
Err(err)
if self.token.is_reserved_ident()
&& !self.token.is_keyword(kw::In)
&& !self.token.is_keyword(kw::If) =>
{
err.emit();
self.bump();
self.mk_pat(self.token.span, PatKind::Wild)
}
Err(err) => return Err(err),
};
if rc == RecoverComma::Yes && !first_pat.could_be_never_pattern() {
self.maybe_recover_unexpected_comma(first_pat.span, rt)?;
}
// If the next token is not a `|`,
// this is not an or-pattern and we should exit here.
if !self.check(exp!(Or)) && self.token != token::OrOr {
// If we parsed a leading `|` which should be gated,
// then we should really gate the leading `|`.
// This complicated procedure is done purely for diagnostics UX.
// Check if the user wrote `foo:bar` instead of `foo::bar`.
if ra == RecoverColon::Yes {
first_pat = self.maybe_recover_colon_colon_in_pat_typo(first_pat, expected);
}
if let Some(leading_vert_span) = leading_vert_span {
// If there was a leading vert, treat this as an or-pattern. This improves
// diagnostics.
let span = leading_vert_span.to(self.prev_token.span);
return Ok((self.mk_pat(span, PatKind::Or(thin_vec![first_pat])), trailing_vert));
}
return Ok((first_pat, trailing_vert));
}
// Parse the patterns `p_1 | ... | p_n` where `n > 0`.
let lo = leading_vert_span.unwrap_or(first_pat.span);
let mut pats = thin_vec![first_pat];
loop {
match self.eat_or_separator(Some(lo)) {
EatOrResult::AteOr => {}
EatOrResult::None => break,
EatOrResult::TrailingVert => {
trailing_vert = true;
break;
}
}
let pat = self.parse_pat_no_top_alt(expected, syntax_loc).map_err(|mut err| {
err.span_label(lo, WHILE_PARSING_OR_MSG);
err
})?;
if rc == RecoverComma::Yes && !pat.could_be_never_pattern() {
self.maybe_recover_unexpected_comma(pat.span, rt)?;
}
pats.push(pat);
}
let or_pattern_span = lo.to(self.prev_token.span);
Ok((self.mk_pat(or_pattern_span, PatKind::Or(pats)), trailing_vert))
}
/// Parse a pattern and (maybe) a `Colon` in positions where a pattern may be followed by a
/// type annotation (e.g. for `let` bindings or `fn` params).
///
/// Generally, this corresponds to `pat_no_top_alt` followed by an optional `Colon`. It will
/// eat the `Colon` token if one is present.
///
/// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
/// otherwise).
pub(super) fn parse_pat_before_ty(
&mut self,
expected: Option<Expected>,
rc: RecoverComma,
syntax_loc: PatternLocation,
) -> PResult<'a, (P<Pat>, bool)> {
// We use `parse_pat_allow_top_alt` regardless of whether we actually want top-level
// or-patterns so that we can detect when a user tries to use it. This allows us to print a
// better error message.
let (pat, trailing_vert) = self.parse_pat_no_top_guard_inner(
expected,
rc,
RecoverColon::No,
CommaRecoveryMode::LikelyTuple,
Some(syntax_loc),
)?;
let colon = self.eat(exp!(Colon));
if let PatKind::Or(pats) = &pat.kind {
let span = pat.span;
let sub = if pats.len() == 1 {
Some(TopLevelOrPatternNotAllowedSugg::RemoveLeadingVert {
span: span.with_hi(span.lo() + BytePos(1)),
})
} else {
Some(TopLevelOrPatternNotAllowedSugg::WrapInParens {
span,
suggestion: WrapInParens { lo: span.shrink_to_lo(), hi: span.shrink_to_hi() },
})
};
let err = self.dcx().create_err(match syntax_loc {
PatternLocation::LetBinding => {
TopLevelOrPatternNotAllowed::LetBinding { span, sub }
}
PatternLocation::FunctionParameter => {
TopLevelOrPatternNotAllowed::FunctionParameter { span, sub }
}
});
if trailing_vert {
err.delay_as_bug();
} else {
err.emit();
}
}
Ok((pat, colon))
}
/// Parse the pattern for a function or function pointer parameter, followed by a colon.
///
/// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
/// otherwise).
pub(super) fn parse_fn_param_pat_colon(&mut self) -> PResult<'a, (P<Pat>, bool)> {
// In order to get good UX, we first recover in the case of a leading vert for an illegal
// top-level or-pat. Normally, this means recovering both `|` and `||`, but in this case,
// a leading `||` probably doesn't indicate an or-pattern attempt, so we handle that
// separately.
if let token::OrOr = self.token.kind {
self.dcx().emit_err(UnexpectedVertVertBeforeFunctionParam { span: self.token.span });
self.bump();
}
self.parse_pat_before_ty(
Some(Expected::ParameterName),
RecoverComma::No,
PatternLocation::FunctionParameter,
)
}
/// Eat the or-pattern `|` separator.
/// If instead a `||` token is encountered, recover and pretend we parsed `|`.
fn eat_or_separator(&mut self, lo: Option<Span>) -> EatOrResult {
if self.recover_trailing_vert(lo) {
EatOrResult::TrailingVert
} else if matches!(self.token.kind, token::OrOr) {
// Found `||`; Recover and pretend we parsed `|`.
self.dcx().emit_err(UnexpectedVertVertInPattern { span: self.token.span, start: lo });
self.bump();
EatOrResult::AteOr
} else if self.eat(exp!(Or)) {
EatOrResult::AteOr
} else {
EatOrResult::None
}
}
/// Recover if `|` or `||` is the current token and we have one of the
/// tokens `=>`, `if`, `=`, `:`, `;`, `,`, `]`, `)`, or `}` ahead of us.
///
/// These tokens all indicate that we reached the end of the or-pattern
/// list and can now reliably say that the `|` was an illegal trailing vert.
/// Note that there are more tokens such as `@` for which we know that the `|`
/// is an illegal parse. However, the user's intent is less clear in that case.
fn recover_trailing_vert(&mut self, lo: Option<Span>) -> bool {
let is_end_ahead = self.look_ahead(1, |token| {
matches!(
&token.uninterpolate().kind,
token::FatArrow // e.g. `a | => 0,`.
| token::Ident(kw::If, token::IdentIsRaw::No) // e.g. `a | if expr`.
| token::Eq // e.g. `let a | = 0`.
| token::Semi // e.g. `let a |;`.
| token::Colon // e.g. `let a | :`.
| token::Comma // e.g. `let (a |,)`.
| token::CloseDelim(Delimiter::Bracket) // e.g. `let [a | ]`.
| token::CloseDelim(Delimiter::Parenthesis) // e.g. `let (a | )`.
| token::CloseDelim(Delimiter::Brace) // e.g. `let A { f: a | }`.
)
});
match (is_end_ahead, &self.token.kind) {
(true, token::BinOp(token::Or) | token::OrOr) => {
// A `|` or possibly `||` token shouldn't be here. Ban it.
self.dcx().emit_err(TrailingVertNotAllowed {
span: self.token.span,
start: lo,
token: self.token.clone(),
note_double_vert: matches!(self.token.kind, token::OrOr),
});
self.bump();
true
}
_ => false,
}
}
/// Ensures that the last parsed pattern (or pattern range bound) is not followed by an expression.
///
/// `is_end_bound` indicates whether the last parsed thing was the end bound of a range pattern (see [`parse_pat_range_end`](Self::parse_pat_range_end))
/// in order to say "expected a pattern range bound" instead of "expected a pattern";
/// ```text
/// 0..=1 + 2
/// ^^^^^
/// ```
/// Only the end bound is spanned in this case, and this function has no idea if there was a `..=` before `pat_span`, hence the parameter.
///
/// This function returns `Some` if a trailing expression was recovered, and said expression's span.
#[must_use = "the pattern must be discarded as `PatKind::Err` if this function returns Some"]
fn maybe_recover_trailing_expr(
&mut self,
pat_span: Span,
is_end_bound: bool,
) -> Option<(ErrorGuaranteed, Span)> {
if self.prev_token.is_keyword(kw::Underscore) || !self.may_recover() {
// Don't recover anything after an `_` or if recovery is disabled.
return None;
}
// Returns `true` iff `token` is an unsuffixed integer.
let is_one_tuple_index = |_: &Self, token: &Token| -> bool {
use token::{Lit, LitKind};
matches!(
token.kind,
token::Literal(Lit { kind: LitKind::Integer, symbol: _, suffix: None })
)
};
// Returns `true` iff `token` is an unsuffixed `x.y` float.
let is_two_tuple_indexes = |this: &Self, token: &Token| -> bool {
use token::{Lit, LitKind};
if let token::Literal(Lit { kind: LitKind::Float, symbol, suffix: None }) = token.kind
&& let DestructuredFloat::MiddleDot(..) = this.break_up_float(symbol, token.span)
{
true
} else {
false
}
};
// Check for `.hello` or `.0`.
let has_dot_expr = self.check_noexpect(&token::Dot) // `.`
&& self.look_ahead(1, |tok| {
tok.is_ident() // `hello`
|| is_one_tuple_index(&self, &tok) // `0`
|| is_two_tuple_indexes(&self, &tok) // `0.0`
});
// Check for operators.
// `|` is excluded as it is used in pattern alternatives and lambdas,
// `?` is included for error propagation,
// `[` is included for indexing operations,
// `[]` is excluded as `a[]` isn't an expression and should be recovered as `a, []` (cf. `tests/ui/parser/pat-lt-bracket-7.rs`),
// `as` is included for type casts
let has_trailing_operator = matches!(self.token.kind, token::BinOp(op) if op != BinOpToken::Or)
|| self.token == token::Question
|| (self.token == token::OpenDelim(Delimiter::Bracket)
&& self.look_ahead(1, |t| *t != token::CloseDelim(Delimiter::Bracket))) // excludes `[]`
|| self.token.is_keyword(kw::As);
if !has_dot_expr && !has_trailing_operator {
// Nothing to recover here.
return None;
}
// Let's try to parse an expression to emit a better diagnostic.
let mut snapshot = self.create_snapshot_for_diagnostic();
snapshot.restrictions.insert(Restrictions::IS_PAT);
// Parse `?`, `.f`, `(arg0, arg1, ...)` or `[expr]` until they've all been eaten.
let Ok(expr) = snapshot
.parse_expr_dot_or_call_with(
AttrVec::new(),
self.mk_expr(pat_span, ExprKind::Dummy), // equivalent to transforming the parsed pattern into an `Expr`
pat_span,
)
.map_err(|err| err.cancel())
else {
// We got a trailing method/operator, but that wasn't an expression.
return None;
};
// Parse an associative expression such as `+ expr`, `% expr`, ...
// Assignments, ranges and `|` are disabled by [`Restrictions::IS_PAT`].
let Ok((expr, _)) = snapshot
.parse_expr_assoc_rest_with(Bound::Unbounded, false, expr)
.map_err(|err| err.cancel())
else {
// We got a trailing method/operator, but that wasn't an expression.
return None;
};
// We got a valid expression.
self.restore_snapshot(snapshot);
self.restrictions.remove(Restrictions::IS_PAT);
let is_bound = is_end_bound
// is_start_bound: either `..` or `)..`
|| self.token.is_range_separator()
|| self.token == token::CloseDelim(Delimiter::Parenthesis)
&& self.look_ahead(1, Token::is_range_separator);
let span = expr.span;
Some((
self.dcx()
.create_err(UnexpectedExpressionInPattern {
span,
is_bound,
expr_precedence: expr.precedence(),
})
.stash(span, StashKey::ExprInPat)
.unwrap(),
span,
))
}
/// Called by [`Parser::parse_stmt_without_recovery`], used to add statement-aware subdiagnostics to the errors stashed
/// by [`Parser::maybe_recover_trailing_expr`].
pub(super) fn maybe_augment_stashed_expr_in_pats_with_suggestions(&mut self, stmt: &Stmt) {
if self.dcx().has_errors().is_none() {
// No need to walk the statement if there's no stashed errors.
return;
}
struct PatVisitor<'a> {
/// `self`
parser: &'a Parser<'a>,
/// The freshly-parsed statement.
stmt: &'a Stmt,
/// The current match arm (for arm guard suggestions).
arm: Option<&'a Arm>,
/// The current struct field (for variable name suggestions).
field: Option<&'a PatField>,
}
impl<'a> PatVisitor<'a> {
/// Looks for stashed [`StashKey::ExprInPat`] errors in `stash_span`, and emit them with suggestions.
/// `stash_span` is contained in `expr_span`, the latter being larger in borrow patterns;
/// ```txt
/// &mut x.y
/// -----^^^ `stash_span`
/// |
/// `expr_span`
/// ```
/// `is_range_bound` is used to exclude arm guard suggestions in range pattern bounds.
fn maybe_add_suggestions_then_emit(
&self,
stash_span: Span,
expr_span: Span,
is_range_bound: bool,
) {
self.parser.dcx().try_steal_modify_and_emit_err(
stash_span,
StashKey::ExprInPat,
|err| {
// Includes pre-pats (e.g. `&mut <err>`) in the diagnostic.
err.span.replace(stash_span, expr_span);
let sm = self.parser.psess.source_map();
let stmt = self.stmt;
let line_lo = sm.span_extend_to_line(stmt.span).shrink_to_lo();
let indentation = sm.indentation_before(stmt.span).unwrap_or_default();
let Ok(expr) = self.parser.span_to_snippet(expr_span) else {
// FIXME: some suggestions don't actually need the snippet; see PR #123877's unresolved conversations.
return;
};
if let StmtKind::Let(local) = &stmt.kind {
match &local.kind {
LocalKind::Decl | LocalKind::Init(_) => {
// It's kinda hard to guess what the user intended, so don't make suggestions.
return;
}
LocalKind::InitElse(_, _) => {}
}
}
// help: use an arm guard `if val == expr`
// FIXME(guard_patterns): suggest this regardless of a match arm.
if let Some(arm) = &self.arm
&& !is_range_bound
{
let (ident, ident_span) = match self.field {
Some(field) => {
(field.ident.to_string(), field.ident.span.to(expr_span))
}
None => ("val".to_owned(), expr_span),
};
// Are parentheses required around `expr`?
// HACK: a neater way would be preferable.
let expr = match &err.args["expr_precedence"] {
DiagArgValue::Number(expr_precedence) => {
if *expr_precedence <= ExprPrecedence::Compare as i32 {
format!("({expr})")
} else {
format!("{expr}")
}
}
_ => unreachable!(),
};
match &arm.guard {
None => {
err.subdiagnostic(
UnexpectedExpressionInPatternSugg::CreateGuard {
ident_span,
pat_hi: arm.pat.span.shrink_to_hi(),
ident,
expr,
},
);
}
Some(guard) => {
// Are parentheses required around the old guard?
let wrap_guard = guard.precedence() <= ExprPrecedence::LAnd;
err.subdiagnostic(
UnexpectedExpressionInPatternSugg::UpdateGuard {
ident_span,
guard_lo: if wrap_guard {
Some(guard.span.shrink_to_lo())
} else {
None
},
guard_hi: guard.span.shrink_to_hi(),
guard_hi_paren: if wrap_guard { ")" } else { "" },
ident,
expr,
},
);
}
}
}
// help: extract the expr into a `const VAL: _ = expr`
let ident = match self.field {
Some(field) => field.ident.as_str().to_uppercase(),
None => "VAL".to_owned(),
};
err.subdiagnostic(UnexpectedExpressionInPatternSugg::Const {
stmt_lo: line_lo,
ident_span: expr_span,
expr,
ident,
indentation,
});
// help: wrap the expr in a `const { expr }`
// FIXME(inline_const_pat): once stabilized, remove this check and remove the `(requires #[feature(inline_const_pat)])` note from the message
if self.parser.psess.unstable_features.is_nightly_build() {
err.subdiagnostic(UnexpectedExpressionInPatternSugg::InlineConst {
start_span: expr_span.shrink_to_lo(),
end_span: expr_span.shrink_to_hi(),
});
}
},
);
}
}
impl<'a> Visitor<'a> for PatVisitor<'a> {
fn visit_arm(&mut self, a: &'a Arm) -> Self::Result {
self.arm = Some(a);
visit::walk_arm(self, a);
self.arm = None;
}
fn visit_pat_field(&mut self, fp: &'a PatField) -> Self::Result {
self.field = Some(fp);
visit::walk_pat_field(self, fp);
self.field = None;
}
fn visit_pat(&mut self, p: &'a Pat) -> Self::Result {
match &p.kind {
// Base expression
PatKind::Err(_) | PatKind::Expr(_) => {
self.maybe_add_suggestions_then_emit(p.span, p.span, false)
}
// Sub-patterns
// FIXME: this doesn't work with recursive subpats (`&mut &mut <err>`)
PatKind::Box(subpat) | PatKind::Ref(subpat, _)
if matches!(subpat.kind, PatKind::Err(_) | PatKind::Expr(_)) =>
{
self.maybe_add_suggestions_then_emit(subpat.span, p.span, false)
}
// Sub-expressions
PatKind::Range(start, end, _) => {
if let Some(start) = start {
self.maybe_add_suggestions_then_emit(start.span, start.span, true);
}
if let Some(end) = end {
self.maybe_add_suggestions_then_emit(end.span, end.span, true);
}
}
// Walk continuation
_ => visit::walk_pat(self, p),
}
}
}
// Starts the visit.
PatVisitor { parser: self, stmt, arm: None, field: None }.visit_stmt(stmt);
}
/// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
/// allowed).
fn parse_pat_with_range_pat(
&mut self,
allow_range_pat: bool,
expected: Option<Expected>,
syntax_loc: Option<PatternLocation>,
) -> PResult<'a, P<Pat>> {
maybe_recover_from_interpolated_ty_qpath!(self, true);
maybe_whole!(self, NtPat, |pat| pat);
let mut lo = self.token.span;
if self.token.is_keyword(kw::Let)
&& self.look_ahead(1, |tok| {
tok.can_begin_pattern(token::NtPatKind::PatParam { inferred: false })
})
{
self.bump();
// Trim extra space after the `let`
let span = lo.with_hi(self.token.span.lo());
self.dcx().emit_err(RemoveLet { span: lo, suggestion: span });
lo = self.token.span;
}
let pat = if self.check(exp!(And)) || self.token == token::AndAnd {
self.parse_pat_deref(expected)?
} else if self.check(exp!(OpenParen)) {
self.parse_pat_tuple_or_parens()?
} else if self.check(exp!(OpenBracket)) {
// Parse `[pat, pat,...]` as a slice pattern.
let (pats, _) =
self.parse_delim_comma_seq(exp!(OpenBracket), exp!(CloseBracket), |p| {
p.parse_pat_allow_top_guard(
None,
RecoverComma::No,
RecoverColon::No,
CommaRecoveryMode::EitherTupleOrPipe,
)
})?;
PatKind::Slice(pats)
} else if self.check(exp!(DotDot)) && !self.is_pat_range_end_start(1) {
// A rest pattern `..`.
self.bump(); // `..`
PatKind::Rest
} else if self.check(exp!(DotDotDot)) && !self.is_pat_range_end_start(1) {
self.recover_dotdotdot_rest_pat(lo)
} else if let Some(form) = self.parse_range_end() {
self.parse_pat_range_to(form)? // `..=X`, `...X`, or `..X`.
} else if self.eat(exp!(Not)) {
// Parse `!`
self.psess.gated_spans.gate(sym::never_patterns, self.prev_token.span);
PatKind::Never
} else if self.eat_keyword(exp!(Underscore)) {
// Parse `_`
PatKind::Wild
} else if self.eat_keyword(exp!(Mut)) {
self.parse_pat_ident_mut()?
} else if self.eat_keyword(exp!(Ref)) {
if self.check_keyword(exp!(Box)) {
// Suggest `box ref`.
let span = self.prev_token.span.to(self.token.span);
self.bump();
self.dcx().emit_err(SwitchRefBoxOrder { span });
}
// Parse ref ident @ pat / ref mut ident @ pat
let mutbl = self.parse_mutability();
self.parse_pat_ident(BindingMode(ByRef::Yes(mutbl), Mutability::Not), syntax_loc)?
} else if self.eat_keyword(exp!(Box)) {
self.parse_pat_box()?
} else if self.check_inline_const(0) {
// Parse `const pat`
let const_expr = self.parse_const_block(lo.to(self.token.span), true)?;
if let Some(re) = self.parse_range_end() {
self.parse_pat_range_begin_with(const_expr, re)?
} else {
PatKind::Expr(const_expr)
}
} else if self.is_builtin() {
self.parse_pat_builtin()?
}
// Don't eagerly error on semantically invalid tokens when matching
// declarative macros, as the input to those doesn't have to be
// semantically valid. For attribute/derive proc macros this is not the
// case, so doing the recovery for them is fine.
else if self.can_be_ident_pat()
|| (self.is_lit_bad_ident().is_some() && self.may_recover())
{
// Parse `ident @ pat`
// This can give false positives and parse nullary enums,
// they are dealt with later in resolve.
self.parse_pat_ident(BindingMode::NONE, syntax_loc)?
} else if self.is_start_of_pat_with_path() {
// Parse pattern starting with a path
let (qself, path) = if self.eat_lt() {
// Parse a qualified path
let (qself, path) = self.parse_qpath(PathStyle::Pat)?;
(Some(qself), path)
} else {
// Parse an unqualified path
(None, self.parse_path(PathStyle::Pat)?)
};
let span = lo.to(self.prev_token.span);
if qself.is_none() && self.check(exp!(Not)) {
self.parse_pat_mac_invoc(path)?
} else if let Some(form) = self.parse_range_end() {
let begin = self.mk_expr(span, ExprKind::Path(qself, path));
self.parse_pat_range_begin_with(begin, form)?
} else if self.check(exp!(OpenBrace)) {
self.parse_pat_struct(qself, path)?
} else if self.check(exp!(OpenParen)) {
self.parse_pat_tuple_struct(qself, path)?
} else {
match self.maybe_recover_trailing_expr(span, false) {
Some((guar, _)) => PatKind::Err(guar),
None => PatKind::Path(qself, path),
}
}
} else if let Some((lt, IdentIsRaw::No)) = self.token.lifetime()
// In pattern position, we're totally fine with using "next token isn't colon"
// as a heuristic. We could probably just always try to recover if it's a lifetime,
// because we never have `'a: label {}` in a pattern position anyways, but it does
// keep us from suggesting something like `let 'a: Ty = ..` => `let 'a': Ty = ..`
&& could_be_unclosed_char_literal(lt)
&& !self.look_ahead(1, |token| matches!(token.kind, token::Colon))
{
// Recover a `'a` as a `'a'` literal
let lt = self.expect_lifetime();
let (lit, _) =
self.recover_unclosed_char(lt.ident, Parser::mk_token_lit_char, |self_| {
let expected = Expected::to_string_or_fallback(expected);
let msg = format!(
"expected {}, found {}",
expected,
super::token_descr(&self_.token)
);
self_
.dcx()
.struct_span_err(self_.token.span, msg)
.with_span_label(self_.token.span, format!("expected {expected}"))
});
PatKind::Expr(self.mk_expr(lo, ExprKind::Lit(lit)))
} else {
// Try to parse everything else as literal with optional minus
match self.parse_literal_maybe_minus() {
Ok(begin) => {
let begin = self
.maybe_recover_trailing_expr(begin.span, false)
.map(|(guar, sp)| self.mk_expr_err(sp, guar))
.unwrap_or(begin);
match self.parse_range_end() {
Some(form) => self.parse_pat_range_begin_with(begin, form)?,
None => PatKind::Expr(begin),
}
}
Err(err) => return self.fatal_unexpected_non_pat(err, expected),
}
};
let pat = self.mk_pat(lo.to(self.prev_token.span), pat);
let pat = self.maybe_recover_from_bad_qpath(pat)?;
let pat = self.recover_intersection_pat(pat)?;
if !allow_range_pat {
self.ban_pat_range_if_ambiguous(&pat)
}
Ok(pat)
}
/// Recover from a typoed `...` pattern that was encountered
/// Ref: Issue #70388
fn recover_dotdotdot_rest_pat(&mut self, lo: Span) -> PatKind {
// A typoed rest pattern `...`.
self.bump(); // `...`
// The user probably mistook `...` for a rest pattern `..`.
self.dcx().emit_err(DotDotDotRestPattern {
span: lo,
suggestion: lo.with_lo(lo.hi() - BytePos(1)),
});
PatKind::Rest
}
/// Try to recover the more general form `intersect ::= $pat_lhs @ $pat_rhs`.
///
/// Allowed binding patterns generated by `binding ::= ref? mut? $ident @ $pat_rhs`
/// should already have been parsed by now at this point,
/// if the next token is `@` then we can try to parse the more general form.
///
/// Consult `parse_pat_ident` for the `binding` grammar.
///
/// The notion of intersection patterns are found in
/// e.g. [F#][and] where they are called AND-patterns.
///
/// [and]: https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/pattern-matching
fn recover_intersection_pat(&mut self, lhs: P<Pat>) -> PResult<'a, P<Pat>> {
if self.token != token::At {
// Next token is not `@` so it's not going to be an intersection pattern.
return Ok(lhs);
}
// At this point we attempt to parse `@ $pat_rhs` and emit an error.
self.bump(); // `@`
let mut rhs = self.parse_pat_no_top_alt(None, None)?;
let whole_span = lhs.span.to(rhs.span);
if let PatKind::Ident(_, _, sub @ None) = &mut rhs.kind {
// The user inverted the order, so help them fix that.
let lhs_span = lhs.span;
// Move the LHS into the RHS as a subpattern.
// The RHS is now the full pattern.
*sub = Some(lhs);
self.dcx().emit_err(PatternOnWrongSideOfAt {
whole_span,
whole_pat: pprust::pat_to_string(&rhs),
pattern: lhs_span,
binding: rhs.span,
});
} else {
// The special case above doesn't apply so we may have e.g. `A(x) @ B(y)`.
rhs.kind = PatKind::Wild;
self.dcx().emit_err(ExpectedBindingLeftOfAt {
whole_span,
lhs: lhs.span,
rhs: rhs.span,
});
}
rhs.span = whole_span;
Ok(rhs)
}
/// Ban a range pattern if it has an ambiguous interpretation.
fn ban_pat_range_if_ambiguous(&self, pat: &Pat) {
match pat.kind {
PatKind::Range(
..,
Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. },
) => return,
PatKind::Range(..) => {}
_ => return,
}
self.dcx().emit_err(AmbiguousRangePattern {
span: pat.span,
suggestion: ParenRangeSuggestion {
lo: pat.span.shrink_to_lo(),
hi: pat.span.shrink_to_hi(),
},
});
}
/// Parse `&pat` / `&mut pat`.
fn parse_pat_deref(&mut self, expected: Option<Expected>) -> PResult<'a, PatKind> {
self.expect_and()?;
if let Some((lifetime, _)) = self.token.lifetime() {
self.bump(); // `'a`
self.dcx().emit_err(UnexpectedLifetimeInPattern {
span: self.prev_token.span,
symbol: lifetime.name,
suggestion: self.prev_token.span.until(self.token.span),
});
}
let mutbl = self.parse_mutability();
let subpat = self.parse_pat_with_range_pat(false, expected, None)?;
Ok(PatKind::Ref(subpat, mutbl))
}
/// Parse a tuple or parenthesis pattern.
fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
let open_paren = self.token.span;
let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| {
p.parse_pat_allow_top_guard(
None,
RecoverComma::No,
RecoverColon::No,
CommaRecoveryMode::LikelyTuple,
)
})?;
// Here, `(pat,)` is a tuple pattern.
// For backward compatibility, `(..)` is a tuple pattern as well.
let paren_pattern =
fields.len() == 1 && !(matches!(trailing_comma, Trailing::Yes) || fields[0].is_rest());
let pat = if paren_pattern {
let pat = fields.into_iter().next().unwrap();
let close_paren = self.prev_token.span;
match &pat.kind {
// recover ranges with parentheses around the `(start)..`
PatKind::Expr(begin)
if self.may_recover()
&& let Some(form) = self.parse_range_end() =>
{
self.dcx().emit_err(UnexpectedParenInRangePat {
span: vec![open_paren, close_paren],
sugg: UnexpectedParenInRangePatSugg {
start_span: open_paren,
end_span: close_paren,