::B::C` can only legally refer to
56 /// associated constants.
57 Path(PatPath),
58
59 /// A range pattern: `1..=2`.
60 Range(PatRange),
61
62 /// A reference pattern: `&mut var`.
63 Reference(PatReference),
64
65 /// The dots in a tuple or slice pattern: `[0, 1, ..]`.
66 Rest(PatRest),
67
68 /// A dynamically sized slice pattern: `[a, b, ref i @ .., y, z]`.
69 Slice(PatSlice),
70
71 /// A struct or struct variant pattern: `Variant { x, y, .. }`.
72 Struct(PatStruct),
73
74 /// A tuple pattern: `(a, b)`.
75 Tuple(PatTuple),
76
77 /// A tuple struct or tuple variant pattern: `Variant(x, y, .., z)`.
78 TupleStruct(PatTupleStruct),
79
80 /// A type ascription pattern: `foo: f64`.
81 Type(PatType),
82
83 /// Tokens in pattern position not interpreted by Syn.
84 ///
85 ///
86 ///
87 /// Important: see [Compatibility notes][crate#verbatim-variants].
88 ///
89 ///
90 Verbatim(TokenStream),
91
92 /// A pattern that matches any value: `_`.
93 Wild(PatWild),
94 }
95 }
96
97 ast_struct! {
98 /// A pattern that binds a new variable: `ref mut binding @ SUBPATTERN`.
99 ///
100 /// It may also be a unit struct or struct variant (e.g. `None`), or a
101 /// constant; these cannot be distinguished syntactically.
102 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
103 pub struct PatIdent {
104 pub attrs: Vec,
105 pub by_ref: Option,
106 pub mutability: Option,
107 pub ident: Ident,
108 pub subpat: Option<(Token![@], Box)>,
109 }
110 }
111
112 ast_struct! {
113 /// A pattern with guard predicate: `Some(x) if x > 0`.
114 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
115 pub struct PatGuard {
116 pub attrs: Vec,
117 pub pat: Box,
118 pub if_token: Token![if],
119 pub guard: Box,
120 }
121 }
122
123 ast_struct! {
124 /// A pattern that matches any one of a set of cases.
125 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
126 pub struct PatOr {
127 pub attrs: Vec,
128 pub leading_vert: Option,
129 pub cases: Punctuated,
130 }
131 }
132
133 ast_struct! {
134 /// A parenthesized pattern: `(A | B)`.
135 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
136 pub struct PatParen {
137 pub attrs: Vec,
138 pub paren_token: token::Paren,
139 pub pat: Box,
140 }
141 }
142
143 ast_struct! {
144 /// A reference pattern: `&mut var`.
145 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
146 pub struct PatReference {
147 pub attrs: Vec,
148 pub and_token: Token![&],
149 pub mutability: Option,
150 pub pat: Box,
151 }
152 }
153
154 ast_struct! {
155 /// The dots in a tuple or slice pattern: `[0, 1, ..]`.
156 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
157 pub struct PatRest {
158 pub attrs: Vec,
159 pub dot2_token: Token![..],
160 }
161 }
162
163 ast_struct! {
164 /// A dynamically sized slice pattern: `[a, b, ref i @ .., y, z]`.
165 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
166 pub struct PatSlice {
167 pub attrs: Vec,
168 pub bracket_token: token::Bracket,
169 pub elems: Punctuated,
170 }
171 }
172
173 ast_struct! {
174 /// A struct or struct variant pattern: `Variant { x, y, .. }`.
175 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
176 pub struct PatStruct {
177 pub attrs: Vec,
178 pub qself: Option,
179 pub path: Path,
180 pub brace_token: token::Brace,
181 pub fields: Punctuated,
182 pub rest: Option,
183 }
184 }
185
186 ast_struct! {
187 /// A tuple pattern: `(a, b)`.
188 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
189 pub struct PatTuple {
190 pub attrs: Vec,
191 pub paren_token: token::Paren,
192 pub elems: Punctuated,
193 }
194 }
195
196 ast_struct! {
197 /// A tuple struct or tuple variant pattern: `Variant(x, y, .., z)`.
198 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
199 pub struct PatTupleStruct {
200 pub attrs: Vec,
201 pub qself: Option,
202 pub path: Path,
203 pub paren_token: token::Paren,
204 pub elems: Punctuated,
205 }
206 }
207
208 ast_struct! {
209 /// A type ascription pattern: `foo: f64`.
210 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
211 pub struct PatType {
212 pub attrs: Vec,
213 pub pat: Box,
214 pub colon_token: Token![:],
215 pub ty: Box,
216 }
217 }
218
219 ast_struct! {
220 /// A pattern that matches any value: `_`.
221 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
222 pub struct PatWild {
223 pub attrs: Vec,
224 pub underscore_token: Token![_],
225 }
226 }
227
228 ast_struct! {
229 /// A single field in a struct pattern.
230 ///
231 /// Patterns like the fields of `Pat { x, ref y, ref mut z }` are treated
232 /// the same as `x: x, y: ref y, z: ref mut z` but there is no colon token.
233 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
234 pub struct FieldPat {
235 pub attrs: Vec,
236 pub member: Member,
237 pub colon_token: Option,
238 pub pat: Box,
239 }
240 }
241
242 #[cfg(feature = "parsing")]
243 pub(crate) mod parsing {
244 use crate::attr::Attribute;
245 use crate::buffer::Cursor;
246 use crate::error::{self, Result};
247 use crate::expr::{
248 Expr, ExprConst, ExprLit, ExprMacro, ExprPath, ExprRange, Member, RangeLimits,
249 };
250 use crate::ext::IdentExt as _;
251 use crate::ident::Ident;
252 use crate::lit::Lit;
253 use crate::mac::{self, Macro};
254 use crate::parse::{Parse, ParseStream};
255 use crate::pat::{
256 FieldPat, Pat, PatGuard, PatIdent, PatOr, PatParen, PatReference, PatRest, PatSlice,
257 PatStruct, PatTuple, PatTupleStruct, PatType, PatWild,
258 };
259 use crate::path::{self, Path, QSelf};
260 use crate::punctuated::Punctuated;
261 use crate::stmt::Block;
262 use crate::token;
263 use crate::verbatim;
264 use alloc::boxed::Box;
265 use alloc::vec::Vec;
266 use proc_macro2::TokenStream;
267
268 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
269 impl Pat {
270 /// Parse a pattern that does _not_ involve `|` at the top level.
271 ///
272 /// This parser matches the behavior of the `$:pat_param` macro_rules
273 /// matcher, and on editions prior to Rust 2021, the behavior of
274 /// `$:pat`.
275 ///
276 /// In Rust syntax, some examples of where this syntax would occur are
277 /// in the argument pattern of functions and closures. Patterns using
278 /// `|` are not allowed to occur in these positions.
279 ///
280 /// ```compile_fail
281 /// fn f(Some(_) | None: Option) {
282 /// let _ = |Some(_) | None: Option| {};
283 /// // ^^^^^^^^^^^^^^^^^^^^^^^^^??? :(
284 /// }
285 /// ```
286 ///
287 /// ```console
288 /// error: top-level or-patterns are not allowed in function parameters
289 /// --> src/main.rs:1:6
290 /// |
291 /// 1 | fn f(Some(_) | None: Option) {
292 /// | ^^^^^^^^^^^^^^ help: wrap the pattern in parentheses: `(Some(_) | None)`
293 /// ```
294 pub fn parse_single(input: ParseStream) -> Result {
295 let begin = input.cursor();
296 let lookahead = input.lookahead1();
297 if lookahead.peek(Ident)
298 && (input.peek2(Token![::])
299 || input.peek2(Token![!])
300 || input.peek2(token::Brace)
301 || input.peek2(token::Paren)
302 || input.peek2(Token![..]))
303 || input.peek(Token![self]) && input.peek2(Token![::])
304 || lookahead.peek(Token![::])
305 || lookahead.peek(Token![<])
306 || input.peek(Token![Self])
307 || input.peek(Token![super])
308 || input.peek(Token![crate])
309 {
310 pat_path_or_macro_or_struct_or_range(input)
311 } else if lookahead.peek(Token![_]) {
312 input.call(pat_wild).map(Pat::Wild)
313 } else if input.peek(Token![box]) {
314 pat_box(begin, input)
315 } else if input.peek(Token![-]) || lookahead.peek(Lit) || lookahead.peek(Token![const])
316 {
317 pat_lit_or_range(input)
318 } else if lookahead.peek(Token![ref])
319 || lookahead.peek(Token![mut])
320 || input.peek(Token![self])
321 || input.peek(Ident)
322 {
323 input.call(pat_ident).map(Pat::Ident)
324 } else if lookahead.peek(Token![&]) {
325 input.call(pat_reference).map(Pat::Reference)
326 } else if lookahead.peek(token::Paren) {
327 input.call(pat_paren_or_tuple)
328 } else if lookahead.peek(token::Bracket) {
329 input.call(pat_slice).map(Pat::Slice)
330 } else if lookahead.peek(Token![..]) && !input.peek(Token![...]) {
331 pat_range_half_open(input)
332 } else if lookahead.peek(Token![const]) {
333 input.call(pat_const).map(Pat::Verbatim)
334 } else {
335 Err(lookahead.error())
336 }
337 }
338
339 /// Parse a pattern, possibly involving `|`, but not a leading `|`.
340 pub fn parse_multi(input: ParseStream) -> Result {
341 let allow_guard = false;
342 multi_pat_impl(input, None, allow_guard)
343 }
344
345 /// Parse a pattern, possibly involving `|`, possibly including a
346 /// leading `|`.
347 ///
348 /// This parser matches the behavior of the Rust 2021 edition's `$:pat`
349 /// macro_rules matcher.
350 ///
351 /// In Rust syntax, an example of where this syntax would occur is in
352 /// the pattern of a `match` arm, where the language permits an optional
353 /// leading `|`, although it is not idiomatic to write one there in
354 /// handwritten code.
355 ///
356 /// ```
357 /// # let wat = None;
358 /// match wat {
359 /// | None | Some(false) => {}
360 /// | Some(true) => {}
361 /// }
362 /// ```
363 ///
364 /// The compiler accepts it only to facilitate some situations in
365 /// macro-generated code where a macro author might need to write:
366 ///
367 /// ```
368 /// # macro_rules! doc {
369 /// # ($value:expr, ($($conditions1:pat),*), ($($conditions2:pat),*), $then:expr) => {
370 /// match $value {
371 /// $(| $conditions1)* $(| $conditions2)* => $then
372 /// }
373 /// # };
374 /// # }
375 /// #
376 /// # doc!(true, (true), (false), {});
377 /// # doc!(true, (), (true, false), {});
378 /// # doc!(true, (true, false), (), {});
379 /// ```
380 ///
381 /// Expressing the same thing correctly in the case that either one (but
382 /// not both) of `$conditions1` and `$conditions2` might be empty,
383 /// without leading `|`, is complex.
384 ///
385 /// Use [`Pat::parse_multi`] instead if you are not intending to support
386 /// macro-generated macro input.
387 pub fn parse_multi_with_leading_vert(input: ParseStream) -> Result {
388 let leading_vert: Option = input.parse()?;
389 let allow_guard = false;
390 multi_pat_impl(input, leading_vert, allow_guard)
391 }
392
393 pub(crate) fn parse_multi_with_leading_vert_and_guard(input: ParseStream) -> Result {
394 let leading_vert: Option = input.parse()?;
395 let allow_guard = true;
396 multi_pat_impl(input, leading_vert, allow_guard)
397 }
398 }
399
400 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
401 impl Parse for PatType {
402 fn parse(input: ParseStream) -> Result {
403 Ok(PatType {
404 attrs: Vec::new(),
405 pat: Box::new(Pat::parse_single(input)?),
406 colon_token: input.parse()?,
407 ty: input.parse()?,
408 })
409 }
410 }
411
412 fn multi_pat_impl(
413 input: ParseStream,
414 leading_vert: Option,
415 allow_guard: bool,
416 ) -> Result {
417 let mut pat = Pat::parse_single(input)?;
418 if leading_vert.is_some()
419 || input.peek(Token![|]) && !input.peek(Token![||]) && !input.peek(Token![|=])
420 {
421 let mut cases = Punctuated::new();
422 cases.push_value(pat);
423 while input.peek(Token![|]) && !input.peek(Token![||]) && !input.peek(Token![|=]) {
424 let punct = input.parse()?;
425 cases.push_punct(punct);
426 let pat = Pat::parse_single(input)?;
427 cases.push_value(pat);
428 }
429 pat = Pat::Or(PatOr {
430 attrs: Vec::new(),
431 leading_vert,
432 cases,
433 });
434 }
435 if allow_guard && input.peek(Token![if]) {
436 let if_token: Token![if] = input.parse()?;
437 let guard: Expr = input.parse()?;
438 pat = Pat::Guard(PatGuard {
439 attrs: Vec::new(),
440 pat: Box::new(pat),
441 if_token,
442 guard: Box::new(guard),
443 });
444 }
445 Ok(pat)
446 }
447
448 fn pat_path_or_macro_or_struct_or_range(input: ParseStream) -> Result {
449 let expr_style = true;
450 let (qself, path) = path::parsing::qpath(input, expr_style)?;
451
452 if qself.is_none()
453 && input.peek(Token![!])
454 && !input.peek(Token![!=])
455 && path.is_mod_style()
456 {
457 let bang_token: Token![!] = input.parse()?;
458 let (delimiter, tokens) = mac::parse_delimiter(input)?;
459 return Ok(Pat::Macro(ExprMacro {
460 attrs: Vec::new(),
461 mac: Macro {
462 path,
463 bang_token,
464 delimiter,
465 tokens,
466 },
467 }));
468 }
469
470 if input.peek(token::Brace) {
471 pat_struct(input, qself, path).map(Pat::Struct)
472 } else if input.peek(token::Paren) {
473 pat_tuple_struct(input, qself, path).map(Pat::TupleStruct)
474 } else if input.peek(Token![..]) {
475 pat_range(input, qself, path)
476 } else {
477 Ok(Pat::Path(ExprPath {
478 attrs: Vec::new(),
479 qself,
480 path,
481 }))
482 }
483 }
484
485 fn pat_wild(input: ParseStream) -> Result {
486 Ok(PatWild {
487 attrs: Vec::new(),
488 underscore_token: input.parse()?,
489 })
490 }
491
492 fn pat_box(begin: Cursor, input: ParseStream) -> Result {
493 input.parse::()?;
494 Pat::parse_single(input)?;
495 Ok(Pat::Verbatim(verbatim::between(begin, input.cursor())))
496 }
497
498 fn pat_ident(input: ParseStream) -> Result {
499 Ok(PatIdent {
500 attrs: Vec::new(),
501 by_ref: input.parse()?,
502 mutability: input.parse()?,
503 ident: {
504 if input.peek(Token![self]) {
505 input.call(Ident::parse_any)?
506 } else {
507 input.parse()?
508 }
509 },
510 subpat: {
511 if input.peek(Token![@]) {
512 let at_token: Token![@] = input.parse()?;
513 let subpat = Pat::parse_single(input)?;
514 Some((at_token, Box::new(subpat)))
515 } else {
516 None
517 }
518 },
519 })
520 }
521
522 fn pat_tuple_struct(
523 input: ParseStream,
524 qself: Option,
525 path: Path,
526 ) -> Result {
527 let content;
528 let paren_token = parenthesized!(content in input);
529
530 let mut elems = Punctuated::new();
531 while !content.is_empty() {
532 let value = Pat::parse_multi_with_leading_vert(&content)?;
533 elems.push_value(value);
534 if content.is_empty() {
535 break;
536 }
537 let punct = content.parse()?;
538 elems.push_punct(punct);
539 }
540
541 Ok(PatTupleStruct {
542 attrs: Vec::new(),
543 qself,
544 path,
545 paren_token,
546 elems,
547 })
548 }
549
550 fn pat_struct(input: ParseStream, qself: Option, path: Path) -> Result {
551 let content;
552 let brace_token = braced!(content in input);
553
554 let mut fields = Punctuated::new();
555 let mut rest = None;
556 while !content.is_empty() {
557 let attrs = content.call(Attribute::parse_outer)?;
558 if content.peek(Token![..]) {
559 rest = Some(PatRest {
560 attrs,
561 dot2_token: content.parse()?,
562 });
563 break;
564 }
565 let mut value = content.call(field_pat)?;
566 value.attrs = attrs;
567 fields.push_value(value);
568 if content.is_empty() {
569 break;
570 }
571 let punct: Token![,] = content.parse()?;
572 fields.push_punct(punct);
573 }
574
575 Ok(PatStruct {
576 attrs: Vec::new(),
577 qself,
578 path,
579 brace_token,
580 fields,
581 rest,
582 })
583 }
584
585 fn field_pat(input: ParseStream) -> Result {
586 let begin = input.cursor();
587 let boxed: Option = input.parse()?;
588 let by_ref: Option = input.parse()?;
589 let mutability: Option = input.parse()?;
590
591 let member = if boxed.is_some() || by_ref.is_some() || mutability.is_some() {
592 input.parse().map(Member::Named)
593 } else {
594 input.parse()
595 }?;
596
597 if boxed.is_none() && by_ref.is_none() && mutability.is_none() && input.peek(Token![:])
598 || !member.is_named()
599 {
600 return Ok(FieldPat {
601 attrs: Vec::new(),
602 member,
603 colon_token: Some(input.parse()?),
604 pat: Box::new(Pat::parse_multi_with_leading_vert(input)?),
605 });
606 }
607
608 let ident = match member {
609 Member::Named(ident) => ident,
610 Member::Unnamed(_) => unreachable!(),
611 };
612
613 let pat = if boxed.is_some() {
614 Pat::Verbatim(verbatim::between(begin, input.cursor()))
615 } else {
616 Pat::Ident(PatIdent {
617 attrs: Vec::new(),
618 by_ref,
619 mutability,
620 ident: ident.clone(),
621 subpat: None,
622 })
623 };
624
625 Ok(FieldPat {
626 attrs: Vec::new(),
627 member: Member::Named(ident),
628 colon_token: None,
629 pat: Box::new(pat),
630 })
631 }
632
633 fn pat_range(input: ParseStream, qself: Option, path: Path) -> Result {
634 let limits = RangeLimits::parse_obsolete(input)?;
635 let end = input.call(pat_range_bound)?;
636 if let (RangeLimits::Closed(_), None) = (&limits, &end) {
637 return Err(input.error("expected range upper bound"));
638 }
639 Ok(Pat::Range(ExprRange {
640 attrs: Vec::new(),
641 start: Some(Box::new(Expr::Path(ExprPath {
642 attrs: Vec::new(),
643 qself,
644 path,
645 }))),
646 limits,
647 end: end.map(PatRangeBound::into_expr),
648 }))
649 }
650
651 fn pat_range_half_open(input: ParseStream) -> Result {
652 let limits: RangeLimits = input.parse()?;
653 let end = input.call(pat_range_bound)?;
654 if end.is_some() {
655 Ok(Pat::Range(ExprRange {
656 attrs: Vec::new(),
657 start: None,
658 limits,
659 end: end.map(PatRangeBound::into_expr),
660 }))
661 } else {
662 match limits {
663 RangeLimits::HalfOpen(dot2_token) => Ok(Pat::Rest(PatRest {
664 attrs: Vec::new(),
665 dot2_token,
666 })),
667 RangeLimits::Closed(_) => Err(input.error("expected range upper bound")),
668 }
669 }
670 }
671
672 fn pat_paren_or_tuple(input: ParseStream) -> Result {
673 let content;
674 let paren_token = parenthesized!(content in input);
675
676 let mut elems = Punctuated::new();
677 while !content.is_empty() {
678 let value = Pat::parse_multi_with_leading_vert(&content)?;
679 if content.is_empty() {
680 if elems.is_empty() && !matches!(value, Pat::Rest(_)) {
681 return Ok(Pat::Paren(PatParen {
682 attrs: Vec::new(),
683 paren_token,
684 pat: Box::new(value),
685 }));
686 }
687 elems.push_value(value);
688 break;
689 }
690 elems.push_value(value);
691 let punct = content.parse()?;
692 elems.push_punct(punct);
693 }
694
695 Ok(Pat::Tuple(PatTuple {
696 attrs: Vec::new(),
697 paren_token,
698 elems,
699 }))
700 }
701
702 fn pat_reference(input: ParseStream) -> Result {
703 Ok(PatReference {
704 attrs: Vec::new(),
705 and_token: input.parse()?,
706 mutability: input.parse()?,
707 pat: Box::new(Pat::parse_single(input)?),
708 })
709 }
710
711 fn pat_lit_or_range(input: ParseStream) -> Result {
712 let start = input.call(pat_range_bound)?.unwrap();
713 if input.peek(Token![..]) {
714 let limits = RangeLimits::parse_obsolete(input)?;
715 let end = input.call(pat_range_bound)?;
716 if let (RangeLimits::Closed(_), None) = (&limits, &end) {
717 return Err(input.error("expected range upper bound"));
718 }
719 Ok(Pat::Range(ExprRange {
720 attrs: Vec::new(),
721 start: Some(start.into_expr()),
722 limits,
723 end: end.map(PatRangeBound::into_expr),
724 }))
725 } else {
726 Ok(start.into_pat())
727 }
728 }
729
730 // Patterns that can appear on either side of a range pattern.
731 enum PatRangeBound {
732 Const(ExprConst),
733 Lit(ExprLit),
734 Path(ExprPath),
735 }
736
737 impl PatRangeBound {
738 fn into_expr(self) -> Box {
739 Box::new(match self {
740 PatRangeBound::Const(pat) => Expr::Const(pat),
741 PatRangeBound::Lit(pat) => Expr::Lit(pat),
742 PatRangeBound::Path(pat) => Expr::Path(pat),
743 })
744 }
745
746 fn into_pat(self) -> Pat {
747 match self {
748 PatRangeBound::Const(pat) => Pat::Const(pat),
749 PatRangeBound::Lit(pat) => Pat::Lit(pat),
750 PatRangeBound::Path(pat) => Pat::Path(pat),
751 }
752 }
753 }
754
755 fn pat_range_bound(input: ParseStream) -> Result