Skip to main content

syn/
pat.rs

1use crate::attr::Attribute;
2use crate::expr::{Expr, Member};
3use crate::ident::Ident;
4use crate::path::{Path, QSelf};
5use crate::punctuated::Punctuated;
6use crate::token;
7use crate::ty::Type;
8use alloc::boxed::Box;
9use alloc::vec::Vec;
10use proc_macro2::TokenStream;
11
12pub use crate::expr::{
13    ExprConst as PatConst, ExprLit as PatLit, ExprMacro as PatMacro, ExprPath as PatPath,
14    ExprRange as PatRange,
15};
16
17ast_enum_of_structs! {
18    /// A pattern in a local binding, function signature, match expression, or
19    /// various other places.
20    ///
21    /// # Syntax tree enum
22    ///
23    /// This type is a [syntax tree enum].
24    ///
25    /// [syntax tree enum]: crate::expr::Expr#syntax-tree-enums
26    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
27    #[non_exhaustive]
28    pub enum Pat {
29        /// A const block: `const { ... }`.
30        Const(PatConst),
31
32        /// A pattern with guard predicate: `Some(x) if x > 0`.
33        Guard(PatGuard),
34
35        /// A pattern that binds a new variable: `ref mut binding @ SUBPATTERN`.
36        Ident(PatIdent),
37
38        /// A literal pattern: `0`.
39        Lit(PatLit),
40
41        /// A macro in pattern position.
42        Macro(PatMacro),
43
44        /// A pattern that matches any one of a set of cases.
45        Or(PatOr),
46
47        /// A parenthesized pattern: `(A | B)`.
48        Paren(PatParen),
49
50        /// A path pattern like `Color::Red`, optionally qualified with a
51        /// self-type.
52        ///
53        /// Unqualified path patterns can legally refer to variants, structs,
54        /// constants or associated constants. Qualified path patterns like
55        /// `<A>::B::C` and `<A as Trait>::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        Verbatim(TokenStream),
85
86        /// A pattern that matches any value: `_`.
87        Wild(PatWild),
88
89        // For testing exhaustiveness in downstream code, use the following idiom:
90        //
91        //     match pat {
92        //         #![cfg_attr(test, deny(non_exhaustive_omitted_patterns))]
93        //
94        //         Pat::Box(pat) => {...}
95        //         Pat::Ident(pat) => {...}
96        //         ...
97        //         Pat::Wild(pat) => {...}
98        //
99        //         _ => { /* some sane fallback */ }
100        //     }
101        //
102        // This way we fail your tests but don't break your library when adding
103        // a variant. You will be notified by a test failure when a variant is
104        // added, so that you can add code to handle it, but your library will
105        // continue to compile and work for downstream users in the interim.
106    }
107}
108
109ast_struct! {
110    /// A pattern that binds a new variable: `ref mut binding @ SUBPATTERN`.
111    ///
112    /// It may also be a unit struct or struct variant (e.g. `None`), or a
113    /// constant; these cannot be distinguished syntactically.
114    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
115    pub struct PatIdent {
116        pub attrs: Vec<Attribute>,
117        pub by_ref: Option<Token![ref]>,
118        pub mutability: Option<Token![mut]>,
119        pub ident: Ident,
120        pub subpat: Option<(Token![@], Box<Pat>)>,
121    }
122}
123
124ast_struct! {
125    /// A pattern with guard predicate: `Some(x) if x > 0`.
126    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
127    pub struct PatGuard {
128        pub attrs: Vec<Attribute>,
129        pub pat: Box<Pat>,
130        pub if_token: Token![if],
131        pub guard: Box<Expr>,
132    }
133}
134
135ast_struct! {
136    /// A pattern that matches any one of a set of cases.
137    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
138    pub struct PatOr {
139        pub attrs: Vec<Attribute>,
140        pub leading_vert: Option<Token![|]>,
141        pub cases: Punctuated<Pat, Token![|]>,
142    }
143}
144
145ast_struct! {
146    /// A parenthesized pattern: `(A | B)`.
147    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
148    pub struct PatParen {
149        pub attrs: Vec<Attribute>,
150        pub paren_token: token::Paren,
151        pub pat: Box<Pat>,
152    }
153}
154
155ast_struct! {
156    /// A reference pattern: `&mut var`.
157    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
158    pub struct PatReference {
159        pub attrs: Vec<Attribute>,
160        pub and_token: Token![&],
161        pub mutability: Option<Token![mut]>,
162        pub pat: Box<Pat>,
163    }
164}
165
166ast_struct! {
167    /// The dots in a tuple or slice pattern: `[0, 1, ..]`.
168    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
169    pub struct PatRest {
170        pub attrs: Vec<Attribute>,
171        pub dot2_token: Token![..],
172    }
173}
174
175ast_struct! {
176    /// A dynamically sized slice pattern: `[a, b, ref i @ .., y, z]`.
177    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
178    pub struct PatSlice {
179        pub attrs: Vec<Attribute>,
180        pub bracket_token: token::Bracket,
181        pub elems: Punctuated<Pat, Token![,]>,
182    }
183}
184
185ast_struct! {
186    /// A struct or struct variant pattern: `Variant { x, y, .. }`.
187    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
188    pub struct PatStruct {
189        pub attrs: Vec<Attribute>,
190        pub qself: Option<QSelf>,
191        pub path: Path,
192        pub brace_token: token::Brace,
193        pub fields: Punctuated<FieldPat, Token![,]>,
194        pub rest: Option<PatRest>,
195    }
196}
197
198ast_struct! {
199    /// A tuple pattern: `(a, b)`.
200    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
201    pub struct PatTuple {
202        pub attrs: Vec<Attribute>,
203        pub paren_token: token::Paren,
204        pub elems: Punctuated<Pat, Token![,]>,
205    }
206}
207
208ast_struct! {
209    /// A tuple struct or tuple variant pattern: `Variant(x, y, .., z)`.
210    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
211    pub struct PatTupleStruct {
212        pub attrs: Vec<Attribute>,
213        pub qself: Option<QSelf>,
214        pub path: Path,
215        pub paren_token: token::Paren,
216        pub elems: Punctuated<Pat, Token![,]>,
217    }
218}
219
220ast_struct! {
221    /// A type ascription pattern: `foo: f64`.
222    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
223    pub struct PatType {
224        pub attrs: Vec<Attribute>,
225        pub pat: Box<Pat>,
226        pub colon_token: Token![:],
227        pub ty: Box<Type>,
228    }
229}
230
231ast_struct! {
232    /// A pattern that matches any value: `_`.
233    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
234    pub struct PatWild {
235        pub attrs: Vec<Attribute>,
236        pub underscore_token: Token![_],
237    }
238}
239
240ast_struct! {
241    /// A single field in a struct pattern.
242    ///
243    /// Patterns like the fields of `Pat { x, ref y, ref mut z }` are treated
244    /// the same as `x: x, y: ref y, z: ref mut z` but there is no colon token.
245    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
246    pub struct FieldPat {
247        pub attrs: Vec<Attribute>,
248        pub member: Member,
249        pub colon_token: Option<Token![:]>,
250        pub pat: Box<Pat>,
251    }
252}
253
254#[cfg(feature = "parsing")]
255pub(crate) mod parsing {
256    use crate::attr::Attribute;
257    use crate::buffer::Cursor;
258    use crate::error::{self, Result};
259    use crate::expr::{
260        Expr, ExprConst, ExprLit, ExprMacro, ExprPath, ExprRange, Member, RangeLimits,
261    };
262    use crate::ext::IdentExt as _;
263    use crate::ident::Ident;
264    use crate::lit::Lit;
265    use crate::mac::{self, Macro};
266    use crate::parse::{Parse, ParseStream};
267    use crate::pat::{
268        FieldPat, Pat, PatGuard, PatIdent, PatOr, PatParen, PatReference, PatRest, PatSlice,
269        PatStruct, PatTuple, PatTupleStruct, PatType, PatWild,
270    };
271    use crate::path::{self, Path, QSelf};
272    use crate::punctuated::Punctuated;
273    use crate::stmt::Block;
274    use crate::token;
275    use crate::verbatim;
276    use alloc::boxed::Box;
277    use alloc::vec::Vec;
278    use proc_macro2::TokenStream;
279
280    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
281    impl Pat {
282        /// Parse a pattern that does _not_ involve `|` at the top level.
283        ///
284        /// This parser matches the behavior of the `$:pat_param` macro_rules
285        /// matcher, and on editions prior to Rust 2021, the behavior of
286        /// `$:pat`.
287        ///
288        /// In Rust syntax, some examples of where this syntax would occur are
289        /// in the argument pattern of functions and closures. Patterns using
290        /// `|` are not allowed to occur in these positions.
291        ///
292        /// ```compile_fail
293        /// fn f(Some(_) | None: Option<T>) {
294        ///     let _ = |Some(_) | None: Option<T>| {};
295        ///     //       ^^^^^^^^^^^^^^^^^^^^^^^^^??? :(
296        /// }
297        /// ```
298        ///
299        /// ```console
300        /// error: top-level or-patterns are not allowed in function parameters
301        ///  --> src/main.rs:1:6
302        ///   |
303        /// 1 | fn f(Some(_) | None: Option<T>) {
304        ///   |      ^^^^^^^^^^^^^^ help: wrap the pattern in parentheses: `(Some(_) | None)`
305        /// ```
306        pub fn parse_single(input: ParseStream) -> Result<Self> {
307            let begin = input.cursor();
308            let lookahead = input.lookahead1();
309            if lookahead.peek(Ident)
310                && (input.peek2(Token![::])
311                    || input.peek2(Token![!])
312                    || input.peek2(token::Brace)
313                    || input.peek2(token::Paren)
314                    || input.peek2(Token![..]))
315                || input.peek(Token![self]) && input.peek2(Token![::])
316                || lookahead.peek(Token![::])
317                || lookahead.peek(Token![<])
318                || input.peek(Token![Self])
319                || input.peek(Token![super])
320                || input.peek(Token![crate])
321            {
322                pat_path_or_macro_or_struct_or_range(input)
323            } else if lookahead.peek(Token![_]) {
324                input.call(pat_wild).map(Pat::Wild)
325            } else if input.peek(Token![box]) {
326                pat_box(begin, input)
327            } else if input.peek(Token![-]) || lookahead.peek(Lit) || lookahead.peek(Token![const])
328            {
329                pat_lit_or_range(input)
330            } else if lookahead.peek(Token![ref])
331                || lookahead.peek(Token![mut])
332                || input.peek(Token![self])
333                || input.peek(Ident)
334            {
335                input.call(pat_ident).map(Pat::Ident)
336            } else if lookahead.peek(Token![&]) {
337                input.call(pat_reference).map(Pat::Reference)
338            } else if lookahead.peek(token::Paren) {
339                input.call(pat_paren_or_tuple)
340            } else if lookahead.peek(token::Bracket) {
341                input.call(pat_slice).map(Pat::Slice)
342            } else if lookahead.peek(Token![..]) && !input.peek(Token![...]) {
343                pat_range_half_open(input)
344            } else if lookahead.peek(Token![const]) {
345                input.call(pat_const).map(Pat::Verbatim)
346            } else {
347                Err(lookahead.error())
348            }
349        }
350
351        /// Parse a pattern, possibly involving `|`, but not a leading `|`.
352        pub fn parse_multi(input: ParseStream) -> Result<Self> {
353            let allow_guard = false;
354            multi_pat_impl(input, None, allow_guard)
355        }
356
357        /// Parse a pattern, possibly involving `|`, possibly including a
358        /// leading `|`.
359        ///
360        /// This parser matches the behavior of the Rust 2021 edition's `$:pat`
361        /// macro_rules matcher.
362        ///
363        /// In Rust syntax, an example of where this syntax would occur is in
364        /// the pattern of a `match` arm, where the language permits an optional
365        /// leading `|`, although it is not idiomatic to write one there in
366        /// handwritten code.
367        ///
368        /// ```
369        /// # let wat = None;
370        /// match wat {
371        ///     | None | Some(false) => {}
372        ///     | Some(true) => {}
373        /// }
374        /// ```
375        ///
376        /// The compiler accepts it only to facilitate some situations in
377        /// macro-generated code where a macro author might need to write:
378        ///
379        /// ```
380        /// # macro_rules! doc {
381        /// #     ($value:expr, ($($conditions1:pat),*), ($($conditions2:pat),*), $then:expr) => {
382        /// match $value {
383        ///     $(| $conditions1)* $(| $conditions2)* => $then
384        /// }
385        /// #     };
386        /// # }
387        /// #
388        /// # doc!(true, (true), (false), {});
389        /// # doc!(true, (), (true, false), {});
390        /// # doc!(true, (true, false), (), {});
391        /// ```
392        ///
393        /// Expressing the same thing correctly in the case that either one (but
394        /// not both) of `$conditions1` and `$conditions2` might be empty,
395        /// without leading `|`, is complex.
396        ///
397        /// Use [`Pat::parse_multi`] instead if you are not intending to support
398        /// macro-generated macro input.
399        pub fn parse_multi_with_leading_vert(input: ParseStream) -> Result<Self> {
400            let leading_vert: Option<Token![|]> = input.parse()?;
401            let allow_guard = false;
402            multi_pat_impl(input, leading_vert, allow_guard)
403        }
404
405        pub(crate) fn parse_multi_with_leading_vert_and_guard(input: ParseStream) -> Result<Self> {
406            let leading_vert: Option<Token![|]> = input.parse()?;
407            let allow_guard = true;
408            multi_pat_impl(input, leading_vert, allow_guard)
409        }
410    }
411
412    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
413    impl Parse for PatType {
414        fn parse(input: ParseStream) -> Result<Self> {
415            Ok(PatType {
416                attrs: Vec::new(),
417                pat: Box::new(Pat::parse_single(input)?),
418                colon_token: input.parse()?,
419                ty: input.parse()?,
420            })
421        }
422    }
423
424    fn multi_pat_impl(
425        input: ParseStream,
426        leading_vert: Option<Token![|]>,
427        allow_guard: bool,
428    ) -> Result<Pat> {
429        let mut pat = Pat::parse_single(input)?;
430        if leading_vert.is_some()
431            || input.peek(Token![|]) && !input.peek(Token![||]) && !input.peek(Token![|=])
432        {
433            let mut cases = Punctuated::new();
434            cases.push_value(pat);
435            while input.peek(Token![|]) && !input.peek(Token![||]) && !input.peek(Token![|=]) {
436                let punct = input.parse()?;
437                cases.push_punct(punct);
438                let pat = Pat::parse_single(input)?;
439                cases.push_value(pat);
440            }
441            pat = Pat::Or(PatOr {
442                attrs: Vec::new(),
443                leading_vert,
444                cases,
445            });
446        }
447        if allow_guard && input.peek(Token![if]) {
448            let if_token: Token![if] = input.parse()?;
449            let guard: Expr = input.parse()?;
450            pat = Pat::Guard(PatGuard {
451                attrs: Vec::new(),
452                pat: Box::new(pat),
453                if_token,
454                guard: Box::new(guard),
455            });
456        }
457        Ok(pat)
458    }
459
460    fn pat_path_or_macro_or_struct_or_range(input: ParseStream) -> Result<Pat> {
461        let expr_style = true;
462        let (qself, path) = path::parsing::qpath(input, expr_style)?;
463
464        if qself.is_none()
465            && input.peek(Token![!])
466            && !input.peek(Token![!=])
467            && path.is_mod_style()
468        {
469            let bang_token: Token![!] = input.parse()?;
470            let (delimiter, tokens) = mac::parse_delimiter(input)?;
471            return Ok(Pat::Macro(ExprMacro {
472                attrs: Vec::new(),
473                mac: Macro {
474                    path,
475                    bang_token,
476                    delimiter,
477                    tokens,
478                },
479            }));
480        }
481
482        if input.peek(token::Brace) {
483            pat_struct(input, qself, path).map(Pat::Struct)
484        } else if input.peek(token::Paren) {
485            pat_tuple_struct(input, qself, path).map(Pat::TupleStruct)
486        } else if input.peek(Token![..]) {
487            pat_range(input, qself, path)
488        } else {
489            Ok(Pat::Path(ExprPath {
490                attrs: Vec::new(),
491                qself,
492                path,
493            }))
494        }
495    }
496
497    fn pat_wild(input: ParseStream) -> Result<PatWild> {
498        Ok(PatWild {
499            attrs: Vec::new(),
500            underscore_token: input.parse()?,
501        })
502    }
503
504    fn pat_box(begin: Cursor, input: ParseStream) -> Result<Pat> {
505        input.parse::<Token![box]>()?;
506        Pat::parse_single(input)?;
507        Ok(Pat::Verbatim(verbatim::between(begin, input.cursor())))
508    }
509
510    fn pat_ident(input: ParseStream) -> Result<PatIdent> {
511        Ok(PatIdent {
512            attrs: Vec::new(),
513            by_ref: input.parse()?,
514            mutability: input.parse()?,
515            ident: {
516                if input.peek(Token![self]) {
517                    input.call(Ident::parse_any)?
518                } else {
519                    input.parse()?
520                }
521            },
522            subpat: {
523                if input.peek(Token![@]) {
524                    let at_token: Token![@] = input.parse()?;
525                    let subpat = Pat::parse_single(input)?;
526                    Some((at_token, Box::new(subpat)))
527                } else {
528                    None
529                }
530            },
531        })
532    }
533
534    fn pat_tuple_struct(
535        input: ParseStream,
536        qself: Option<QSelf>,
537        path: Path,
538    ) -> Result<PatTupleStruct> {
539        let content;
540        let paren_token = parenthesized!(content in input);
541
542        let mut elems = Punctuated::new();
543        while !content.is_empty() {
544            let value = Pat::parse_multi_with_leading_vert(&content)?;
545            elems.push_value(value);
546            if content.is_empty() {
547                break;
548            }
549            let punct = content.parse()?;
550            elems.push_punct(punct);
551        }
552
553        Ok(PatTupleStruct {
554            attrs: Vec::new(),
555            qself,
556            path,
557            paren_token,
558            elems,
559        })
560    }
561
562    fn pat_struct(input: ParseStream, qself: Option<QSelf>, path: Path) -> Result<PatStruct> {
563        let content;
564        let brace_token = braced!(content in input);
565
566        let mut fields = Punctuated::new();
567        let mut rest = None;
568        while !content.is_empty() {
569            let attrs = content.call(Attribute::parse_outer)?;
570            if content.peek(Token![..]) {
571                rest = Some(PatRest {
572                    attrs,
573                    dot2_token: content.parse()?,
574                });
575                break;
576            }
577            let mut value = content.call(field_pat)?;
578            value.attrs = attrs;
579            fields.push_value(value);
580            if content.is_empty() {
581                break;
582            }
583            let punct: Token![,] = content.parse()?;
584            fields.push_punct(punct);
585        }
586
587        Ok(PatStruct {
588            attrs: Vec::new(),
589            qself,
590            path,
591            brace_token,
592            fields,
593            rest,
594        })
595    }
596
597    fn field_pat(input: ParseStream) -> Result<FieldPat> {
598        let begin = input.cursor();
599        let boxed: Option<Token![box]> = input.parse()?;
600        let by_ref: Option<Token![ref]> = input.parse()?;
601        let mutability: Option<Token![mut]> = input.parse()?;
602
603        let member = if boxed.is_some() || by_ref.is_some() || mutability.is_some() {
604            input.parse().map(Member::Named)
605        } else {
606            input.parse()
607        }?;
608
609        if boxed.is_none() && by_ref.is_none() && mutability.is_none() && input.peek(Token![:])
610            || !member.is_named()
611        {
612            return Ok(FieldPat {
613                attrs: Vec::new(),
614                member,
615                colon_token: Some(input.parse()?),
616                pat: Box::new(Pat::parse_multi_with_leading_vert(input)?),
617            });
618        }
619
620        let ident = match member {
621            Member::Named(ident) => ident,
622            Member::Unnamed(_) => unreachable!(),
623        };
624
625        let pat = if boxed.is_some() {
626            Pat::Verbatim(verbatim::between(begin, input.cursor()))
627        } else {
628            Pat::Ident(PatIdent {
629                attrs: Vec::new(),
630                by_ref,
631                mutability,
632                ident: ident.clone(),
633                subpat: None,
634            })
635        };
636
637        Ok(FieldPat {
638            attrs: Vec::new(),
639            member: Member::Named(ident),
640            colon_token: None,
641            pat: Box::new(pat),
642        })
643    }
644
645    fn pat_range(input: ParseStream, qself: Option<QSelf>, path: Path) -> Result<Pat> {
646        let limits = RangeLimits::parse_obsolete(input)?;
647        let end = input.call(pat_range_bound)?;
648        if let (RangeLimits::Closed(_), None) = (&limits, &end) {
649            return Err(input.error("expected range upper bound"));
650        }
651        Ok(Pat::Range(ExprRange {
652            attrs: Vec::new(),
653            start: Some(Box::new(Expr::Path(ExprPath {
654                attrs: Vec::new(),
655                qself,
656                path,
657            }))),
658            limits,
659            end: end.map(PatRangeBound::into_expr),
660        }))
661    }
662
663    fn pat_range_half_open(input: ParseStream) -> Result<Pat> {
664        let limits: RangeLimits = input.parse()?;
665        let end = input.call(pat_range_bound)?;
666        if end.is_some() {
667            Ok(Pat::Range(ExprRange {
668                attrs: Vec::new(),
669                start: None,
670                limits,
671                end: end.map(PatRangeBound::into_expr),
672            }))
673        } else {
674            match limits {
675                RangeLimits::HalfOpen(dot2_token) => Ok(Pat::Rest(PatRest {
676                    attrs: Vec::new(),
677                    dot2_token,
678                })),
679                RangeLimits::Closed(_) => Err(input.error("expected range upper bound")),
680            }
681        }
682    }
683
684    fn pat_paren_or_tuple(input: ParseStream) -> Result<Pat> {
685        let content;
686        let paren_token = parenthesized!(content in input);
687
688        let mut elems = Punctuated::new();
689        while !content.is_empty() {
690            let value = Pat::parse_multi_with_leading_vert(&content)?;
691            if content.is_empty() {
692                if elems.is_empty() && !matches!(value, Pat::Rest(_)) {
693                    return Ok(Pat::Paren(PatParen {
694                        attrs: Vec::new(),
695                        paren_token,
696                        pat: Box::new(value),
697                    }));
698                }
699                elems.push_value(value);
700                break;
701            }
702            elems.push_value(value);
703            let punct = content.parse()?;
704            elems.push_punct(punct);
705        }
706
707        Ok(Pat::Tuple(PatTuple {
708            attrs: Vec::new(),
709            paren_token,
710            elems,
711        }))
712    }
713
714    fn pat_reference(input: ParseStream) -> Result<PatReference> {
715        Ok(PatReference {
716            attrs: Vec::new(),
717            and_token: input.parse()?,
718            mutability: input.parse()?,
719            pat: Box::new(Pat::parse_single(input)?),
720        })
721    }
722
723    fn pat_lit_or_range(input: ParseStream) -> Result<Pat> {
724        let start = input.call(pat_range_bound)?.unwrap();
725        if input.peek(Token![..]) {
726            let limits = RangeLimits::parse_obsolete(input)?;
727            let end = input.call(pat_range_bound)?;
728            if let (RangeLimits::Closed(_), None) = (&limits, &end) {
729                return Err(input.error("expected range upper bound"));
730            }
731            Ok(Pat::Range(ExprRange {
732                attrs: Vec::new(),
733                start: Some(start.into_expr()),
734                limits,
735                end: end.map(PatRangeBound::into_expr),
736            }))
737        } else {
738            Ok(start.into_pat())
739        }
740    }
741
742    // Patterns that can appear on either side of a range pattern.
743    enum PatRangeBound {
744        Const(ExprConst),
745        Lit(ExprLit),
746        Path(ExprPath),
747    }
748
749    impl PatRangeBound {
750        fn into_expr(self) -> Box<Expr> {
751            Box::new(match self {
752                PatRangeBound::Const(pat) => Expr::Const(pat),
753                PatRangeBound::Lit(pat) => Expr::Lit(pat),
754                PatRangeBound::Path(pat) => Expr::Path(pat),
755            })
756        }
757
758        fn into_pat(self) -> Pat {
759            match self {
760                PatRangeBound::Const(pat) => Pat::Const(pat),
761                PatRangeBound::Lit(pat) => Pat::Lit(pat),
762                PatRangeBound::Path(pat) => Pat::Path(pat),
763            }
764        }
765    }
766
767    fn pat_range_bound(input: ParseStream) -> Result<Option<PatRangeBound>> {
768        if input.is_empty()
769            || input.peek(Token![|])
770            || input.peek(Token![=])
771            || input.peek(Token![:]) && !input.peek(Token![::])
772            || input.peek(Token![,])
773            || input.peek(Token![;])
774            || input.peek(Token![if])
775        {
776            return Ok(None);
777        }
778
779        let lookahead = input.lookahead1();
780        let expr = if lookahead.peek(Lit) {
781            PatRangeBound::Lit(input.parse()?)
782        } else if lookahead.peek(Ident)
783            || lookahead.peek(Token![::])
784            || lookahead.peek(Token![<])
785            || lookahead.peek(Token![self])
786            || lookahead.peek(Token![Self])
787            || lookahead.peek(Token![super])
788            || lookahead.peek(Token![crate])
789        {
790            PatRangeBound::Path(input.parse()?)
791        } else if lookahead.peek(Token![const]) {
792            PatRangeBound::Const(input.parse()?)
793        } else {
794            return Err(lookahead.error());
795        };
796
797        Ok(Some(expr))
798    }
799
800    fn pat_slice(input: ParseStream) -> Result<PatSlice> {
801        let content;
802        let bracket_token = bracketed!(content in input);
803
804        let mut elems = Punctuated::new();
805        while !content.is_empty() {
806            let value = Pat::parse_multi_with_leading_vert(&content)?;
807            match value {
808                Pat::Range(pat) if pat.start.is_none() || pat.end.is_none() => {
809                    let (start, end) = match pat.limits {
810                        RangeLimits::HalfOpen(dot_dot) => (dot_dot.spans[0], dot_dot.spans[1]),
811                        RangeLimits::Closed(dot_dot_eq) => {
812                            (dot_dot_eq.spans[0], dot_dot_eq.spans[2])
813                        }
814                    };
815                    let msg = "range pattern is not allowed unparenthesized inside slice pattern";
816                    return Err(error::new2(start, end, msg));
817                }
818                _ => {}
819            }
820            elems.push_value(value);
821            if content.is_empty() {
822                break;
823            }
824            let punct = content.parse()?;
825            elems.push_punct(punct);
826        }
827
828        Ok(PatSlice {
829            attrs: Vec::new(),
830            bracket_token,
831            elems,
832        })
833    }
834
835    fn pat_const(input: ParseStream) -> Result<TokenStream> {
836        let begin = input.cursor();
837        input.parse::<Token![const]>()?;
838
839        let content;
840        braced!(content in input);
841        content.call(Attribute::parse_inner)?;
842        content.call(Block::parse_within)?;
843
844        Ok(verbatim::between(begin, input.cursor()))
845    }
846}
847
848#[cfg(feature = "printing")]
849mod printing {
850    use crate::attr::FilterAttrs;
851    use crate::pat::{
852        FieldPat, Pat, PatGuard, PatIdent, PatOr, PatParen, PatReference, PatRest, PatSlice,
853        PatStruct, PatTuple, PatTupleStruct, PatType, PatWild,
854    };
855    use crate::path;
856    use crate::path::printing::PathStyle;
857    use proc_macro2::TokenStream;
858    use quote::{ToTokens, TokenStreamExt as _};
859
860    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
861    impl ToTokens for PatIdent {
862        fn to_tokens(&self, tokens: &mut TokenStream) {
863            tokens.append_all(self.attrs.outer());
864            self.by_ref.to_tokens(tokens);
865            self.mutability.to_tokens(tokens);
866            self.ident.to_tokens(tokens);
867            if let Some((at_token, subpat)) = &self.subpat {
868                at_token.to_tokens(tokens);
869                subpat.to_tokens(tokens);
870            }
871        }
872    }
873
874    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
875    impl ToTokens for PatGuard {
876        fn to_tokens(&self, tokens: &mut TokenStream) {
877            tokens.append_all(self.attrs.outer());
878            self.pat.to_tokens(tokens);
879            self.if_token.to_tokens(tokens);
880            self.guard.to_tokens(tokens);
881        }
882    }
883
884    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
885    impl ToTokens for PatOr {
886        fn to_tokens(&self, tokens: &mut TokenStream) {
887            tokens.append_all(self.attrs.outer());
888            self.leading_vert.to_tokens(tokens);
889            self.cases.to_tokens(tokens);
890        }
891    }
892
893    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
894    impl ToTokens for PatParen {
895        fn to_tokens(&self, tokens: &mut TokenStream) {
896            tokens.append_all(self.attrs.outer());
897            self.paren_token.surround(tokens, |tokens| {
898                self.pat.to_tokens(tokens);
899            });
900        }
901    }
902
903    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
904    impl ToTokens for PatReference {
905        fn to_tokens(&self, tokens: &mut TokenStream) {
906            tokens.append_all(self.attrs.outer());
907            self.and_token.to_tokens(tokens);
908            self.mutability.to_tokens(tokens);
909            self.pat.to_tokens(tokens);
910        }
911    }
912
913    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
914    impl ToTokens for PatRest {
915        fn to_tokens(&self, tokens: &mut TokenStream) {
916            tokens.append_all(self.attrs.outer());
917            self.dot2_token.to_tokens(tokens);
918        }
919    }
920
921    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
922    impl ToTokens for PatSlice {
923        fn to_tokens(&self, tokens: &mut TokenStream) {
924            tokens.append_all(self.attrs.outer());
925            self.bracket_token.surround(tokens, |tokens| {
926                self.elems.to_tokens(tokens);
927            });
928        }
929    }
930
931    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
932    impl ToTokens for PatStruct {
933        fn to_tokens(&self, tokens: &mut TokenStream) {
934            tokens.append_all(self.attrs.outer());
935            path::printing::print_qpath(tokens, &self.qself, &self.path, PathStyle::Expr);
936            self.brace_token.surround(tokens, |tokens| {
937                self.fields.to_tokens(tokens);
938                // NOTE: We need a comma before the dot2 token if it is present.
939                if !self.fields.empty_or_trailing() && self.rest.is_some() {
940                    <Token![,]>::default().to_tokens(tokens);
941                }
942                self.rest.to_tokens(tokens);
943            });
944        }
945    }
946
947    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
948    impl ToTokens for PatTuple {
949        fn to_tokens(&self, tokens: &mut TokenStream) {
950            tokens.append_all(self.attrs.outer());
951            self.paren_token.surround(tokens, |tokens| {
952                self.elems.to_tokens(tokens);
953                // If there is only one element, a trailing comma is needed to
954                // distinguish PatTuple from PatParen, unless this is `(..)`
955                // which is a tuple pattern even without comma.
956                if self.elems.len() == 1
957                    && !self.elems.trailing_punct()
958                    && !matches!(self.elems[0], Pat::Rest { .. })
959                {
960                    <Token![,]>::default().to_tokens(tokens);
961                }
962            });
963        }
964    }
965
966    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
967    impl ToTokens for PatTupleStruct {
968        fn to_tokens(&self, tokens: &mut TokenStream) {
969            tokens.append_all(self.attrs.outer());
970            path::printing::print_qpath(tokens, &self.qself, &self.path, PathStyle::Expr);
971            self.paren_token.surround(tokens, |tokens| {
972                self.elems.to_tokens(tokens);
973            });
974        }
975    }
976
977    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
978    impl ToTokens for PatType {
979        fn to_tokens(&self, tokens: &mut TokenStream) {
980            tokens.append_all(self.attrs.outer());
981            self.pat.to_tokens(tokens);
982            self.colon_token.to_tokens(tokens);
983            self.ty.to_tokens(tokens);
984        }
985    }
986
987    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
988    impl ToTokens for PatWild {
989        fn to_tokens(&self, tokens: &mut TokenStream) {
990            tokens.append_all(self.attrs.outer());
991            self.underscore_token.to_tokens(tokens);
992        }
993    }
994
995    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
996    impl ToTokens for FieldPat {
997        fn to_tokens(&self, tokens: &mut TokenStream) {
998            tokens.append_all(self.attrs.outer());
999            if let Some(colon_token) = &self.colon_token {
1000                self.member.to_tokens(tokens);
1001                colon_token.to_tokens(tokens);
1002            }
1003            self.pat.to_tokens(tokens);
1004        }
1005    }
1006}