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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
use super::{ForceCollect, Parser, PathStyle, TrailingToken};
use crate::parser::diagnostics::RemoveLet;
use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
use rustc_ast::mut_visit::{noop_visit_pat, MutVisitor};
use rustc_ast::ptr::P;
use rustc_ast::token::{self, Delimiter};
use rustc_ast::{
self as ast, AttrVec, BindingAnnotation, ByRef, Expr, ExprKind, MacCall, Mutability, Pat,
PatField, PatKind, Path, QSelf, RangeEnd, RangeSyntax,
};
use rustc_ast_pretty::pprust;
use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, PResult};
use rustc_span::source_map::{respan, Span, Spanned};
use rustc_span::symbol::{kw, sym, Ident};
pub(super) type Expected = Option<&'static str>;
pub(super) const PARAM_EXPECTED: Expected = Some("parameter name");
const WHILE_PARSING_OR_MSG: &str = "while parsing this or-pattern starting here";
#[derive(PartialEq, Copy, Clone)]
pub enum RecoverComma {
Yes,
No,
}
#[derive(PartialEq, Copy, Clone)]
pub enum RecoverColon {
Yes,
No,
}
#[derive(PartialEq, Copy, Clone)]
pub enum CommaRecoveryMode {
LikelyTuple,
EitherTupleOrPipe,
}
#[derive(Debug, Clone, Copy)]
enum EatOrResult {
TrailingVert,
AteOr,
None,
}
impl<'a> Parser<'a> {
pub fn parse_pat_no_top_alt(&mut self, expected: Expected) -> PResult<'a, P<Pat>> {
self.parse_pat_with_range_pat(true, expected)
}
pub fn parse_pat_allow_top_alt(
&mut self,
expected: Expected,
rc: RecoverComma,
ra: RecoverColon,
rt: CommaRecoveryMode,
) -> PResult<'a, P<Pat>> {
self.parse_pat_allow_top_alt_inner(expected, rc, ra, rt).map(|(pat, _)| pat)
}
fn parse_pat_allow_top_alt_inner(
&mut self,
expected: Expected,
rc: RecoverComma,
ra: RecoverColon,
rt: CommaRecoveryMode,
) -> PResult<'a, (P<Pat>, bool)> {
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),
};
let mut first_pat = self.parse_pat_no_top_alt(expected)?;
if rc == RecoverComma::Yes {
self.maybe_recover_unexpected_comma(first_pat.span, rt)?;
}
if !self.check(&token::BinOp(token::Or)) && self.token != token::OrOr {
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 {
let span = leading_vert_span.to(self.prev_token.span);
return Ok((self.mk_pat(span, PatKind::Or(vec![first_pat])), trailing_vert));
}
return Ok((first_pat, trailing_vert));
}
let lo = leading_vert_span.unwrap_or(first_pat.span);
let mut pats = 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).map_err(|mut err| {
err.span_label(lo, WHILE_PARSING_OR_MSG);
err
})?;
if rc == RecoverComma::Yes {
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))
}
pub(super) fn parse_pat_before_ty(
&mut self,
expected: Expected,
rc: RecoverComma,
syntax_loc: &str,
) -> PResult<'a, (P<Pat>, bool)> {
let (pat, trailing_vert) = self.parse_pat_allow_top_alt_inner(
expected,
rc,
RecoverColon::No,
CommaRecoveryMode::LikelyTuple,
)?;
let colon = self.eat(&token::Colon);
if let PatKind::Or(pats) = &pat.kind {
let msg = format!("top-level or-patterns are not allowed in {}", syntax_loc);
let (help, fix) = if pats.len() == 1 {
let msg = "remove the `|`";
let fix = pprust::pat_to_string(&pat);
(msg, fix)
} else {
let msg = "wrap the pattern in parentheses";
let fix = format!("({})", pprust::pat_to_string(&pat));
(msg, fix)
};
if trailing_vert {
self.sess.span_diagnostic.delay_span_bug(pat.span, &msg);
} else {
self.struct_span_err(pat.span, &msg)
.span_suggestion(pat.span, help, fix, Applicability::MachineApplicable)
.emit();
}
}
Ok((pat, colon))
}
pub(super) fn parse_fn_param_pat_colon(&mut self) -> PResult<'a, (P<Pat>, bool)> {
if let token::OrOr = self.token.kind {
let span = self.token.span;
let mut err = self.struct_span_err(span, "unexpected `||` before function parameter");
err.span_suggestion(span, "remove the `||`", "", Applicability::MachineApplicable);
err.note("alternatives in or-patterns are separated with `|`, not `||`");
err.emit();
self.bump();
}
self.parse_pat_before_ty(PARAM_EXPECTED, RecoverComma::No, "function parameters")
}
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) {
self.ban_unexpected_or_or(lo);
self.bump();
EatOrResult::AteOr
} else if self.eat(&token::BinOp(token::Or)) {
EatOrResult::AteOr
} else {
EatOrResult::None
}
}
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 | token::Ident(kw::If, false) | token::Eq | token::Semi | token::Colon | token::Comma | token::CloseDelim(Delimiter::Bracket) | token::CloseDelim(Delimiter::Parenthesis) | token::CloseDelim(Delimiter::Brace) )
});
match (is_end_ahead, &self.token.kind) {
(true, token::BinOp(token::Or) | token::OrOr) => {
self.ban_illegal_vert(lo, "trailing", "not allowed in an or-pattern");
self.bump();
true
}
_ => false,
}
}
fn ban_unexpected_or_or(&mut self, lo: Option<Span>) {
let mut err = self.struct_span_err(self.token.span, "unexpected token `||` in pattern");
err.span_suggestion(
self.token.span,
"use a single `|` to separate multiple alternative patterns",
"|",
Applicability::MachineApplicable,
);
if let Some(lo) = lo {
err.span_label(lo, WHILE_PARSING_OR_MSG);
}
err.emit();
}
fn ban_illegal_vert(&mut self, lo: Option<Span>, pos: &str, ctx: &str) {
let span = self.token.span;
let mut err = self.struct_span_err(span, &format!("a {} `|` is {}", pos, ctx));
err.span_suggestion(
span,
&format!("remove the `{}`", pprust::token_to_string(&self.token)),
"",
Applicability::MachineApplicable,
);
if let Some(lo) = lo {
err.span_label(lo, WHILE_PARSING_OR_MSG);
}
if let token::OrOr = self.token.kind {
err.note("alternatives in or-patterns are separated with `|`, not `||`");
}
err.emit();
}
fn parse_pat_with_range_pat(
&mut self,
allow_range_pat: bool,
expected: Expected,
) -> PResult<'a, P<Pat>> {
maybe_recover_from_interpolated_ty_qpath!(self, true);
maybe_whole!(self, NtPat, |x| x);
let mut lo = self.token.span;
if self.token.is_keyword(kw::Let) && self.look_ahead(1, |tok| tok.can_begin_pattern()) {
self.bump();
self.sess.emit_err(RemoveLet { span: lo });
lo = self.token.span;
}
let pat = if self.check(&token::BinOp(token::And)) || self.token.kind == token::AndAnd {
self.parse_pat_deref(expected)?
} else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
self.parse_pat_tuple_or_parens()?
} else if self.check(&token::OpenDelim(Delimiter::Bracket)) {
let (pats, _) = self.parse_delim_comma_seq(Delimiter::Bracket, |p| {
p.parse_pat_allow_top_alt(
None,
RecoverComma::No,
RecoverColon::No,
CommaRecoveryMode::EitherTupleOrPipe,
)
})?;
PatKind::Slice(pats)
} else if self.check(&token::DotDot) && !self.is_pat_range_end_start(1) {
self.bump(); PatKind::Rest
} else if self.check(&token::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)? } else if self.eat_keyword(kw::Underscore) {
PatKind::Wild
} else if self.eat_keyword(kw::Mut) {
self.parse_pat_ident_mut()?
} else if self.eat_keyword(kw::Ref) {
let mutbl = self.parse_mutability();
self.parse_pat_ident(BindingAnnotation(ByRef::Yes, mutbl))?
} else if self.eat_keyword(kw::Box) {
self.parse_pat_box()?
} else if self.check_inline_const(0) {
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::Lit(const_expr)
}
} else if self.can_be_ident_pat() {
self.parse_pat_ident(BindingAnnotation::NONE)?
} else if self.is_start_of_pat_with_path() {
let (qself, path) = if self.eat_lt() {
let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
(Some(qself), path)
} else {
(None, self.parse_path(PathStyle::Expr)?)
};
let span = lo.to(self.prev_token.span);
if qself.is_none() && self.check(&token::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(&token::OpenDelim(Delimiter::Brace)) {
self.parse_pat_struct(qself, path)?
} else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
self.parse_pat_tuple_struct(qself, path)?
} else {
PatKind::Path(qself, path)
}
} else {
match self.parse_literal_maybe_minus() {
Ok(begin) => match self.parse_range_end() {
Some(form) => self.parse_pat_range_begin_with(begin, form)?,
None => PatKind::Lit(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)
}
fn recover_dotdotdot_rest_pat(&mut self, lo: Span) -> PatKind {
self.bump(); self.struct_span_err(lo, "unexpected `...`")
.span_label(lo, "not a valid pattern")
.span_suggestion_short(
lo,
"for a rest pattern, use `..` instead of `...`",
"..",
Applicability::MachineApplicable,
)
.emit();
PatKind::Rest
}
fn recover_intersection_pat(&mut self, lhs: P<Pat>) -> PResult<'a, P<Pat>> {
if self.token.kind != token::At {
return Ok(lhs);
}
self.bump(); let mut rhs = self.parse_pat_no_top_alt(None)?;
let sp = lhs.span.to(rhs.span);
if let PatKind::Ident(_, _, ref mut sub @ None) = rhs.kind {
let mut applicability = Applicability::MachineApplicable;
lhs.walk(&mut |p| match p.kind {
PatKind::Ident(..) => {
applicability = Applicability::MaybeIncorrect;
false }
_ => true,
});
let lhs_span = lhs.span;
*sub = Some(lhs);
self.struct_span_err(sp, "pattern on wrong side of `@`")
.span_label(lhs_span, "pattern on the left, should be on the right")
.span_label(rhs.span, "binding on the right, should be on the left")
.span_suggestion(sp, "switch the order", pprust::pat_to_string(&rhs), applicability)
.emit();
} else {
rhs.kind = PatKind::Wild;
self.struct_span_err(sp, "left-hand side of `@` must be a binding")
.span_label(lhs.span, "interpreted as a pattern, not a binding")
.span_label(rhs.span, "also a pattern")
.note("bindings are `x`, `mut x`, `ref x`, and `ref mut x`")
.emit();
}
rhs.span = sp;
Ok(rhs)
}
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.struct_span_err(pat.span, "the range pattern here has ambiguous interpretation")
.span_suggestion(
pat.span,
"add parentheses to clarify the precedence",
format!("({})", pprust::pat_to_string(&pat)),
Applicability::MaybeIncorrect,
)
.emit();
}
fn parse_pat_deref(&mut self, expected: Expected) -> PResult<'a, PatKind> {
self.expect_and()?;
self.recover_lifetime_in_deref_pat();
let mutbl = self.parse_mutability();
let subpat = self.parse_pat_with_range_pat(false, expected)?;
Ok(PatKind::Ref(subpat, mutbl))
}
fn recover_lifetime_in_deref_pat(&mut self) {
if let token::Lifetime(name) = self.token.kind {
self.bump(); let span = self.prev_token.span;
self.struct_span_err(span, &format!("unexpected lifetime `{}` in pattern", name))
.span_suggestion(span, "remove the lifetime", "", Applicability::MachineApplicable)
.emit();
}
}
fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| {
p.parse_pat_allow_top_alt(
None,
RecoverComma::No,
RecoverColon::No,
CommaRecoveryMode::LikelyTuple,
)
})?;
Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
PatKind::Paren(fields.into_iter().next().unwrap())
} else {
PatKind::Tuple(fields)
})
}
fn parse_pat_ident_mut(&mut self) -> PResult<'a, PatKind> {
let mut_span = self.prev_token.span;
if self.eat_keyword(kw::Ref) {
return self.recover_mut_ref_ident(mut_span);
}
self.recover_additional_muts();
if let token::Interpolated(ref nt) = self.token.kind {
if let token::NtPat(_) = **nt {
self.expected_ident_found().emit();
}
}
let mut pat = self.parse_pat_no_top_alt(Some("identifier"))?;
if let PatKind::Ident(BindingAnnotation(ByRef::No, m @ Mutability::Not), ..) = &mut pat.kind
{
*m = Mutability::Mut;
} else {
let changed_any_binding = Self::make_all_value_bindings_mutable(&mut pat);
self.ban_mut_general_pat(mut_span, &pat, changed_any_binding);
}
Ok(pat.into_inner().kind)
}
fn recover_mut_ref_ident(&mut self, lo: Span) -> PResult<'a, PatKind> {
let mutref_span = lo.to(self.prev_token.span);
self.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
.span_suggestion(
mutref_span,
"try switching the order",
"ref mut",
Applicability::MachineApplicable,
)
.emit();
self.parse_pat_ident(BindingAnnotation::REF_MUT)
}
fn make_all_value_bindings_mutable(pat: &mut P<Pat>) -> bool {
struct AddMut(bool);
impl MutVisitor for AddMut {
fn visit_pat(&mut self, pat: &mut P<Pat>) {
if let PatKind::Ident(BindingAnnotation(ByRef::No, m @ Mutability::Not), ..) =
&mut pat.kind
{
self.0 = true;
*m = Mutability::Mut;
}
noop_visit_pat(pat, self);
}
}
let mut add_mut = AddMut(false);
add_mut.visit_pat(pat);
add_mut.0
}
fn ban_mut_general_pat(&self, lo: Span, pat: &Pat, changed_any_binding: bool) {
let span = lo.to(pat.span);
let fix = pprust::pat_to_string(&pat);
let (problem, suggestion) = if changed_any_binding {
("`mut` must be attached to each individual binding", "add `mut` to each binding")
} else {
("`mut` must be followed by a named binding", "remove the `mut` prefix")
};
self.struct_span_err(span, problem)
.span_suggestion(span, suggestion, fix, Applicability::MachineApplicable)
.note("`mut` may be followed by `variable` and `variable @ pattern`")
.emit();
}
fn recover_additional_muts(&mut self) {
let lo = self.token.span;
while self.eat_keyword(kw::Mut) {}
if lo == self.token.span {
return;
}
let span = lo.to(self.prev_token.span);
self.struct_span_err(span, "`mut` on a binding may not be repeated")
.span_suggestion(
span,
"remove the additional `mut`s",
"",
Applicability::MachineApplicable,
)
.emit();
}
fn parse_pat_mac_invoc(&mut self, path: Path) -> PResult<'a, PatKind> {
self.bump();
let args = self.parse_mac_args()?;
let mac = P(MacCall { path, args, prior_type_ascription: self.last_type_ascription });
Ok(PatKind::MacCall(mac))
}
fn fatal_unexpected_non_pat(
&mut self,
err: DiagnosticBuilder<'a, ErrorGuaranteed>,
expected: Expected,
) -> PResult<'a, P<Pat>> {
err.cancel();
let expected = expected.unwrap_or("pattern");
let msg = format!("expected {}, found {}", expected, super::token_descr(&self.token));
let mut err = self.struct_span_err(self.token.span, &msg);
err.span_label(self.token.span, format!("expected {}", expected));
let sp = self.sess.source_map().start_point(self.token.span);
if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
self.sess.expr_parentheses_needed(&mut err, *sp);
}
Err(err)
}
fn parse_range_end(&mut self) -> Option<Spanned<RangeEnd>> {
let re = if self.eat(&token::DotDotDot) {
RangeEnd::Included(RangeSyntax::DotDotDot)
} else if self.eat(&token::DotDotEq) {
RangeEnd::Included(RangeSyntax::DotDotEq)
} else if self.eat(&token::DotDot) {
RangeEnd::Excluded
} else {
return None;
};
Some(respan(self.prev_token.span, re))
}
fn parse_pat_range_begin_with(
&mut self,
begin: P<Expr>,
re: Spanned<RangeEnd>,
) -> PResult<'a, PatKind> {
let end = if self.is_pat_range_end_start(0) {
Some(self.parse_pat_range_end()?)
} else {
if let RangeEnd::Included(_) = re.node {
self.inclusive_range_with_incorrect_end(re.span);
}
None
};
Ok(PatKind::Range(Some(begin), end, re))
}
pub(super) fn inclusive_range_with_incorrect_end(&mut self, span: Span) {
let tok = &self.token;
if matches!(tok.kind, token::Eq) && tok.span.lo() == span.hi() {
let span_with_eq = span.to(tok.span);
self.bump();
if self.is_pat_range_end_start(0) {
let _ = self.parse_pat_range_end().map_err(|e| e.cancel());
}
self.error_inclusive_range_with_extra_equals(span_with_eq);
} else {
self.error_inclusive_range_with_no_end(span);
}
}
fn error_inclusive_range_with_extra_equals(&self, span: Span) {
self.struct_span_err(span, "unexpected `=` after inclusive range")
.span_suggestion_short(span, "use `..=` instead", "..=", Applicability::MaybeIncorrect)
.note("inclusive ranges end with a single equals sign (`..=`)")
.emit();
}
fn error_inclusive_range_with_no_end(&self, span: Span) {
struct_span_err!(self.sess.span_diagnostic, span, E0586, "inclusive range with no end")
.span_suggestion_short(span, "use `..` instead", "..", Applicability::MachineApplicable)
.note("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)")
.emit();
}
fn parse_pat_range_to(&mut self, mut re: Spanned<RangeEnd>) -> PResult<'a, PatKind> {
let end = self.parse_pat_range_end()?;
self.sess.gated_spans.gate(sym::half_open_range_patterns, re.span.to(self.prev_token.span));
if let RangeEnd::Included(ref mut syn @ RangeSyntax::DotDotDot) = &mut re.node {
*syn = RangeSyntax::DotDotEq;
self.struct_span_err(re.span, "range-to patterns with `...` are not allowed")
.span_suggestion_short(
re.span,
"use `..=` instead",
"..=",
Applicability::MachineApplicable,
)
.emit();
}
Ok(PatKind::Range(None, Some(end), re))
}
fn is_pat_range_end_start(&self, dist: usize) -> bool {
self.check_inline_const(dist)
|| self.look_ahead(dist, |t| {
t.is_path_start() || t.kind == token::Dot || t.can_begin_literal_maybe_minus() || t.is_whole_expr()
})
}
fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
if self.check_inline_const(0) {
self.parse_const_block(self.token.span, true)
} else if self.check_path() {
let lo = self.token.span;
let (qself, path) = if self.eat_lt() {
let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
(Some(qself), path)
} else {
(None, self.parse_path(PathStyle::Expr)?)
};
let hi = self.prev_token.span;
Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path)))
} else {
self.parse_literal_maybe_minus()
}
}
fn is_start_of_pat_with_path(&mut self) -> bool {
self.check_path()
|| self.token.is_ident() && !self.token.is_bool_lit() && !self.token.is_keyword(kw::In)
}
fn can_be_ident_pat(&mut self) -> bool {
self.check_ident()
&& !self.token.is_bool_lit() && !self.token.is_path_segment_keyword() && !self.token.is_keyword(kw::In)
&& self.look_ahead(1, |t| !matches!(t.kind, token::OpenDelim(Delimiter::Parenthesis) | token::OpenDelim(Delimiter::Brace) | token::DotDotDot | token::DotDotEq | token::DotDot | token::ModSep | token::Not)) }
fn parse_pat_ident(&mut self, binding_annotation: BindingAnnotation) -> PResult<'a, PatKind> {
let ident = self.parse_ident()?;
let sub = if self.eat(&token::At) {
Some(self.parse_pat_no_top_alt(Some("binding pattern"))?)
} else {
None
};
if self.token == token::OpenDelim(Delimiter::Parenthesis) {
return Err(self
.struct_span_err(self.prev_token.span, "expected identifier, found enum pattern"));
}
Ok(PatKind::Ident(binding_annotation, ident, sub))
}
fn parse_pat_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
if qself.is_some() {
self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
}
self.bump();
let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
e.span_label(path.span, "while parsing the fields for this pattern");
e.emit();
self.recover_stmt();
(vec![], true)
});
self.bump();
Ok(PatKind::Struct(qself, path, fields, etc))
}
fn parse_pat_tuple_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
let (fields, _) = self.parse_paren_comma_seq(|p| {
p.parse_pat_allow_top_alt(
None,
RecoverComma::No,
RecoverColon::No,
CommaRecoveryMode::EitherTupleOrPipe,
)
})?;
if qself.is_some() {
self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
}
Ok(PatKind::TupleStruct(qself, path, fields))
}
fn isnt_pattern_start(&self) -> bool {
[
token::Eq,
token::Colon,
token::Comma,
token::Semi,
token::At,
token::OpenDelim(Delimiter::Brace),
token::CloseDelim(Delimiter::Brace),
token::CloseDelim(Delimiter::Parenthesis),
]
.contains(&self.token.kind)
}
fn parse_pat_box(&mut self) -> PResult<'a, PatKind> {
let box_span = self.prev_token.span;
if self.isnt_pattern_start() {
self.struct_span_err(
self.token.span,
format!("expected pattern, found {}", super::token_descr(&self.token)),
)
.span_note(box_span, "`box` is a reserved keyword")
.span_suggestion_verbose(
box_span.shrink_to_lo(),
"escape `box` to use it as an identifier",
"r#",
Applicability::MaybeIncorrect,
)
.emit();
let sub = if self.eat(&token::At) {
Some(self.parse_pat_no_top_alt(Some("binding pattern"))?)
} else {
None
};
Ok(PatKind::Ident(BindingAnnotation::NONE, Ident::new(kw::Box, box_span), sub))
} else {
let pat = self.parse_pat_with_range_pat(false, None)?;
self.sess.gated_spans.gate(sym::box_patterns, box_span.to(self.prev_token.span));
Ok(PatKind::Box(pat))
}
}
fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<PatField>, bool)> {
let mut fields = Vec::new();
let mut etc = false;
let mut ate_comma = true;
let mut delayed_err: Option<DiagnosticBuilder<'a, ErrorGuaranteed>> = None;
let mut etc_span = None;
while self.token != token::CloseDelim(Delimiter::Brace) {
let attrs = match self.parse_outer_attributes() {
Ok(attrs) => attrs,
Err(err) => {
if let Some(mut delayed) = delayed_err {
delayed.emit();
}
return Err(err);
}
};
let lo = self.token.span;
if !ate_comma {
let err = self.struct_span_err(self.token.span, "expected `,`");
if let Some(mut delayed) = delayed_err {
delayed.emit();
}
return Err(err);
}
ate_comma = false;
if self.check(&token::DotDot) || self.token == token::DotDotDot {
etc = true;
let mut etc_sp = self.token.span;
self.recover_one_fewer_dotdot();
self.bump(); if self.token == token::CloseDelim(Delimiter::Brace) {
etc_span = Some(etc_sp);
break;
}
let token_str = super::token_descr(&self.token);
let msg = &format!("expected `}}`, found {}", token_str);
let mut err = self.struct_span_err(self.token.span, msg);
err.span_label(self.token.span, "expected `}`");
let mut comma_sp = None;
if self.token == token::Comma {
let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
etc_sp = etc_sp.to(nw_span);
err.span_label(
etc_sp,
"`..` must be at the end and cannot have a trailing comma",
);
comma_sp = Some(self.token.span);
self.bump();
ate_comma = true;
}
etc_span = Some(etc_sp.until(self.token.span));
if self.token == token::CloseDelim(Delimiter::Brace) {
if let Some(sp) = comma_sp {
err.span_suggestion_short(
sp,
"remove this comma",
"",
Applicability::MachineApplicable,
);
}
err.emit();
break;
} else if self.token.is_ident() && ate_comma {
if let Some(mut delayed_err) = delayed_err {
delayed_err.emit();
return Err(err);
} else {
delayed_err = Some(err);
}
} else {
if let Some(mut err) = delayed_err {
err.emit();
}
return Err(err);
}
}
let field =
self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
let field = match this.parse_pat_field(lo, attrs) {
Ok(field) => Ok(field),
Err(err) => {
if let Some(mut delayed_err) = delayed_err.take() {
delayed_err.emit();
}
return Err(err);
}
}?;
ate_comma = this.eat(&token::Comma);
Ok((field, TrailingToken::None))
})?;
fields.push(field)
}
if let Some(mut err) = delayed_err {
if let Some(etc_span) = etc_span {
err.multipart_suggestion(
"move the `..` to the end of the field list",
vec![
(etc_span, String::new()),
(self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
],
Applicability::MachineApplicable,
);
}
err.emit();
}
Ok((fields, etc))
}
fn recover_one_fewer_dotdot(&self) {
if self.token != token::DotDotDot {
return;
}
self.struct_span_err(self.token.span, "expected field pattern, found `...`")
.span_suggestion(
self.token.span,
"to omit remaining fields, use one fewer `.`",
"..",
Applicability::MachineApplicable,
)
.emit();
}
fn parse_pat_field(&mut self, lo: Span, attrs: AttrVec) -> PResult<'a, PatField> {
let hi;
let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
let fieldname = self.parse_field_name()?;
self.bump();
let pat = self.parse_pat_allow_top_alt(
None,
RecoverComma::No,
RecoverColon::No,
CommaRecoveryMode::EitherTupleOrPipe,
)?;
hi = pat.span;
(pat, fieldname, false)
} else {
let is_box = self.eat_keyword(kw::Box);
let boxed_span = self.token.span;
let is_ref = self.eat_keyword(kw::Ref);
let is_mut = self.eat_keyword(kw::Mut);
let fieldname = self.parse_field_name()?;
hi = self.prev_token.span;
let mutability = match is_mut {
false => Mutability::Not,
true => Mutability::Mut,
};
let ann = BindingAnnotation(ByRef::from(is_ref), mutability);
let fieldpat = self.mk_pat_ident(boxed_span.to(hi), ann, fieldname);
let subpat =
if is_box { self.mk_pat(lo.to(hi), PatKind::Box(fieldpat)) } else { fieldpat };
(subpat, fieldname, true)
};
Ok(PatField {
ident: fieldname,
pat: subpat,
is_shorthand,
attrs,
id: ast::DUMMY_NODE_ID,
span: lo.to(hi),
is_placeholder: false,
})
}
pub(super) fn mk_pat_ident(&self, span: Span, ann: BindingAnnotation, ident: Ident) -> P<Pat> {
self.mk_pat(span, PatKind::Ident(ann, ident, None))
}
pub(super) fn mk_pat(&self, span: Span, kind: PatKind) -> P<Pat> {
P(Pat { kind, span, id: ast::DUMMY_NODE_ID, tokens: None })
}
}