Skip to main content

syn/
expr.rs

1use crate::attr::Attribute;
2#[cfg(all(feature = "parsing", feature = "full"))]
3use crate::error::Result;
4#[cfg(feature = "parsing")]
5use crate::ext::IdentExt as _;
6#[cfg(feature = "full")]
7use crate::generics::BoundLifetimes;
8use crate::ident::Ident;
9#[cfg(any(feature = "parsing", feature = "full"))]
10use crate::lifetime::Lifetime;
11use crate::lit::Lit;
12use crate::mac::Macro;
13use crate::op::{BinOp, UnOp};
14#[cfg(feature = "parsing")]
15use crate::parse::ParseStream;
16#[cfg(feature = "full")]
17use crate::pat::Pat;
18use crate::path::{AngleBracketedGenericArguments, Path, QSelf};
19use crate::punctuated::Punctuated;
20#[cfg(feature = "full")]
21use crate::stmt::Block;
22use crate::token;
23use crate::ty::Type;
24#[cfg(feature = "full")]
25use crate::ty::{PointerMutability, ReturnType};
26use alloc::boxed::Box;
27use alloc::vec::Vec;
28#[cfg(feature = "printing")]
29use core::fmt::{self, Display};
30use core::hash::{Hash, Hasher};
31#[cfg(all(feature = "parsing", feature = "full"))]
32use core::mem;
33use proc_macro2::{Span, TokenStream};
34#[cfg(feature = "printing")]
35use quote::IdentFragment;
36
37ast_enum_of_structs! {
38    /// A Rust expression.
39    ///
40    /// *This type is available only if Syn is built with the `"derive"` or `"full"`
41    /// feature, but most of the variants are not available unless "full" is enabled.*
42    ///
43    /// # Syntax tree enums
44    ///
45    /// This type is a syntax tree enum. In Syn this and other syntax tree enums
46    /// are designed to be traversed using the following rebinding idiom.
47    ///
48    /// ```
49    /// # use syn::Expr;
50    /// #
51    /// # fn example(expr: Expr) {
52    /// # const IGNORE: &str = stringify! {
53    /// let expr: Expr = /* ... */;
54    /// # };
55    /// match expr {
56    ///     Expr::MethodCall(expr) => {
57    ///         /* ... */
58    ///     }
59    ///     Expr::Cast(expr) => {
60    ///         /* ... */
61    ///     }
62    ///     Expr::If(expr) => {
63    ///         /* ... */
64    ///     }
65    ///
66    ///     /* ... */
67    ///     # _ => {}
68    /// # }
69    /// # }
70    /// ```
71    ///
72    /// We begin with a variable `expr` of type `Expr` that has no fields
73    /// (because it is an enum), and by matching on it and rebinding a variable
74    /// with the same name `expr` we effectively imbue our variable with all of
75    /// the data fields provided by the variant that it turned out to be. So for
76    /// example above if we ended up in the `MethodCall` case then we get to use
77    /// `expr.receiver`, `expr.args` etc; if we ended up in the `If` case we get
78    /// to use `expr.cond`, `expr.then_branch`, `expr.else_branch`.
79    ///
80    /// This approach avoids repeating the variant names twice on every line.
81    ///
82    /// ```
83    /// # use syn::{Expr, ExprMethodCall};
84    /// #
85    /// # fn example(expr: Expr) {
86    /// // Repetitive; recommend not doing this.
87    /// match expr {
88    ///     Expr::MethodCall(ExprMethodCall { method, args, .. }) => {
89    /// # }
90    /// # _ => {}
91    /// # }
92    /// # }
93    /// ```
94    ///
95    /// In general, the name to which a syntax tree enum variant is bound should
96    /// be a suitable name for the complete syntax tree enum type.
97    ///
98    /// ```
99    /// # use syn::{Expr, ExprField};
100    /// #
101    /// # fn example(discriminant: ExprField) {
102    /// // Binding is called `base` which is the name I would use if I were
103    /// // assigning `*discriminant.base` without an `if let`.
104    /// if let Expr::Tuple(base) = *discriminant.base {
105    /// # }
106    /// # }
107    /// ```
108    ///
109    /// A sign that you may not be choosing the right variable names is if you
110    /// see names getting repeated in your code, like accessing
111    /// `receiver.receiver` or `pat.pat` or `cond.cond`.
112    ///
113    /// # Exhaustive matching
114    ///
115    /// For testing exhaustiveness in downstream code, use the following idiom:
116    ///
117    /// ```
118    /// # use syn::Expr;
119    /// #
120    /// # fn example(expr: Expr) {
121    /// match expr {
122    ///     #![cfg_attr(test, deny(non_exhaustive_omitted_patterns))]
123    ///
124    ///     Expr::Array(expr) => { /*...*/ }
125    ///     Expr::Assign(expr) => { /*...*/ }
126    #[cfg_attr(not(doctest), doc = "     ...")]
127    ///     Expr::Yield(expr) => { /*...*/ }
128    ///
129    ///     _ => { /* some sane fallback */ }
130    /// }
131    /// # }
132    /// ```
133    ///
134    /// This way we fail your tests but don't break your library when adding a
135    /// variant. You will be notified by a test failure when a variant is added,
136    /// so that you can add code to handle it, but your library will continue to
137    /// compile and work for downstream users in the interim.
138    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
139    #[non_exhaustive]
140    pub enum Expr {
141        /// A slice literal expression: `[a, b, c, d]`.
142        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
143        Array(ExprArray),
144
145        /// An assignment expression: `a = compute()`.
146        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
147        Assign(ExprAssign),
148
149        /// An async block: `async { ... }`.
150        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
151        Async(ExprAsync),
152
153        /// An await expression: `fut.await`.
154        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
155        Await(ExprAwait),
156
157        /// A binary operation: `a + b`, `a += b`.
158        Binary(ExprBinary),
159
160        /// A braced block: `{ ... }`.
161        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
162        Block(ExprBlock),
163
164        /// A `break`, with an optional label to break and an optional
165        /// expression.
166        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
167        Break(ExprBreak),
168
169        /// A function call expression: `invoke(a, b)`.
170        Call(ExprCall),
171
172        /// A cast expression: `foo as f64`.
173        Cast(ExprCast),
174
175        /// A closure expression: `|a, b| a + b`.
176        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
177        Closure(ExprClosure),
178
179        /// A const block: `const { ... }`.
180        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
181        Const(ExprConst),
182
183        /// A `continue`, with an optional label.
184        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
185        Continue(ExprContinue),
186
187        /// Access of a named struct field (`obj.k`) or unnamed tuple struct
188        /// field (`obj.0`).
189        Field(ExprField),
190
191        /// A for loop: `for pat in expr { ... }`.
192        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
193        ForLoop(ExprForLoop),
194
195        /// An expression contained within invisible delimiters.
196        ///
197        /// This variant is important for faithfully representing the precedence
198        /// of expressions and is related to `None`-delimited spans in a
199        /// `TokenStream`.
200        Group(ExprGroup),
201
202        /// An `if` expression with an optional `else` block: `if expr { ... }
203        /// else { ... }`.
204        ///
205        /// The `else` branch expression may only be an `If` or `Block`
206        /// expression, not any of the other types of expression.
207        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
208        If(ExprIf),
209
210        /// A square bracketed indexing expression: `vector[2]`.
211        Index(ExprIndex),
212
213        /// The inferred value of a const generic argument, denoted `_`.
214        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
215        Infer(ExprInfer),
216
217        /// A pattern application: `let Some(x) = opt`.
218        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
219        Let(ExprLet),
220
221        /// A literal in place of an expression: `1`, `"foo"`.
222        Lit(ExprLit),
223
224        /// Conditionless loop: `loop { ... }`.
225        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
226        Loop(ExprLoop),
227
228        /// A macro invocation expression: `format!("{}", q)`.
229        Macro(ExprMacro),
230
231        /// A `match` expression: `match n { Some(n) => {}, None => {} }`.
232        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
233        Match(ExprMatch),
234
235        /// A method call expression: `x.foo::<T>(a, b)`.
236        MethodCall(ExprMethodCall),
237
238        /// A parenthesized expression: `(a + b)`.
239        Paren(ExprParen),
240
241        /// A path like `core::mem::replace` possibly containing generic
242        /// parameters and a qualified self-type.
243        ///
244        /// A plain identifier like `x` is a path of length 1.
245        Path(ExprPath),
246
247        /// A range expression: `1..2`, `1..`, `..2`, `1..=2`, `..=2`.
248        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
249        Range(ExprRange),
250
251        /// Address-of operation: `&raw const place` or `&raw mut place`.
252        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
253        RawAddr(ExprRawAddr),
254
255        /// A referencing operation: `&a` or `&mut a`.
256        Reference(ExprReference),
257
258        /// An array literal constructed from one repeated element: `[0u8; N]`.
259        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
260        Repeat(ExprRepeat),
261
262        /// A `return`, with an optional value to be returned.
263        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
264        Return(ExprReturn),
265
266        /// A struct literal expression: `Point { x: 1, y: 1 }`.
267        ///
268        /// The `rest` provides the value of the remaining fields as in `S { a:
269        /// 1, b: 1, ..rest }`.
270        Struct(ExprStruct),
271
272        /// A try-expression: `expr?`.
273        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
274        Try(ExprTry),
275
276        /// A try block: `try { ... }`.
277        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
278        TryBlock(ExprTryBlock),
279
280        /// A tuple expression: `(a, b, c, d)`.
281        Tuple(ExprTuple),
282
283        /// A unary operation: `!x`, `*x`, `-x`.
284        Unary(ExprUnary),
285
286        /// An unsafe block: `unsafe { ... }`.
287        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
288        Unsafe(ExprUnsafe),
289
290        /// Tokens in expression position not interpreted by Syn.
291        Verbatim(TokenStream),
292
293        /// A while loop: `while expr { ... }`.
294        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
295        While(ExprWhile),
296
297        /// A yield expression: `yield expr`.
298        #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
299        Yield(ExprYield),
300    }
301}
302
303ast_struct! {
304    /// A slice literal expression: `[a, b, c, d]`.
305    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
306    pub struct ExprArray #full {
307        pub attrs: Vec<Attribute>,
308        pub bracket_token: token::Bracket,
309        pub elems: Punctuated<Expr, Token![,]>,
310    }
311}
312
313ast_struct! {
314    /// An assignment expression: `a = compute()`.
315    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
316    pub struct ExprAssign #full {
317        pub attrs: Vec<Attribute>,
318        pub left: Box<Expr>,
319        pub eq_token: Token![=],
320        pub right: Box<Expr>,
321    }
322}
323
324ast_struct! {
325    /// An async block: `async { ... }`.
326    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
327    pub struct ExprAsync #full {
328        pub attrs: Vec<Attribute>,
329        pub async_token: Token![async],
330        pub capture: Option<Token![move]>,
331        /// (Non-exhaustive) Additional optional information about a block.
332        pub modifiers: BlockModifiers,
333        pub block: Block,
334    }
335}
336
337ast_struct! {
338    /// An await expression: `fut.await`.
339    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
340    pub struct ExprAwait #full {
341        pub attrs: Vec<Attribute>,
342        pub base: Box<Expr>,
343        pub dot_token: Token![.],
344        pub await_token: Token![await],
345    }
346}
347
348ast_struct! {
349    /// A binary operation: `a + b`, `a += b`.
350    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
351    pub struct ExprBinary {
352        pub attrs: Vec<Attribute>,
353        pub left: Box<Expr>,
354        pub op: BinOp,
355        pub right: Box<Expr>,
356    }
357}
358
359ast_struct! {
360    /// A braced block: `{ ... }`.
361    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
362    pub struct ExprBlock #full {
363        pub attrs: Vec<Attribute>,
364        pub label: Option<Label>,
365        pub block: Block,
366    }
367}
368
369ast_struct! {
370    /// A `break`, with an optional label to break and an optional
371    /// expression.
372    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
373    pub struct ExprBreak #full {
374        pub attrs: Vec<Attribute>,
375        pub break_token: Token![break],
376        pub label: Option<Lifetime>,
377        pub expr: Option<Box<Expr>>,
378    }
379}
380
381ast_struct! {
382    /// A function call expression: `invoke(a, b)`.
383    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
384    pub struct ExprCall {
385        pub attrs: Vec<Attribute>,
386        pub func: Box<Expr>,
387        pub paren_token: token::Paren,
388        pub args: Punctuated<Expr, Token![,]>,
389    }
390}
391
392ast_struct! {
393    /// A cast expression: `foo as f64`.
394    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
395    pub struct ExprCast {
396        pub attrs: Vec<Attribute>,
397        pub expr: Box<Expr>,
398        pub as_token: Token![as],
399        pub ty: Box<Type>,
400    }
401}
402
403ast_struct! {
404    /// A closure expression: `|a, b| a + b`.
405    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
406    pub struct ExprClosure #full {
407        pub attrs: Vec<Attribute>,
408        pub lifetimes: Option<BoundLifetimes>,
409        /// (Non-exhaustive) Additional optional information about a closure.
410        pub modifiers: ClosureModifiers,
411        pub constness: Option<Token![const]>,
412        pub asyncness: Option<Token![async]>,
413        pub capture: Option<Token![move]>,
414        pub inputs_begin: Token![|],
415        pub inputs: Punctuated<Pat, Token![,]>,
416        pub inputs_end: Token![|],
417        pub output: ReturnType,
418        pub body: Box<Expr>,
419    }
420}
421
422#[cfg(feature = "full")]
423ast_struct! {
424    /// Additional optional information about a closure.
425    ///
426    /// This data structure may grow to accommodate future Rust language
427    /// changes, including the following in-progress RFCs:
428    ///
429    /// - [RFC 2033] "Coroutines" (`static || ...`)
430    /// - [RFC 3680] "Simplify lightweight clones" (`use || ...`)
431    ///
432    /// [RFC 2033]: https://github.com/rust-lang/rust/issues/43122
433    /// [RFC 3680]: https://github.com/rust-lang/rust/issues/132290
434    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
435    #[non_exhaustive]
436    pub struct ClosureModifiers {}
437}
438
439#[cfg(feature = "full")]
440impl Default for ClosureModifiers {
441    fn default() -> Self {
442        ClosureModifiers {}
443    }
444}
445
446#[cfg(feature = "full")]
447impl ClosureModifiers {
448    #[cfg(feature = "parsing")]
449    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
450    pub fn require_empty(&self) -> Result<()> {
451        Ok(())
452    }
453}
454
455ast_struct! {
456    /// A const block: `const { ... }`.
457    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
458    pub struct ExprConst #full {
459        pub attrs: Vec<Attribute>,
460        pub const_token: Token![const],
461        /// (Non-exhaustive) Additional optional information about a block.
462        pub modifiers: BlockModifiers,
463        pub block: Block,
464    }
465}
466
467ast_struct! {
468    /// A `continue`, with an optional label.
469    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
470    pub struct ExprContinue #full {
471        pub attrs: Vec<Attribute>,
472        pub continue_token: Token![continue],
473        pub label: Option<Lifetime>,
474    }
475}
476
477ast_struct! {
478    /// Access of a named struct field (`obj.k`) or unnamed tuple struct
479    /// field (`obj.0`).
480    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
481    pub struct ExprField {
482        pub attrs: Vec<Attribute>,
483        pub base: Box<Expr>,
484        pub dot_token: Token![.],
485        pub member: Member,
486    }
487}
488
489ast_struct! {
490    /// A for loop: `for pat in expr { ... }`.
491    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
492    pub struct ExprForLoop #full {
493        pub attrs: Vec<Attribute>,
494        pub label: Option<Label>,
495        pub for_token: Token![for],
496        pub pat: Box<Pat>,
497        pub in_token: Token![in],
498        pub expr: Box<Expr>,
499        pub body: Block,
500    }
501}
502
503ast_struct! {
504    /// An expression contained within invisible delimiters.
505    ///
506    /// This variant is important for faithfully representing the precedence
507    /// of expressions and is related to `None`-delimited spans in a
508    /// `TokenStream`.
509    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
510    pub struct ExprGroup {
511        pub attrs: Vec<Attribute>,
512        pub group_token: token::Group,
513        pub expr: Box<Expr>,
514    }
515}
516
517ast_struct! {
518    /// An `if` expression with an optional `else` block: `if expr { ... }
519    /// else { ... }`.
520    ///
521    /// The `else` branch expression may only be an `If` or `Block`
522    /// expression, not any of the other types of expression.
523    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
524    pub struct ExprIf #full {
525        pub attrs: Vec<Attribute>,
526        pub if_token: Token![if],
527        pub cond: Box<Expr>,
528        pub then_branch: Block,
529        pub else_branch: Option<(Token![else], Box<Expr>)>,
530    }
531}
532
533ast_struct! {
534    /// A square bracketed indexing expression: `vector[2]`.
535    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
536    pub struct ExprIndex {
537        pub attrs: Vec<Attribute>,
538        pub expr: Box<Expr>,
539        pub bracket_token: token::Bracket,
540        pub index: Box<Expr>,
541    }
542}
543
544ast_struct! {
545    /// The inferred value of a const generic argument, denoted `_`.
546    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
547    pub struct ExprInfer #full {
548        pub attrs: Vec<Attribute>,
549        pub underscore_token: Token![_],
550    }
551}
552
553ast_struct! {
554    /// A pattern application: `let Some(x) = opt`.
555    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
556    pub struct ExprLet #full {
557        pub attrs: Vec<Attribute>,
558        pub let_token: Token![let],
559        pub pat: Box<Pat>,
560        pub eq_token: Token![=],
561        pub expr: Box<Expr>,
562    }
563}
564
565ast_struct! {
566    /// A literal in place of an expression: `1`, `"foo"`.
567    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
568    pub struct ExprLit {
569        pub attrs: Vec<Attribute>,
570        pub lit: Lit,
571    }
572}
573
574ast_struct! {
575    /// Conditionless loop: `loop { ... }`.
576    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
577    pub struct ExprLoop #full {
578        pub attrs: Vec<Attribute>,
579        pub label: Option<Label>,
580        pub loop_token: Token![loop],
581        pub body: Block,
582    }
583}
584
585ast_struct! {
586    /// A macro invocation expression: `format!("{}", q)`.
587    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
588    pub struct ExprMacro {
589        pub attrs: Vec<Attribute>,
590        pub mac: Macro,
591    }
592}
593
594ast_struct! {
595    /// A `match` expression: `match n { Some(n) => {}, None => {} }`.
596    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
597    pub struct ExprMatch #full {
598        pub attrs: Vec<Attribute>,
599        pub match_token: Token![match],
600        pub expr: Box<Expr>,
601        pub brace_token: token::Brace,
602        pub arms: Vec<Arm>,
603    }
604}
605
606ast_struct! {
607    /// A method call expression: `x.foo::<T>(a, b)`.
608    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
609    pub struct ExprMethodCall {
610        pub attrs: Vec<Attribute>,
611        pub receiver: Box<Expr>,
612        pub dot_token: Token![.],
613        pub method: Ident,
614        pub turbofish: Option<AngleBracketedGenericArguments>,
615        pub paren_token: token::Paren,
616        pub args: Punctuated<Expr, Token![,]>,
617    }
618}
619
620ast_struct! {
621    /// A parenthesized expression: `(a + b)`.
622    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
623    pub struct ExprParen {
624        pub attrs: Vec<Attribute>,
625        pub paren_token: token::Paren,
626        pub expr: Box<Expr>,
627    }
628}
629
630ast_struct! {
631    /// A path like `core::mem::replace` possibly containing generic
632    /// parameters and a qualified self-type.
633    ///
634    /// A plain identifier like `x` is a path of length 1.
635    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
636    pub struct ExprPath {
637        pub attrs: Vec<Attribute>,
638        pub qself: Option<QSelf>,
639        pub path: Path,
640    }
641}
642
643ast_struct! {
644    /// A range expression: `1..2`, `1..`, `..2`, `1..=2`, `..=2`.
645    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
646    pub struct ExprRange #full {
647        pub attrs: Vec<Attribute>,
648        pub start: Option<Box<Expr>>,
649        pub limits: RangeLimits,
650        pub end: Option<Box<Expr>>,
651    }
652}
653
654ast_struct! {
655    /// Address-of operation: `&raw const place` or `&raw mut place`.
656    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
657    pub struct ExprRawAddr #full {
658        pub attrs: Vec<Attribute>,
659        pub and_token: Token![&],
660        pub raw: Token![raw],
661        pub mutability: PointerMutability,
662        pub expr: Box<Expr>,
663    }
664}
665
666ast_struct! {
667    /// A referencing operation: `&a` or `&mut a`.
668    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
669    pub struct ExprReference {
670        pub attrs: Vec<Attribute>,
671        pub and_token: Token![&],
672        pub mutability: Option<Token![mut]>,
673        pub expr: Box<Expr>,
674    }
675}
676
677ast_struct! {
678    /// An array literal constructed from one repeated element: `[0u8; N]`.
679    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
680    pub struct ExprRepeat #full {
681        pub attrs: Vec<Attribute>,
682        pub bracket_token: token::Bracket,
683        pub expr: Box<Expr>,
684        pub semi_token: Token![;],
685        pub len: Box<Expr>,
686    }
687}
688
689ast_struct! {
690    /// A `return`, with an optional value to be returned.
691    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
692    pub struct ExprReturn #full {
693        pub attrs: Vec<Attribute>,
694        pub return_token: Token![return],
695        pub expr: Option<Box<Expr>>,
696    }
697}
698
699ast_struct! {
700    /// A struct literal expression: `Point { x: 1, y: 1 }`.
701    ///
702    /// The `rest` provides the value of the remaining fields as in `S { a:
703    /// 1, b: 1, ..rest }`.
704    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
705    pub struct ExprStruct {
706        pub attrs: Vec<Attribute>,
707        pub qself: Option<QSelf>,
708        pub path: Path,
709        pub brace_token: token::Brace,
710        pub fields: Punctuated<FieldValue, Token![,]>,
711        pub dot2_token: Option<Token![..]>,
712        pub rest: Option<Box<Expr>>,
713    }
714}
715
716ast_struct! {
717    /// A try-expression: `expr?`.
718    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
719    pub struct ExprTry #full {
720        pub attrs: Vec<Attribute>,
721        pub expr: Box<Expr>,
722        pub question_token: Token![?],
723    }
724}
725
726ast_struct! {
727    /// A try block: `try { ... }`.
728    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
729    pub struct ExprTryBlock #full {
730        pub attrs: Vec<Attribute>,
731        pub try_token: Token![try],
732        /// (Non-exhaustive) Additional optional information about a block.
733        pub modifiers: BlockModifiers,
734        pub block: Block,
735    }
736}
737
738ast_struct! {
739    /// A tuple expression: `(a, b, c, d)`.
740    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
741    pub struct ExprTuple {
742        pub attrs: Vec<Attribute>,
743        pub paren_token: token::Paren,
744        pub elems: Punctuated<Expr, Token![,]>,
745    }
746}
747
748ast_struct! {
749    /// A unary operation: `!x`, `*x`, `-x`.
750    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
751    pub struct ExprUnary {
752        pub attrs: Vec<Attribute>,
753        pub op: UnOp,
754        pub expr: Box<Expr>,
755    }
756}
757
758ast_struct! {
759    /// An unsafe block: `unsafe { ... }`.
760    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
761    pub struct ExprUnsafe #full {
762        pub attrs: Vec<Attribute>,
763        pub unsafe_token: Token![unsafe],
764        pub block: Block,
765    }
766}
767
768ast_struct! {
769    /// A while loop: `while expr { ... }`.
770    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
771    pub struct ExprWhile #full {
772        pub attrs: Vec<Attribute>,
773        pub label: Option<Label>,
774        pub while_token: Token![while],
775        pub cond: Box<Expr>,
776        pub body: Block,
777    }
778}
779
780ast_struct! {
781    /// A yield expression: `yield expr`.
782    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
783    pub struct ExprYield #full {
784        pub attrs: Vec<Attribute>,
785        pub yield_token: Token![yield],
786        pub expr: Option<Box<Expr>>,
787    }
788}
789
790impl Expr {
791    /// An unspecified invalid expression.
792    ///
793    /// ```
794    /// use core::mem;
795    /// use quote::ToTokens;
796    /// use syn::{parse_quote, Expr};
797    ///
798    /// fn unparenthesize(e: &mut Expr) {
799    ///     while let Expr::Paren(paren) = e {
800    ///         *e = mem::replace(&mut *paren.expr, Expr::PLACEHOLDER);
801    ///     }
802    /// }
803    ///
804    /// fn main() {
805    ///     let mut e: Expr = parse_quote! { ((1 + 1)) };
806    ///     unparenthesize(&mut e);
807    ///     assert_eq!("1 + 1", e.to_token_stream().to_string());
808    /// }
809    /// ```
810    pub const PLACEHOLDER: Self = Expr::Path(ExprPath {
811        attrs: Vec::new(),
812        qself: None,
813        path: Path {
814            leading_colon: None,
815            segments: Punctuated::new(),
816        },
817    });
818
819    /// An alternative to the primary `Expr::parse` parser (from the [`Parse`]
820    /// trait) for ambiguous syntactic positions in which a trailing brace
821    /// should not be taken as part of the expression.
822    ///
823    /// [`Parse`]: crate::parse::Parse
824    ///
825    /// Rust grammar has an ambiguity where braces sometimes turn a path
826    /// expression into a struct initialization and sometimes do not. In the
827    /// following code, the expression `S {}` is one expression. Presumably
828    /// there is an empty struct `struct S {}` defined somewhere which it is
829    /// instantiating.
830    ///
831    /// ```
832    /// # struct S;
833    /// # impl core::ops::Deref for S {
834    /// #     type Target = bool;
835    /// #     fn deref(&self) -> &Self::Target {
836    /// #         &true
837    /// #     }
838    /// # }
839    /// let _ = *S {};
840    ///
841    /// // parsed by rustc as: `*(S {})`
842    /// ```
843    ///
844    /// We would want to parse the above using `Expr::parse` after the `=`
845    /// token.
846    ///
847    /// But in the following, `S {}` is *not* a struct init expression.
848    ///
849    /// ```
850    /// # const S: &bool = &true;
851    /// if *S {} {}
852    ///
853    /// // parsed by rustc as:
854    /// //
855    /// //    if (*S) {
856    /// //        /* empty block */
857    /// //    }
858    /// //    {
859    /// //        /* another empty block */
860    /// //    }
861    /// ```
862    ///
863    /// For that reason we would want to parse if-conditions using
864    /// `Expr::parse_without_eager_brace` after the `if` token. Same for similar
865    /// syntactic positions such as the condition expr after a `while` token or
866    /// the expr at the top of a `match`.
867    ///
868    /// The Rust grammar's choices around which way this ambiguity is resolved
869    /// at various syntactic positions is fairly arbitrary. Really either parse
870    /// behavior could work in most positions, and language designers just
871    /// decide each case based on which is more likely to be what the programmer
872    /// had in mind most of the time.
873    ///
874    /// ```
875    /// # struct S;
876    /// # fn doc() -> S {
877    /// if return S {} {}
878    /// # unreachable!()
879    /// # }
880    ///
881    /// // parsed by rustc as:
882    /// //
883    /// //    if (return (S {})) {
884    /// //    }
885    /// //
886    /// // but could equally well have been this other arbitrary choice:
887    /// //
888    /// //    if (return S) {
889    /// //    }
890    /// //    {}
891    /// ```
892    ///
893    /// Note the grammar ambiguity on trailing braces is distinct from
894    /// precedence and is not captured by assigning a precedence level to the
895    /// braced struct init expr in relation to other operators. This can be
896    /// illustrated by `return 0..S {}` vs `match 0..S {}`. The former parses as
897    /// `return (0..(S {}))` implying tighter precedence for struct init than
898    /// `..`, while the latter parses as `match (0..S) {}` implying tighter
899    /// precedence for `..` than struct init, a contradiction.
900    #[cfg(all(feature = "full", feature = "parsing"))]
901    #[cfg_attr(docsrs, doc(cfg(all(feature = "full", feature = "parsing"))))]
902    pub fn parse_without_eager_brace(input: ParseStream) -> Result<Expr> {
903        parsing::ambiguous_expr(input, parsing::AllowStruct(false))
904    }
905
906    /// An alternative to the primary `Expr::parse` parser (from the [`Parse`]
907    /// trait) for syntactic positions in which expression boundaries are placed
908    /// more eagerly than done by the typical expression grammar. This includes
909    /// expressions at the head of a statement or in the right-hand side of a
910    /// `match` arm.
911    ///
912    /// [`Parse`]: crate::parse::Parse
913    ///
914    /// Compare the following cases:
915    ///
916    /// 1.
917    ///   ```
918    ///   # let result = ();
919    ///   # let guard = false;
920    ///   # let cond = true;
921    ///   # let f = true;
922    ///   # let g = f;
923    ///   #
924    ///   let _ = match result {
925    ///       () if guard => if cond { f } else { g }
926    ///       () => false,
927    ///   };
928    ///   ```
929    ///
930    /// 2.
931    ///   ```
932    ///   # let cond = true;
933    ///   # let f = ();
934    ///   # let g = f;
935    ///   #
936    ///   let _ = || {
937    ///       if cond { f } else { g }
938    ///       ()
939    ///   };
940    ///   ```
941    ///
942    /// 3.
943    ///   ```
944    ///   # let cond = true;
945    ///   # let f = || ();
946    ///   # let g = f;
947    ///   #
948    ///   let _ = [if cond { f } else { g } ()];
949    ///   ```
950    ///
951    /// The same sequence of tokens `if cond { f } else { g } ()` appears in
952    /// expression position 3 times. The first two syntactic positions use eager
953    /// placement of expression boundaries, and parse as `Expr::If`, with the
954    /// adjacent `()` becoming `Pat::Tuple` or `Expr::Tuple`. In contrast, the
955    /// third case uses standard expression boundaries and parses as
956    /// `Expr::Call`.
957    ///
958    /// As with [`parse_without_eager_brace`], this ambiguity in the Rust
959    /// grammar is independent of precedence.
960    ///
961    /// [`parse_without_eager_brace`]: Self::parse_without_eager_brace
962    #[cfg(all(feature = "full", feature = "parsing"))]
963    #[cfg_attr(docsrs, doc(cfg(all(feature = "full", feature = "parsing"))))]
964    pub fn parse_with_earlier_boundary_rule(input: ParseStream) -> Result<Expr> {
965        parsing::parse_with_earlier_boundary_rule(input)
966    }
967
968    /// Returns whether the next token in the parse stream is one that might
969    /// possibly form the beginning of an expr.
970    ///
971    /// This classification is a load-bearing part of the grammar of some Rust
972    /// expressions, notably `return` and `break`. For example `return < …` will
973    /// never parse `<` as a binary operator regardless of what comes after,
974    /// because `<` is a legal starting token for an expression and so it's
975    /// required to be continued as a return value, such as `return <Struct as
976    /// Trait>::CONST`. Meanwhile `return > …` treats the `>` as a binary
977    /// operator because it cannot be a starting token for any Rust expression.
978    #[cfg(feature = "parsing")]
979    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
980    pub fn peek(input: ParseStream) -> bool {
981        input.peek(Ident::peek_any) && !input.peek(Token![as]) // value name or keyword
982            || input.peek(token::Paren) // tuple
983            || input.peek(token::Bracket) // array
984            || input.peek(token::Brace) // block
985            || input.peek(Lit) // literal
986            || input.peek(Token![!]) && !input.peek(Token![!=]) // operator not
987            || input.peek(Token![-]) && !input.peek(Token![-=]) && !input.peek(Token![->]) // unary minus
988            || input.peek(Token![*]) && !input.peek(Token![*=]) // dereference
989            || input.peek(Token![|]) && !input.peek(Token![|=]) // closure
990            || input.peek(Token![&]) && !input.peek(Token![&=]) // reference
991            || input.peek(Token![..]) // range
992            || input.peek(Token![<]) && !input.peek(Token![<=]) && !input.peek(Token![<<=]) // associated path
993            || input.peek(Token![::]) // absolute path
994            || input.peek(Lifetime) // labeled loop
995            || input.peek(Token![#]) // expression attributes
996    }
997
998    #[cfg(all(feature = "parsing", feature = "full"))]
999    pub(crate) fn replace_attrs(&mut self, new: Vec<Attribute>) -> Vec<Attribute> {
1000        match self {
1001            Expr::Array(ExprArray { attrs, .. })
1002            | Expr::Assign(ExprAssign { attrs, .. })
1003            | Expr::Async(ExprAsync { attrs, .. })
1004            | Expr::Await(ExprAwait { attrs, .. })
1005            | Expr::Binary(ExprBinary { attrs, .. })
1006            | Expr::Block(ExprBlock { attrs, .. })
1007            | Expr::Break(ExprBreak { attrs, .. })
1008            | Expr::Call(ExprCall { attrs, .. })
1009            | Expr::Cast(ExprCast { attrs, .. })
1010            | Expr::Closure(ExprClosure { attrs, .. })
1011            | Expr::Const(ExprConst { attrs, .. })
1012            | Expr::Continue(ExprContinue { attrs, .. })
1013            | Expr::Field(ExprField { attrs, .. })
1014            | Expr::ForLoop(ExprForLoop { attrs, .. })
1015            | Expr::Group(ExprGroup { attrs, .. })
1016            | Expr::If(ExprIf { attrs, .. })
1017            | Expr::Index(ExprIndex { attrs, .. })
1018            | Expr::Infer(ExprInfer { attrs, .. })
1019            | Expr::Let(ExprLet { attrs, .. })
1020            | Expr::Lit(ExprLit { attrs, .. })
1021            | Expr::Loop(ExprLoop { attrs, .. })
1022            | Expr::Macro(ExprMacro { attrs, .. })
1023            | Expr::Match(ExprMatch { attrs, .. })
1024            | Expr::MethodCall(ExprMethodCall { attrs, .. })
1025            | Expr::Paren(ExprParen { attrs, .. })
1026            | Expr::Path(ExprPath { attrs, .. })
1027            | Expr::Range(ExprRange { attrs, .. })
1028            | Expr::RawAddr(ExprRawAddr { attrs, .. })
1029            | Expr::Reference(ExprReference { attrs, .. })
1030            | Expr::Repeat(ExprRepeat { attrs, .. })
1031            | Expr::Return(ExprReturn { attrs, .. })
1032            | Expr::Struct(ExprStruct { attrs, .. })
1033            | Expr::Try(ExprTry { attrs, .. })
1034            | Expr::TryBlock(ExprTryBlock { attrs, .. })
1035            | Expr::Tuple(ExprTuple { attrs, .. })
1036            | Expr::Unary(ExprUnary { attrs, .. })
1037            | Expr::Unsafe(ExprUnsafe { attrs, .. })
1038            | Expr::While(ExprWhile { attrs, .. })
1039            | Expr::Yield(ExprYield { attrs, .. }) => mem::replace(attrs, new),
1040            Expr::Verbatim(_) => Vec::new(),
1041        }
1042    }
1043}
1044
1045ast_enum! {
1046    /// A struct or tuple struct field accessed in a struct literal or field
1047    /// expression.
1048    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
1049    pub enum Member {
1050        /// A named field like `self.x`.
1051        Named(Ident),
1052        /// An unnamed field like `self.0`.
1053        Unnamed(Index),
1054    }
1055}
1056
1057impl From<Ident> for Member {
1058    fn from(ident: Ident) -> Member {
1059        Member::Named(ident)
1060    }
1061}
1062
1063impl From<Index> for Member {
1064    fn from(index: Index) -> Member {
1065        Member::Unnamed(index)
1066    }
1067}
1068
1069impl From<usize> for Member {
1070    fn from(index: usize) -> Member {
1071        Member::Unnamed(Index::from(index))
1072    }
1073}
1074
1075impl Eq for Member {}
1076
1077impl PartialEq for Member {
1078    fn eq(&self, other: &Self) -> bool {
1079        match (self, other) {
1080            (Member::Named(this), Member::Named(other)) => this == other,
1081            (Member::Unnamed(this), Member::Unnamed(other)) => this == other,
1082            _ => false,
1083        }
1084    }
1085}
1086
1087impl Hash for Member {
1088    fn hash<H: Hasher>(&self, state: &mut H) {
1089        match self {
1090            Member::Named(m) => m.hash(state),
1091            Member::Unnamed(m) => m.hash(state),
1092        }
1093    }
1094}
1095
1096#[cfg(feature = "printing")]
1097impl IdentFragment for Member {
1098    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1099        match self {
1100            Member::Named(m) => Display::fmt(m, formatter),
1101            Member::Unnamed(m) => Display::fmt(&m.index, formatter),
1102        }
1103    }
1104
1105    fn span(&self) -> Option<Span> {
1106        match self {
1107            Member::Named(m) => Some(m.span()),
1108            Member::Unnamed(m) => Some(m.span),
1109        }
1110    }
1111}
1112
1113#[cfg(any(feature = "parsing", feature = "printing"))]
1114impl Member {
1115    pub(crate) fn is_named(&self) -> bool {
1116        match self {
1117            Member::Named(_) => true,
1118            Member::Unnamed(_) => false,
1119        }
1120    }
1121}
1122
1123ast_struct! {
1124    /// The index of an unnamed tuple struct field.
1125    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
1126    pub struct Index {
1127        pub index: u32,
1128        pub span: Span,
1129    }
1130}
1131
1132impl From<usize> for Index {
1133    fn from(index: usize) -> Index {
1134        assert!(index < u32::MAX as usize);
1135        Index {
1136            index: index as u32,
1137            span: Span::call_site(),
1138        }
1139    }
1140}
1141
1142impl Eq for Index {}
1143
1144impl PartialEq for Index {
1145    fn eq(&self, other: &Self) -> bool {
1146        self.index == other.index
1147    }
1148}
1149
1150impl Hash for Index {
1151    fn hash<H: Hasher>(&self, state: &mut H) {
1152        self.index.hash(state);
1153    }
1154}
1155
1156#[cfg(feature = "printing")]
1157impl IdentFragment for Index {
1158    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1159        Display::fmt(&self.index, formatter)
1160    }
1161
1162    fn span(&self) -> Option<Span> {
1163        Some(self.span)
1164    }
1165}
1166
1167ast_struct! {
1168    /// A field-value pair in a struct literal.
1169    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
1170    pub struct FieldValue {
1171        pub attrs: Vec<Attribute>,
1172        pub member: Member,
1173
1174        /// The colon in `Struct { x: x }`. If written in shorthand like
1175        /// `Struct { x }`, there is no colon.
1176        pub colon_token: Option<Token![:]>,
1177
1178        pub expr: Expr,
1179    }
1180}
1181
1182#[cfg(feature = "full")]
1183ast_struct! {
1184    /// A lifetime labeling a `for`, `while`, or `loop`.
1185    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
1186    pub struct Label {
1187        pub name: Lifetime,
1188        pub colon_token: Token![:],
1189    }
1190}
1191
1192#[cfg(feature = "full")]
1193ast_struct! {
1194    /// One arm of a `match` expression: `0..=10 => { return true; }`.
1195    ///
1196    /// As in:
1197    ///
1198    /// ```
1199    /// # fn f() -> bool {
1200    /// #     let n = 0;
1201    /// match n {
1202    ///     0..=10 => {
1203    ///         return true;
1204    ///     }
1205    ///     // ...
1206    ///     # _ => {}
1207    /// }
1208    /// #   false
1209    /// # }
1210    /// ```
1211    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
1212    pub struct Arm {
1213        pub attrs: Vec<Attribute>,
1214        pub pat: Pat,
1215        pub fat_arrow_token: Token![=>],
1216        pub body: Box<Expr>,
1217        pub comma: Option<Token![,]>,
1218    }
1219}
1220
1221#[cfg(feature = "full")]
1222ast_struct! {
1223    /// Additional optional information about a block.
1224    ///
1225    /// This data structure may grow to accommodate future Rust language
1226    /// changes, including the following in-progress RFCs:
1227    ///
1228    /// - [RFC 3680] "Simplify lightweight clones" (`async use { ... }`)
1229    /// - [#149488] "Heterogeneous try blocks" (`try bikeshed Option<_> { ... }`)
1230    ///
1231    /// [RFC 3680]: https://github.com/rust-lang/rust/issues/132290
1232    /// [#149488]: https://github.com/rust-lang/rust/issues/149488
1233    #[non_exhaustive]
1234    pub struct BlockModifiers {}
1235}
1236
1237#[cfg(feature = "full")]
1238impl Default for BlockModifiers {
1239    fn default() -> Self {
1240        BlockModifiers {}
1241    }
1242}
1243
1244#[cfg(feature = "full")]
1245impl BlockModifiers {
1246    #[cfg(feature = "parsing")]
1247    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1248    pub fn require_empty(&self) -> Result<()> {
1249        Ok(())
1250    }
1251}
1252
1253#[cfg(feature = "full")]
1254ast_enum! {
1255    /// Limit types of a range, inclusive or exclusive.
1256    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
1257    pub enum RangeLimits {
1258        /// Inclusive at the beginning, exclusive at the end.
1259        HalfOpen(Token![..]),
1260        /// Inclusive at the beginning and end.
1261        Closed(Token![..=]),
1262    }
1263}
1264
1265#[cfg(feature = "parsing")]
1266pub(crate) mod parsing {
1267    #[cfg(feature = "full")]
1268    use crate::attr;
1269    use crate::attr::Attribute;
1270    #[cfg(feature = "full")]
1271    use crate::buffer::Cursor;
1272    #[cfg(feature = "full")]
1273    use crate::classify;
1274    use crate::error::{Error, Result};
1275    #[cfg(feature = "full")]
1276    use crate::expr::{
1277        Arm, BlockModifiers, ClosureModifiers, ExprArray, ExprAssign, ExprAsync, ExprAwait,
1278        ExprBlock, ExprBreak, ExprClosure, ExprConst, ExprContinue, ExprForLoop, ExprIf, ExprInfer,
1279        ExprLet, ExprLoop, ExprMatch, ExprRange, ExprRawAddr, ExprRepeat, ExprReturn, ExprTry,
1280        ExprTryBlock, ExprUnsafe, ExprWhile, ExprYield, Label, RangeLimits,
1281    };
1282    use crate::expr::{
1283        Expr, ExprBinary, ExprCall, ExprCast, ExprField, ExprGroup, ExprIndex, ExprLit, ExprMacro,
1284        ExprMethodCall, ExprParen, ExprPath, ExprReference, ExprStruct, ExprTuple, ExprUnary,
1285        FieldValue, Index, Member,
1286    };
1287    #[cfg(feature = "full")]
1288    use crate::generics::{self, BoundLifetimes};
1289    use crate::ident::Ident;
1290    #[cfg(feature = "full")]
1291    use crate::lifetime::Lifetime;
1292    use crate::lit::{Lit, LitFloat, LitInt};
1293    use crate::mac::{self, Macro};
1294    use crate::op::BinOp;
1295    use crate::parse::discouraged::Speculative as _;
1296    use crate::parse::{Parse, ParseStream};
1297    #[cfg(feature = "full")]
1298    use crate::pat::{Pat, PatType};
1299    use crate::path::{self, AngleBracketedGenericArguments, Path, QSelf};
1300    use crate::precedence::Precedence;
1301    use crate::punctuated::Punctuated;
1302    #[cfg(feature = "full")]
1303    use crate::stmt::Block;
1304    use crate::token;
1305    use crate::ty;
1306    #[cfg(feature = "full")]
1307    use crate::ty::{PointerMutability, ReturnType, Type};
1308    use crate::verbatim;
1309    use alloc::boxed::Box;
1310    use alloc::format;
1311    use alloc::string::ToString;
1312    use alloc::vec::Vec;
1313    use core::mem;
1314    #[cfg(feature = "full")]
1315    use proc_macro2::{Span, TokenStream};
1316
1317    // When we're parsing expressions which occur before blocks, like in an if
1318    // statement's condition, we cannot parse a struct literal.
1319    //
1320    // Struct literals are ambiguous in certain positions
1321    // https://github.com/rust-lang/rfcs/pull/92
1322    #[cfg(feature = "full")]
1323    pub(super) struct AllowStruct(pub bool);
1324
1325    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1326    impl Parse for Expr {
1327        fn parse(input: ParseStream) -> Result<Self> {
1328            ambiguous_expr(
1329                input,
1330                #[cfg(feature = "full")]
1331                AllowStruct(true),
1332            )
1333        }
1334    }
1335
1336    #[cfg(feature = "full")]
1337    pub(super) fn parse_with_earlier_boundary_rule(input: ParseStream) -> Result<Expr> {
1338        let mut attrs = input.call(expr_attrs)?;
1339        let mut expr = if input.peek(token::Group) {
1340            let allow_struct = AllowStruct(true);
1341            let atom = expr_group(input, allow_struct)?;
1342            if continue_parsing_early(&atom) {
1343                trailer_helper(input, atom)?
1344            } else {
1345                atom
1346            }
1347        } else if input.peek(Token![if]) {
1348            Expr::If(input.parse()?)
1349        } else if input.peek(Token![while]) {
1350            Expr::While(input.parse()?)
1351        } else if input.peek(Token![for])
1352            && !generics::parsing::choose_generics_over_qpath_after_keyword(input)
1353        {
1354            Expr::ForLoop(input.parse()?)
1355        } else if input.peek(Token![loop]) {
1356            Expr::Loop(input.parse()?)
1357        } else if input.peek(Token![match]) {
1358            Expr::Match(input.parse()?)
1359        } else if input.peek(Token![try]) && input.peek2(token::Brace) {
1360            Expr::TryBlock(input.parse()?)
1361        } else if input.peek(Token![unsafe]) {
1362            Expr::Unsafe(input.parse()?)
1363        } else if input.peek(Token![const]) && input.peek2(token::Brace) {
1364            Expr::Const(input.parse()?)
1365        } else if input.peek(token::Brace) {
1366            Expr::Block(input.parse()?)
1367        } else if input.peek(Lifetime) {
1368            atom_labeled(input)?
1369        } else {
1370            let allow_struct = AllowStruct(true);
1371            unary_expr(input, allow_struct)?
1372        };
1373
1374        if continue_parsing_early(&expr) {
1375            attrs.extend(expr.replace_attrs(Vec::new()));
1376            expr.replace_attrs(attrs);
1377
1378            let allow_struct = AllowStruct(true);
1379            return parse_expr(input, expr, allow_struct, Precedence::MIN);
1380        }
1381
1382        if input.peek(Token![.]) && !input.peek(Token![..]) || input.peek(Token![?]) {
1383            expr = trailer_helper(input, expr)?;
1384
1385            attrs.extend(expr.replace_attrs(Vec::new()));
1386            expr.replace_attrs(attrs);
1387
1388            let allow_struct = AllowStruct(true);
1389            return parse_expr(input, expr, allow_struct, Precedence::MIN);
1390        }
1391
1392        attrs.extend(expr.replace_attrs(Vec::new()));
1393        expr.replace_attrs(attrs);
1394        Ok(expr)
1395    }
1396
1397    #[cfg(feature = "full")]
1398    impl Copy for AllowStruct {}
1399
1400    #[cfg(feature = "full")]
1401    impl Clone for AllowStruct {
1402        fn clone(&self) -> Self {
1403            *self
1404        }
1405    }
1406
1407    #[cfg(feature = "full")]
1408    fn parse_expr(
1409        input: ParseStream,
1410        mut lhs: Expr,
1411        allow_struct: AllowStruct,
1412        base: Precedence,
1413    ) -> Result<Expr> {
1414        loop {
1415            let ahead = input.fork();
1416            if let Expr::Range(_) = lhs {
1417                // A range cannot be the left-hand side of another binary operator.
1418                break;
1419            } else if let Ok(op) = ahead.parse::<BinOp>() {
1420                let precedence = Precedence::of_binop(&op);
1421                if precedence < base {
1422                    break;
1423                }
1424                if precedence == Precedence::Assign {
1425                    if let Expr::Range(_) = lhs {
1426                        break;
1427                    }
1428                }
1429                if precedence == Precedence::Compare {
1430                    if let Expr::Binary(lhs) = &lhs {
1431                        if Precedence::of_binop(&lhs.op) == Precedence::Compare {
1432                            return Err(input.error("comparison operators cannot be chained"));
1433                        }
1434                    }
1435                }
1436                input.advance_to(&ahead);
1437                let right = parse_binop_rhs(input, allow_struct, precedence)?;
1438                lhs = Expr::Binary(ExprBinary {
1439                    attrs: Vec::new(),
1440                    left: Box::new(lhs),
1441                    op,
1442                    right,
1443                });
1444            } else if Precedence::Assign >= base
1445                && input.peek(Token![=])
1446                && !input.peek(Token![=>])
1447                && match lhs {
1448                    Expr::Range(_) => false,
1449                    _ => true,
1450                }
1451            {
1452                let eq_token: Token![=] = input.parse()?;
1453                let right = parse_binop_rhs(input, allow_struct, Precedence::Assign)?;
1454                lhs = Expr::Assign(ExprAssign {
1455                    attrs: Vec::new(),
1456                    left: Box::new(lhs),
1457                    eq_token,
1458                    right,
1459                });
1460            } else if Precedence::Range >= base && input.peek(Token![..]) {
1461                let limits: RangeLimits = input.parse()?;
1462                let end = parse_range_end(input, &limits, allow_struct)?;
1463                lhs = Expr::Range(ExprRange {
1464                    attrs: Vec::new(),
1465                    start: Some(Box::new(lhs)),
1466                    limits,
1467                    end,
1468                });
1469            } else if Precedence::Cast >= base && input.peek(Token![as]) {
1470                let as_token: Token![as] = input.parse()?;
1471                let allow_plus = false;
1472                let allow_group_generic = false;
1473                let ty = ty::parsing::ambig_ty(input, allow_plus, allow_group_generic)?;
1474                check_cast(input)?;
1475                lhs = Expr::Cast(ExprCast {
1476                    attrs: Vec::new(),
1477                    expr: Box::new(lhs),
1478                    as_token,
1479                    ty: Box::new(ty),
1480                });
1481            } else {
1482                break;
1483            }
1484        }
1485        Ok(lhs)
1486    }
1487
1488    #[cfg(not(feature = "full"))]
1489    fn parse_expr(input: ParseStream, mut lhs: Expr, base: Precedence) -> Result<Expr> {
1490        loop {
1491            let ahead = input.fork();
1492            if let Ok(op) = ahead.parse::<BinOp>() {
1493                let precedence = Precedence::of_binop(&op);
1494                if precedence < base {
1495                    break;
1496                }
1497                if precedence == Precedence::Compare {
1498                    if let Expr::Binary(lhs) = &lhs {
1499                        if Precedence::of_binop(&lhs.op) == Precedence::Compare {
1500                            return Err(input.error("comparison operators cannot be chained"));
1501                        }
1502                    }
1503                }
1504                input.advance_to(&ahead);
1505                let right = parse_binop_rhs(input, precedence)?;
1506                lhs = Expr::Binary(ExprBinary {
1507                    attrs: Vec::new(),
1508                    left: Box::new(lhs),
1509                    op,
1510                    right,
1511                });
1512            } else if Precedence::Cast >= base && input.peek(Token![as]) {
1513                let as_token: Token![as] = input.parse()?;
1514                let allow_plus = false;
1515                let allow_group_generic = false;
1516                let ty = ty::parsing::ambig_ty(input, allow_plus, allow_group_generic)?;
1517                check_cast(input)?;
1518                lhs = Expr::Cast(ExprCast {
1519                    attrs: Vec::new(),
1520                    expr: Box::new(lhs),
1521                    as_token,
1522                    ty: Box::new(ty),
1523                });
1524            } else {
1525                break;
1526            }
1527        }
1528        Ok(lhs)
1529    }
1530
1531    fn parse_binop_rhs(
1532        input: ParseStream,
1533        #[cfg(feature = "full")] allow_struct: AllowStruct,
1534        precedence: Precedence,
1535    ) -> Result<Box<Expr>> {
1536        let mut rhs = unary_expr(
1537            input,
1538            #[cfg(feature = "full")]
1539            allow_struct,
1540        )?;
1541        loop {
1542            let next = peek_precedence(input);
1543            if next > precedence || next == precedence && precedence == Precedence::Assign {
1544                let cursor = input.cursor();
1545                rhs = parse_expr(
1546                    input,
1547                    rhs,
1548                    #[cfg(feature = "full")]
1549                    allow_struct,
1550                    next,
1551                )?;
1552                if cursor == input.cursor() {
1553                    // Bespoke grammar restrictions separate from precedence can
1554                    // cause parsing to not advance, such as `..a` being
1555                    // disallowed in the left-hand side of binary operators,
1556                    // even ones that have lower precedence than `..`.
1557                    break;
1558                }
1559            } else {
1560                break;
1561            }
1562        }
1563        Ok(Box::new(rhs))
1564    }
1565
1566    fn peek_precedence(input: ParseStream) -> Precedence {
1567        if let Ok(op) = input.fork().parse() {
1568            Precedence::of_binop(&op)
1569        } else if input.peek(Token![=]) && !input.peek(Token![=>]) {
1570            Precedence::Assign
1571        } else if input.peek(Token![..]) {
1572            Precedence::Range
1573        } else if input.peek(Token![as]) {
1574            Precedence::Cast
1575        } else {
1576            Precedence::MIN
1577        }
1578    }
1579
1580    // Parse an arbitrary expression.
1581    pub(super) fn ambiguous_expr(
1582        input: ParseStream,
1583        #[cfg(feature = "full")] allow_struct: AllowStruct,
1584    ) -> Result<Expr> {
1585        let lhs = unary_expr(
1586            input,
1587            #[cfg(feature = "full")]
1588            allow_struct,
1589        )?;
1590        parse_expr(
1591            input,
1592            lhs,
1593            #[cfg(feature = "full")]
1594            allow_struct,
1595            Precedence::MIN,
1596        )
1597    }
1598
1599    #[cfg(feature = "full")]
1600    fn expr_attrs(input: ParseStream) -> Result<Vec<Attribute>> {
1601        let mut attrs = Vec::new();
1602        while !input.peek(token::Group) && input.peek(Token![#]) {
1603            attrs.push(input.call(attr::parsing::single_parse_outer)?);
1604        }
1605        Ok(attrs)
1606    }
1607
1608    // <UnOp> <trailer>
1609    // & <trailer>
1610    // &mut <trailer>
1611    // box <trailer>
1612    #[cfg(feature = "full")]
1613    fn unary_expr(input: ParseStream, allow_struct: AllowStruct) -> Result<Expr> {
1614        let begin = input.cursor();
1615        let attrs = input.call(expr_attrs)?;
1616        if input.peek(token::Group) {
1617            return trailer_expr(begin, attrs, input, allow_struct);
1618        }
1619
1620        if input.peek(Token![&]) {
1621            let and_token: Token![&] = input.parse()?;
1622            let raw: Option<Token![raw]> = if input.peek(Token![raw])
1623                && (input.peek2(Token![mut]) || input.peek2(Token![const]))
1624            {
1625                Some(input.parse()?)
1626            } else {
1627                None
1628            };
1629            let mutability: Option<Token![mut]> = input.parse()?;
1630            let const_token: Option<Token![const]> = if raw.is_some() && mutability.is_none() {
1631                Some(input.parse()?)
1632            } else {
1633                None
1634            };
1635            let expr = Box::new(unary_expr(input, allow_struct)?);
1636            if let Some(raw) = raw {
1637                Ok(Expr::RawAddr(ExprRawAddr {
1638                    attrs,
1639                    and_token,
1640                    raw,
1641                    mutability: match mutability {
1642                        Some(mut_token) => PointerMutability::Mut(mut_token),
1643                        None => PointerMutability::Const(const_token.unwrap()),
1644                    },
1645                    expr,
1646                }))
1647            } else {
1648                Ok(Expr::Reference(ExprReference {
1649                    attrs,
1650                    and_token,
1651                    mutability,
1652                    expr,
1653                }))
1654            }
1655        } else if input.peek(Token![*]) || input.peek(Token![!]) || input.peek(Token![-]) {
1656            expr_unary(input, attrs, allow_struct).map(Expr::Unary)
1657        } else {
1658            trailer_expr(begin, attrs, input, allow_struct)
1659        }
1660    }
1661
1662    #[cfg(not(feature = "full"))]
1663    fn unary_expr(input: ParseStream) -> Result<Expr> {
1664        if input.peek(Token![&]) {
1665            Ok(Expr::Reference(ExprReference {
1666                attrs: Vec::new(),
1667                and_token: input.parse()?,
1668                mutability: input.parse()?,
1669                expr: Box::new(unary_expr(input)?),
1670            }))
1671        } else if input.peek(Token![*]) || input.peek(Token![!]) || input.peek(Token![-]) {
1672            Ok(Expr::Unary(ExprUnary {
1673                attrs: Vec::new(),
1674                op: input.parse()?,
1675                expr: Box::new(unary_expr(input)?),
1676            }))
1677        } else {
1678            trailer_expr(input)
1679        }
1680    }
1681
1682    // <atom> (..<args>) ...
1683    // <atom> . <ident> (..<args>) ...
1684    // <atom> . <ident> ...
1685    // <atom> . <lit> ...
1686    // <atom> [ <expr> ] ...
1687    // <atom> ? ...
1688    #[cfg(feature = "full")]
1689    fn trailer_expr(
1690        begin: Cursor,
1691        mut attrs: Vec<Attribute>,
1692        input: ParseStream,
1693        allow_struct: AllowStruct,
1694    ) -> Result<Expr> {
1695        let atom = atom_expr(input, allow_struct)?;
1696        let mut e = trailer_helper(input, atom)?;
1697
1698        if let Expr::Verbatim(tokens) = &mut e {
1699            *tokens = verbatim::between(begin, input.cursor());
1700        } else if !attrs.is_empty() {
1701            if let Expr::Range(range) = e {
1702                let spans: &[Span] = match &range.limits {
1703                    RangeLimits::HalfOpen(limits) => &limits.spans,
1704                    RangeLimits::Closed(limits) => &limits.spans,
1705                };
1706                return Err(crate::error::new2(
1707                    spans[0],
1708                    *spans.last().unwrap(),
1709                    "attributes are not allowed on range expressions starting with `..`",
1710                ));
1711            }
1712            let inner_attrs = e.replace_attrs(Vec::new());
1713            attrs.extend(inner_attrs);
1714            e.replace_attrs(attrs);
1715        }
1716
1717        Ok(e)
1718    }
1719
1720    #[cfg(feature = "full")]
1721    fn trailer_helper(input: ParseStream, mut e: Expr) -> Result<Expr> {
1722        loop {
1723            if input.peek(token::Paren) {
1724                let content;
1725                e = Expr::Call(ExprCall {
1726                    attrs: Vec::new(),
1727                    func: Box::new(e),
1728                    paren_token: parenthesized!(content in input),
1729                    args: content.parse_terminated(Expr::parse, Token![,])?,
1730                });
1731            } else if input.peek(Token![.])
1732                && !input.peek(Token![..])
1733                && match e {
1734                    Expr::Range(_) => false,
1735                    _ => true,
1736                }
1737            {
1738                let mut dot_token: Token![.] = input.parse()?;
1739
1740                let float_token: Option<LitFloat> = input.parse()?;
1741                if let Some(float_token) = float_token {
1742                    if multi_index(&mut e, &mut dot_token, float_token)? {
1743                        continue;
1744                    }
1745                }
1746
1747                let await_token: Option<Token![await]> = input.parse()?;
1748                if let Some(await_token) = await_token {
1749                    e = Expr::Await(ExprAwait {
1750                        attrs: Vec::new(),
1751                        base: Box::new(e),
1752                        dot_token,
1753                        await_token,
1754                    });
1755                    continue;
1756                }
1757
1758                let member: Member = input.parse()?;
1759                let turbofish = if member.is_named() && input.peek(Token![::]) {
1760                    Some(AngleBracketedGenericArguments::parse_turbofish(input)?)
1761                } else {
1762                    None
1763                };
1764
1765                if turbofish.is_some() || input.peek(token::Paren) {
1766                    if let Member::Named(method) = member {
1767                        let content;
1768                        e = Expr::MethodCall(ExprMethodCall {
1769                            attrs: Vec::new(),
1770                            receiver: Box::new(e),
1771                            dot_token,
1772                            method,
1773                            turbofish,
1774                            paren_token: parenthesized!(content in input),
1775                            args: content.parse_terminated(Expr::parse, Token![,])?,
1776                        });
1777                        continue;
1778                    }
1779                }
1780
1781                e = Expr::Field(ExprField {
1782                    attrs: Vec::new(),
1783                    base: Box::new(e),
1784                    dot_token,
1785                    member,
1786                });
1787            } else if input.peek(token::Bracket) {
1788                let content;
1789                e = Expr::Index(ExprIndex {
1790                    attrs: Vec::new(),
1791                    expr: Box::new(e),
1792                    bracket_token: bracketed!(content in input),
1793                    index: content.parse()?,
1794                });
1795            } else if input.peek(Token![?])
1796                && match e {
1797                    Expr::Range(_) => false,
1798                    _ => true,
1799                }
1800            {
1801                e = Expr::Try(ExprTry {
1802                    attrs: Vec::new(),
1803                    expr: Box::new(e),
1804                    question_token: input.parse()?,
1805                });
1806            } else {
1807                break;
1808            }
1809        }
1810        Ok(e)
1811    }
1812
1813    #[cfg(not(feature = "full"))]
1814    fn trailer_expr(input: ParseStream) -> Result<Expr> {
1815        let mut e = atom_expr(input)?;
1816
1817        loop {
1818            if input.peek(token::Paren) {
1819                let content;
1820                e = Expr::Call(ExprCall {
1821                    attrs: Vec::new(),
1822                    func: Box::new(e),
1823                    paren_token: parenthesized!(content in input),
1824                    args: content.parse_terminated(Expr::parse, Token![,])?,
1825                });
1826            } else if input.peek(Token![.])
1827                && !input.peek(Token![..])
1828                && !input.peek2(Token![await])
1829            {
1830                let mut dot_token: Token![.] = input.parse()?;
1831
1832                let float_token: Option<LitFloat> = input.parse()?;
1833                if let Some(float_token) = float_token {
1834                    if multi_index(&mut e, &mut dot_token, float_token)? {
1835                        continue;
1836                    }
1837                }
1838
1839                let member: Member = input.parse()?;
1840                let turbofish = if member.is_named() && input.peek(Token![::]) {
1841                    let colon2_token: Token![::] = input.parse()?;
1842                    let turbofish =
1843                        AngleBracketedGenericArguments::do_parse(Some(colon2_token), input)?;
1844                    Some(turbofish)
1845                } else {
1846                    None
1847                };
1848
1849                if turbofish.is_some() || input.peek(token::Paren) {
1850                    if let Member::Named(method) = member {
1851                        let content;
1852                        e = Expr::MethodCall(ExprMethodCall {
1853                            attrs: Vec::new(),
1854                            receiver: Box::new(e),
1855                            dot_token,
1856                            method,
1857                            turbofish,
1858                            paren_token: parenthesized!(content in input),
1859                            args: content.parse_terminated(Expr::parse, Token![,])?,
1860                        });
1861                        continue;
1862                    }
1863                }
1864
1865                e = Expr::Field(ExprField {
1866                    attrs: Vec::new(),
1867                    base: Box::new(e),
1868                    dot_token,
1869                    member,
1870                });
1871            } else if input.peek(token::Bracket) {
1872                let content;
1873                e = Expr::Index(ExprIndex {
1874                    attrs: Vec::new(),
1875                    expr: Box::new(e),
1876                    bracket_token: bracketed!(content in input),
1877                    index: content.parse()?,
1878                });
1879            } else {
1880                break;
1881            }
1882        }
1883
1884        Ok(e)
1885    }
1886
1887    // Parse all atomic expressions which don't have to worry about precedence
1888    // interactions, as they are fully contained.
1889    #[cfg(feature = "full")]
1890    fn atom_expr(input: ParseStream, allow_struct: AllowStruct) -> Result<Expr> {
1891        if input.peek(token::Group) {
1892            expr_group(input, allow_struct)
1893        } else if input.peek(Lit) {
1894            input.parse().map(Expr::Lit)
1895        } else if input.peek(Token![async])
1896            && (input.peek2(token::Brace) || input.peek2(Token![move]) && input.peek3(token::Brace))
1897        {
1898            input.parse().map(Expr::Async)
1899        } else if input.peek(Token![try]) && input.peek2(token::Brace) {
1900            input.parse().map(Expr::TryBlock)
1901        } else if input.peek(Token![|])
1902            || input.peek(Token![move])
1903            || input.peek(Token![for])
1904                && generics::parsing::choose_generics_over_qpath_after_keyword(input)
1905            || input.peek(Token![const]) && !input.peek2(token::Brace)
1906            || input.peek(Token![static])
1907            || input.peek(Token![async]) && (input.peek2(Token![|]) || input.peek2(Token![move]))
1908        {
1909            expr_closure(input, allow_struct).map(Expr::Closure)
1910        } else if token::parsing::peek_keyword(input.cursor(), "builtin") && input.peek2(Token![#])
1911        {
1912            expr_builtin(input)
1913        } else if input.peek(Ident)
1914            || input.peek(Token![::])
1915            || input.peek(Token![<])
1916            || input.peek(Token![self])
1917            || input.peek(Token![Self])
1918            || input.peek(Token![super])
1919            || input.peek(Token![crate])
1920            || input.peek(Token![try]) && (input.peek2(Token![!]) || input.peek2(Token![::]))
1921        {
1922            path_or_macro_or_struct(input, allow_struct)
1923        } else if input.peek(token::Paren) {
1924            paren_or_tuple(input)
1925        } else if input.peek(Token![break]) {
1926            expr_break(input, allow_struct).map(Expr::Break)
1927        } else if input.peek(Token![continue]) {
1928            input.parse().map(Expr::Continue)
1929        } else if input.peek(Token![return]) {
1930            input.parse().map(Expr::Return)
1931        } else if input.peek(Token![become]) {
1932            expr_become(input)
1933        } else if input.peek(token::Bracket) {
1934            array_or_repeat(input)
1935        } else if input.peek(Token![let]) {
1936            expr_let(input, allow_struct).map(Expr::Let)
1937        } else if input.peek(Token![if]) {
1938            input.parse().map(Expr::If)
1939        } else if input.peek(Token![while]) {
1940            input.parse().map(Expr::While)
1941        } else if input.peek(Token![for]) {
1942            input.parse().map(Expr::ForLoop)
1943        } else if input.peek(Token![loop]) {
1944            input.parse().map(Expr::Loop)
1945        } else if input.peek(Token![match]) {
1946            input.parse().map(Expr::Match)
1947        } else if input.peek(Token![yield]) {
1948            input.parse().map(Expr::Yield)
1949        } else if input.peek(Token![unsafe]) {
1950            input.parse().map(Expr::Unsafe)
1951        } else if input.peek(Token![const]) {
1952            input.parse().map(Expr::Const)
1953        } else if input.peek(token::Brace) {
1954            input.parse().map(Expr::Block)
1955        } else if input.peek(Token![..]) {
1956            expr_range(input, allow_struct).map(Expr::Range)
1957        } else if input.peek(Token![_]) {
1958            input.parse().map(Expr::Infer)
1959        } else if input.peek(Lifetime) {
1960            atom_labeled(input)
1961        } else {
1962            Err(input.error("expected an expression"))
1963        }
1964    }
1965
1966    #[cfg(feature = "full")]
1967    fn atom_labeled(input: ParseStream) -> Result<Expr> {
1968        let the_label: Label = input.parse()?;
1969        let mut expr = if input.peek(Token![while]) {
1970            Expr::While(input.parse()?)
1971        } else if input.peek(Token![for]) {
1972            Expr::ForLoop(input.parse()?)
1973        } else if input.peek(Token![loop]) {
1974            Expr::Loop(input.parse()?)
1975        } else if input.peek(token::Brace) {
1976            Expr::Block(input.parse()?)
1977        } else {
1978            return Err(input.error("expected loop or block expression"));
1979        };
1980        match &mut expr {
1981            Expr::While(ExprWhile { label, .. })
1982            | Expr::ForLoop(ExprForLoop { label, .. })
1983            | Expr::Loop(ExprLoop { label, .. })
1984            | Expr::Block(ExprBlock { label, .. }) => *label = Some(the_label),
1985            _ => unreachable!(),
1986        }
1987        Ok(expr)
1988    }
1989
1990    #[cfg(not(feature = "full"))]
1991    fn atom_expr(input: ParseStream) -> Result<Expr> {
1992        if input.peek(token::Group) {
1993            expr_group(input)
1994        } else if input.peek(Lit) {
1995            input.parse().map(Expr::Lit)
1996        } else if input.peek(token::Paren) {
1997            paren_or_tuple(input)
1998        } else if input.peek(Ident)
1999            || input.peek(Token![::])
2000            || input.peek(Token![<])
2001            || input.peek(Token![self])
2002            || input.peek(Token![Self])
2003            || input.peek(Token![super])
2004            || input.peek(Token![crate])
2005        {
2006            path_or_macro_or_struct(input)
2007        } else if input.is_empty() {
2008            Err(input.error("expected an expression"))
2009        } else {
2010            if input.peek(token::Brace) {
2011                let scan = input.fork();
2012                let content;
2013                braced!(content in scan);
2014                if content.parse::<Expr>().is_ok() && content.is_empty() {
2015                    let expr_block = verbatim::between(input.cursor(), scan.cursor());
2016                    input.advance_to(&scan);
2017                    return Ok(Expr::Verbatim(expr_block));
2018                }
2019            }
2020            Err(input.error("unsupported expression; enable syn's features=[\"full\"]"))
2021        }
2022    }
2023
2024    #[cfg(feature = "full")]
2025    fn expr_builtin(input: ParseStream) -> Result<Expr> {
2026        let begin = input.cursor();
2027
2028        token::parsing::keyword(input, "builtin")?;
2029        input.parse::<Token![#]>()?;
2030        input.parse::<Ident>()?;
2031
2032        let args;
2033        parenthesized!(args in input);
2034        args.parse::<TokenStream>()?;
2035
2036        Ok(Expr::Verbatim(verbatim::between(begin, input.cursor())))
2037    }
2038
2039    fn path_or_macro_or_struct(
2040        input: ParseStream,
2041        #[cfg(feature = "full")] allow_struct: AllowStruct,
2042    ) -> Result<Expr> {
2043        let expr_style = true;
2044        let (qself, path) = path::parsing::qpath(input, expr_style)?;
2045        rest_of_path_or_macro_or_struct(
2046            qself,
2047            path,
2048            input,
2049            #[cfg(feature = "full")]
2050            allow_struct,
2051        )
2052    }
2053
2054    fn rest_of_path_or_macro_or_struct(
2055        qself: Option<QSelf>,
2056        path: Path,
2057        input: ParseStream,
2058        #[cfg(feature = "full")] allow_struct: AllowStruct,
2059    ) -> Result<Expr> {
2060        if qself.is_none()
2061            && input.peek(Token![!])
2062            && !input.peek(Token![!=])
2063            && path.is_mod_style()
2064        {
2065            let bang_token: Token![!] = input.parse()?;
2066            let (delimiter, tokens) = mac::parse_delimiter(input)?;
2067            return Ok(Expr::Macro(ExprMacro {
2068                attrs: Vec::new(),
2069                mac: Macro {
2070                    path,
2071                    bang_token,
2072                    delimiter,
2073                    tokens,
2074                },
2075            }));
2076        }
2077
2078        #[cfg(not(feature = "full"))]
2079        let allow_struct = (true,);
2080        if allow_struct.0 && input.peek(token::Brace) {
2081            return expr_struct_helper(input, qself, path).map(Expr::Struct);
2082        }
2083
2084        Ok(Expr::Path(ExprPath {
2085            attrs: Vec::new(),
2086            qself,
2087            path,
2088        }))
2089    }
2090
2091    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2092    impl Parse for ExprMacro {
2093        fn parse(input: ParseStream) -> Result<Self> {
2094            Ok(ExprMacro {
2095                attrs: Vec::new(),
2096                mac: input.parse()?,
2097            })
2098        }
2099    }
2100
2101    fn paren_or_tuple(input: ParseStream) -> Result<Expr> {
2102        let content;
2103        let paren_token = parenthesized!(content in input);
2104        if content.is_empty() {
2105            return Ok(Expr::Tuple(ExprTuple {
2106                attrs: Vec::new(),
2107                paren_token,
2108                elems: Punctuated::new(),
2109            }));
2110        }
2111
2112        let first: Expr = content.parse()?;
2113        if content.is_empty() {
2114            return Ok(Expr::Paren(ExprParen {
2115                attrs: Vec::new(),
2116                paren_token,
2117                expr: Box::new(first),
2118            }));
2119        }
2120
2121        let mut elems = Punctuated::new();
2122        elems.push_value(first);
2123        while !content.is_empty() {
2124            let punct = content.parse()?;
2125            elems.push_punct(punct);
2126            if content.is_empty() {
2127                break;
2128            }
2129            let value = content.parse()?;
2130            elems.push_value(value);
2131        }
2132        Ok(Expr::Tuple(ExprTuple {
2133            attrs: Vec::new(),
2134            paren_token,
2135            elems,
2136        }))
2137    }
2138
2139    #[cfg(feature = "full")]
2140    fn array_or_repeat(input: ParseStream) -> Result<Expr> {
2141        let content;
2142        let bracket_token = bracketed!(content in input);
2143        if content.is_empty() {
2144            return Ok(Expr::Array(ExprArray {
2145                attrs: Vec::new(),
2146                bracket_token,
2147                elems: Punctuated::new(),
2148            }));
2149        }
2150
2151        let first: Expr = content.parse()?;
2152        if content.is_empty() || content.peek(Token![,]) {
2153            let mut elems = Punctuated::new();
2154            elems.push_value(first);
2155            while !content.is_empty() {
2156                let punct = content.parse()?;
2157                elems.push_punct(punct);
2158                if content.is_empty() {
2159                    break;
2160                }
2161                let value = content.parse()?;
2162                elems.push_value(value);
2163            }
2164            Ok(Expr::Array(ExprArray {
2165                attrs: Vec::new(),
2166                bracket_token,
2167                elems,
2168            }))
2169        } else if content.peek(Token![;]) {
2170            let semi_token: Token![;] = content.parse()?;
2171            let len: Expr = content.parse()?;
2172            Ok(Expr::Repeat(ExprRepeat {
2173                attrs: Vec::new(),
2174                bracket_token,
2175                expr: Box::new(first),
2176                semi_token,
2177                len: Box::new(len),
2178            }))
2179        } else {
2180            Err(content.error("expected `,` or `;`"))
2181        }
2182    }
2183
2184    #[cfg(feature = "full")]
2185    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2186    impl Parse for ExprArray {
2187        fn parse(input: ParseStream) -> Result<Self> {
2188            let content;
2189            let bracket_token = bracketed!(content in input);
2190            let mut elems = Punctuated::new();
2191
2192            while !content.is_empty() {
2193                let first: Expr = content.parse()?;
2194                elems.push_value(first);
2195                if content.is_empty() {
2196                    break;
2197                }
2198                let punct = content.parse()?;
2199                elems.push_punct(punct);
2200            }
2201
2202            Ok(ExprArray {
2203                attrs: Vec::new(),
2204                bracket_token,
2205                elems,
2206            })
2207        }
2208    }
2209
2210    #[cfg(feature = "full")]
2211    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2212    impl Parse for ExprRepeat {
2213        fn parse(input: ParseStream) -> Result<Self> {
2214            let content;
2215            Ok(ExprRepeat {
2216                bracket_token: bracketed!(content in input),
2217                attrs: Vec::new(),
2218                expr: content.parse()?,
2219                semi_token: content.parse()?,
2220                len: content.parse()?,
2221            })
2222        }
2223    }
2224
2225    #[cfg(feature = "full")]
2226    fn continue_parsing_early(mut expr: &Expr) -> bool {
2227        while let Expr::Group(group) = expr {
2228            expr = &group.expr;
2229        }
2230        match expr {
2231            Expr::If(_)
2232            | Expr::While(_)
2233            | Expr::ForLoop(_)
2234            | Expr::Loop(_)
2235            | Expr::Match(_)
2236            | Expr::TryBlock(_)
2237            | Expr::Unsafe(_)
2238            | Expr::Const(_)
2239            | Expr::Block(_) => false,
2240            _ => true,
2241        }
2242    }
2243
2244    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2245    impl Parse for ExprLit {
2246        fn parse(input: ParseStream) -> Result<Self> {
2247            Ok(ExprLit {
2248                attrs: Vec::new(),
2249                lit: input.parse()?,
2250            })
2251        }
2252    }
2253
2254    fn expr_group(
2255        input: ParseStream,
2256        #[cfg(feature = "full")] allow_struct: AllowStruct,
2257    ) -> Result<Expr> {
2258        let group = crate::group::parse_group(input)?;
2259        let mut inner: Expr = group.content.parse()?;
2260
2261        match inner {
2262            Expr::Path(mut expr) if expr.attrs.is_empty() => {
2263                let grouped_len = expr.path.segments.len();
2264                Path::parse_rest(input, &mut expr.path, true)?;
2265                match rest_of_path_or_macro_or_struct(
2266                    expr.qself,
2267                    expr.path,
2268                    input,
2269                    #[cfg(feature = "full")]
2270                    allow_struct,
2271                )? {
2272                    Expr::Path(expr) if expr.path.segments.len() == grouped_len => {
2273                        inner = Expr::Path(expr);
2274                    }
2275                    extended => return Ok(extended),
2276                }
2277            }
2278            _ => {}
2279        }
2280
2281        Ok(Expr::Group(ExprGroup {
2282            attrs: Vec::new(),
2283            group_token: group.token,
2284            expr: Box::new(inner),
2285        }))
2286    }
2287
2288    #[cfg(feature = "full")]
2289    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2290    impl Parse for ExprParen {
2291        fn parse(input: ParseStream) -> Result<Self> {
2292            let content;
2293            Ok(ExprParen {
2294                attrs: Vec::new(),
2295                paren_token: parenthesized!(content in input),
2296                expr: content.parse()?,
2297            })
2298        }
2299    }
2300
2301    #[cfg(feature = "full")]
2302    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2303    impl Parse for ExprLet {
2304        fn parse(input: ParseStream) -> Result<Self> {
2305            let allow_struct = AllowStruct(true);
2306            expr_let(input, allow_struct)
2307        }
2308    }
2309
2310    #[cfg(feature = "full")]
2311    fn expr_let(input: ParseStream, allow_struct: AllowStruct) -> Result<ExprLet> {
2312        Ok(ExprLet {
2313            attrs: Vec::new(),
2314            let_token: input.parse()?,
2315            pat: Box::new(Pat::parse_multi_with_leading_vert(input)?),
2316            eq_token: input.parse()?,
2317            expr: Box::new({
2318                let lhs = unary_expr(input, allow_struct)?;
2319                parse_expr(input, lhs, allow_struct, Precedence::Compare)?
2320            }),
2321        })
2322    }
2323
2324    #[cfg(feature = "full")]
2325    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2326    impl Parse for ExprIf {
2327        fn parse(input: ParseStream) -> Result<Self> {
2328            let attrs = input.call(Attribute::parse_outer)?;
2329
2330            let mut clauses = Vec::new();
2331            let mut expr;
2332            loop {
2333                let if_token: Token![if] = input.parse()?;
2334                let cond = input.call(Expr::parse_without_eager_brace)?;
2335                let then_branch: Block = input.parse()?;
2336
2337                expr = ExprIf {
2338                    attrs: Vec::new(),
2339                    if_token,
2340                    cond: Box::new(cond),
2341                    then_branch,
2342                    else_branch: None,
2343                };
2344
2345                if !input.peek(Token![else]) {
2346                    break;
2347                }
2348
2349                let else_token: Token![else] = input.parse()?;
2350                let lookahead = input.lookahead1();
2351                if lookahead.peek(Token![if]) {
2352                    expr.else_branch = Some((else_token, Box::new(Expr::PLACEHOLDER)));
2353                    clauses.push(expr);
2354                } else if lookahead.peek(token::Brace) {
2355                    expr.else_branch = Some((
2356                        else_token,
2357                        Box::new(Expr::Block(ExprBlock {
2358                            attrs: Vec::new(),
2359                            label: None,
2360                            block: input.parse()?,
2361                        })),
2362                    ));
2363                    break;
2364                } else {
2365                    return Err(lookahead.error());
2366                }
2367            }
2368
2369            while let Some(mut prev) = clauses.pop() {
2370                *prev.else_branch.as_mut().unwrap().1 = Expr::If(expr);
2371                expr = prev;
2372            }
2373            expr.attrs = attrs;
2374            Ok(expr)
2375        }
2376    }
2377
2378    #[cfg(feature = "full")]
2379    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2380    impl Parse for ExprInfer {
2381        fn parse(input: ParseStream) -> Result<Self> {
2382            Ok(ExprInfer {
2383                attrs: input.call(Attribute::parse_outer)?,
2384                underscore_token: input.parse()?,
2385            })
2386        }
2387    }
2388
2389    #[cfg(feature = "full")]
2390    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2391    impl Parse for ExprForLoop {
2392        fn parse(input: ParseStream) -> Result<Self> {
2393            let mut attrs = input.call(Attribute::parse_outer)?;
2394            let label: Option<Label> = input.parse()?;
2395            let for_token: Token![for] = input.parse()?;
2396
2397            let pat = Pat::parse_multi_with_leading_vert(input)?;
2398
2399            let in_token: Token![in] = input.parse()?;
2400            let expr: Expr = input.call(Expr::parse_without_eager_brace)?;
2401
2402            let content;
2403            let brace_token = braced!(content in input);
2404            attr::parsing::parse_inner(&content, &mut attrs)?;
2405            let stmts = content.call(Block::parse_within)?;
2406
2407            Ok(ExprForLoop {
2408                attrs,
2409                label,
2410                for_token,
2411                pat: Box::new(pat),
2412                in_token,
2413                expr: Box::new(expr),
2414                body: Block { brace_token, stmts },
2415            })
2416        }
2417    }
2418
2419    #[cfg(feature = "full")]
2420    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2421    impl Parse for ExprLoop {
2422        fn parse(input: ParseStream) -> Result<Self> {
2423            let mut attrs = input.call(Attribute::parse_outer)?;
2424            let label: Option<Label> = input.parse()?;
2425            let loop_token: Token![loop] = input.parse()?;
2426
2427            let content;
2428            let brace_token = braced!(content in input);
2429            attr::parsing::parse_inner(&content, &mut attrs)?;
2430            let stmts = content.call(Block::parse_within)?;
2431
2432            Ok(ExprLoop {
2433                attrs,
2434                label,
2435                loop_token,
2436                body: Block { brace_token, stmts },
2437            })
2438        }
2439    }
2440
2441    #[cfg(feature = "full")]
2442    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2443    impl Parse for ExprMatch {
2444        fn parse(input: ParseStream) -> Result<Self> {
2445            let mut attrs = input.call(Attribute::parse_outer)?;
2446            let match_token: Token![match] = input.parse()?;
2447            let expr = Expr::parse_without_eager_brace(input)?;
2448
2449            let content;
2450            let brace_token = braced!(content in input);
2451            attr::parsing::parse_inner(&content, &mut attrs)?;
2452
2453            let arms = Arm::parse_multiple(&content)?;
2454
2455            Ok(ExprMatch {
2456                attrs,
2457                match_token,
2458                expr: Box::new(expr),
2459                brace_token,
2460                arms,
2461            })
2462        }
2463    }
2464
2465    macro_rules! impl_by_parsing_expr {
2466        (
2467            $(
2468                $expr_type:ty, $variant:ident, $msg:expr,
2469            )*
2470        ) => {
2471            $(
2472                #[cfg(all(feature = "full", feature = "printing"))]
2473                #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2474                impl Parse for $expr_type {
2475                    fn parse(input: ParseStream) -> Result<Self> {
2476                        let mut expr: Expr = input.parse()?;
2477                        loop {
2478                            match expr {
2479                                Expr::$variant(inner) => return Ok(inner),
2480                                Expr::Group(next) => expr = *next.expr,
2481                                _ => return Err(Error::new_spanned(expr, $msg)),
2482                            }
2483                        }
2484                    }
2485                }
2486            )*
2487        };
2488    }
2489
2490    impl_by_parsing_expr! {
2491        ExprAssign, Assign, "expected assignment expression",
2492        ExprAwait, Await, "expected await expression",
2493        ExprBinary, Binary, "expected binary operation",
2494        ExprCall, Call, "expected function call expression",
2495        ExprCast, Cast, "expected cast expression",
2496        ExprField, Field, "expected struct field access",
2497        ExprIndex, Index, "expected indexing expression",
2498        ExprMethodCall, MethodCall, "expected method call expression",
2499        ExprRange, Range, "expected range expression",
2500        ExprTry, Try, "expected try expression",
2501        ExprTuple, Tuple, "expected tuple expression",
2502    }
2503
2504    #[cfg(feature = "full")]
2505    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2506    impl Parse for ExprUnary {
2507        fn parse(input: ParseStream) -> Result<Self> {
2508            let attrs = Vec::new();
2509            let allow_struct = AllowStruct(true);
2510            expr_unary(input, attrs, allow_struct)
2511        }
2512    }
2513
2514    #[cfg(feature = "full")]
2515    fn expr_unary(
2516        input: ParseStream,
2517        attrs: Vec<Attribute>,
2518        allow_struct: AllowStruct,
2519    ) -> Result<ExprUnary> {
2520        Ok(ExprUnary {
2521            attrs,
2522            op: input.parse()?,
2523            expr: Box::new(unary_expr(input, allow_struct)?),
2524        })
2525    }
2526
2527    #[cfg(feature = "full")]
2528    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2529    impl Parse for ExprClosure {
2530        fn parse(input: ParseStream) -> Result<Self> {
2531            let allow_struct = AllowStruct(true);
2532            expr_closure(input, allow_struct)
2533        }
2534    }
2535
2536    #[cfg(feature = "full")]
2537    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2538    impl Parse for ExprRawAddr {
2539        fn parse(input: ParseStream) -> Result<Self> {
2540            let allow_struct = AllowStruct(true);
2541            Ok(ExprRawAddr {
2542                attrs: Vec::new(),
2543                and_token: input.parse()?,
2544                raw: input.parse()?,
2545                mutability: input.parse()?,
2546                expr: Box::new(unary_expr(input, allow_struct)?),
2547            })
2548        }
2549    }
2550
2551    #[cfg(feature = "full")]
2552    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2553    impl Parse for ExprReference {
2554        fn parse(input: ParseStream) -> Result<Self> {
2555            let allow_struct = AllowStruct(true);
2556            Ok(ExprReference {
2557                attrs: Vec::new(),
2558                and_token: input.parse()?,
2559                mutability: input.parse()?,
2560                expr: Box::new(unary_expr(input, allow_struct)?),
2561            })
2562        }
2563    }
2564
2565    #[cfg(feature = "full")]
2566    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2567    impl Parse for ExprBreak {
2568        fn parse(input: ParseStream) -> Result<Self> {
2569            let allow_struct = AllowStruct(true);
2570            expr_break(input, allow_struct)
2571        }
2572    }
2573
2574    #[cfg(feature = "full")]
2575    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2576    impl Parse for ExprReturn {
2577        fn parse(input: ParseStream) -> Result<Self> {
2578            Ok(ExprReturn {
2579                attrs: Vec::new(),
2580                return_token: input.parse()?,
2581                expr: {
2582                    if Expr::peek(input) {
2583                        Some(input.parse()?)
2584                    } else {
2585                        None
2586                    }
2587                },
2588            })
2589        }
2590    }
2591
2592    #[cfg(feature = "full")]
2593    fn expr_become(input: ParseStream) -> Result<Expr> {
2594        let begin = input.cursor();
2595        input.parse::<Token![become]>()?;
2596        input.parse::<Expr>()?;
2597        Ok(Expr::Verbatim(verbatim::between(begin, input.cursor())))
2598    }
2599
2600    #[cfg(feature = "full")]
2601    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2602    impl Parse for ExprTryBlock {
2603        fn parse(input: ParseStream) -> Result<Self> {
2604            Ok(ExprTryBlock {
2605                attrs: Vec::new(),
2606                try_token: input.parse()?,
2607                modifiers: BlockModifiers {},
2608                block: input.parse()?,
2609            })
2610        }
2611    }
2612
2613    #[cfg(feature = "full")]
2614    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2615    impl Parse for ExprYield {
2616        fn parse(input: ParseStream) -> Result<Self> {
2617            Ok(ExprYield {
2618                attrs: Vec::new(),
2619                yield_token: input.parse()?,
2620                expr: {
2621                    if Expr::peek(input) {
2622                        Some(input.parse()?)
2623                    } else {
2624                        None
2625                    }
2626                },
2627            })
2628        }
2629    }
2630
2631    #[cfg(feature = "full")]
2632    fn expr_closure(input: ParseStream, allow_struct: AllowStruct) -> Result<ExprClosure> {
2633        let lifetimes: Option<BoundLifetimes> = input.parse()?;
2634        let constness: Option<Token![const]> = input.parse()?;
2635        let asyncness: Option<Token![async]> = input.parse()?;
2636        let capture: Option<Token![move]> = input.parse()?;
2637        let inputs_begin: Token![|] = input.parse()?;
2638
2639        let mut inputs = Punctuated::new();
2640        loop {
2641            if input.peek(Token![|]) {
2642                break;
2643            }
2644            let value = closure_arg(input)?;
2645            inputs.push_value(value);
2646            if input.peek(Token![|]) {
2647                break;
2648            }
2649            let punct: Token![,] = input.parse()?;
2650            inputs.push_punct(punct);
2651        }
2652
2653        let inputs_end: Token![|] = input.parse()?;
2654
2655        let (output, body) = if input.peek(Token![->]) {
2656            let arrow_token: Token![->] = input.parse()?;
2657            let ty: Type = input.parse()?;
2658            let body: Block = input.parse()?;
2659            let output = ReturnType::Type(arrow_token, Box::new(ty));
2660            let block = Expr::Block(ExprBlock {
2661                attrs: Vec::new(),
2662                label: None,
2663                block: body,
2664            });
2665            (output, block)
2666        } else {
2667            let body = ambiguous_expr(input, allow_struct)?;
2668            (ReturnType::Default, body)
2669        };
2670
2671        Ok(ExprClosure {
2672            attrs: Vec::new(),
2673            lifetimes,
2674            modifiers: ClosureModifiers {},
2675            constness,
2676            asyncness,
2677            capture,
2678            inputs_begin,
2679            inputs,
2680            inputs_end,
2681            output,
2682            body: Box::new(body),
2683        })
2684    }
2685
2686    #[cfg(feature = "full")]
2687    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2688    impl Parse for ExprAsync {
2689        fn parse(input: ParseStream) -> Result<Self> {
2690            Ok(ExprAsync {
2691                attrs: Vec::new(),
2692                async_token: input.parse()?,
2693                capture: input.parse()?,
2694                modifiers: BlockModifiers {},
2695                block: input.parse()?,
2696            })
2697        }
2698    }
2699
2700    #[cfg(feature = "full")]
2701    fn closure_arg(input: ParseStream) -> Result<Pat> {
2702        let attrs = input.call(Attribute::parse_outer)?;
2703        let mut pat = Pat::parse_single(input)?;
2704
2705        if input.peek(Token![:]) {
2706            Ok(Pat::Type(PatType {
2707                attrs,
2708                pat: Box::new(pat),
2709                colon_token: input.parse()?,
2710                ty: input.parse()?,
2711            }))
2712        } else {
2713            match &mut pat {
2714                Pat::Const(pat) => pat.attrs = attrs,
2715                Pat::Guard(_) => unreachable!(),
2716                Pat::Ident(pat) => pat.attrs = attrs,
2717                Pat::Lit(pat) => pat.attrs = attrs,
2718                Pat::Macro(pat) => pat.attrs = attrs,
2719                Pat::Or(pat) => pat.attrs = attrs,
2720                Pat::Paren(pat) => pat.attrs = attrs,
2721                Pat::Path(pat) => pat.attrs = attrs,
2722                Pat::Range(pat) => pat.attrs = attrs,
2723                Pat::Reference(pat) => pat.attrs = attrs,
2724                Pat::Rest(pat) => pat.attrs = attrs,
2725                Pat::Slice(pat) => pat.attrs = attrs,
2726                Pat::Struct(pat) => pat.attrs = attrs,
2727                Pat::Tuple(pat) => pat.attrs = attrs,
2728                Pat::TupleStruct(pat) => pat.attrs = attrs,
2729                Pat::Type(_) => unreachable!(),
2730                Pat::Verbatim(_) => {}
2731                Pat::Wild(pat) => pat.attrs = attrs,
2732            }
2733            Ok(pat)
2734        }
2735    }
2736
2737    #[cfg(feature = "full")]
2738    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2739    impl Parse for ExprWhile {
2740        fn parse(input: ParseStream) -> Result<Self> {
2741            let mut attrs = input.call(Attribute::parse_outer)?;
2742            let label: Option<Label> = input.parse()?;
2743            let while_token: Token![while] = input.parse()?;
2744            let cond = Expr::parse_without_eager_brace(input)?;
2745
2746            let content;
2747            let brace_token = braced!(content in input);
2748            attr::parsing::parse_inner(&content, &mut attrs)?;
2749            let stmts = content.call(Block::parse_within)?;
2750
2751            Ok(ExprWhile {
2752                attrs,
2753                label,
2754                while_token,
2755                cond: Box::new(cond),
2756                body: Block { brace_token, stmts },
2757            })
2758        }
2759    }
2760
2761    #[cfg(feature = "full")]
2762    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2763    impl Parse for ExprConst {
2764        fn parse(input: ParseStream) -> Result<Self> {
2765            let const_token: Token![const] = input.parse()?;
2766
2767            let content;
2768            let brace_token = braced!(content in input);
2769            let inner_attrs = content.call(Attribute::parse_inner)?;
2770            let stmts = content.call(Block::parse_within)?;
2771
2772            Ok(ExprConst {
2773                attrs: inner_attrs,
2774                const_token,
2775                modifiers: BlockModifiers {},
2776                block: Block { brace_token, stmts },
2777            })
2778        }
2779    }
2780
2781    #[cfg(feature = "full")]
2782    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2783    impl Parse for Label {
2784        fn parse(input: ParseStream) -> Result<Self> {
2785            Ok(Label {
2786                name: Lifetime::parse_any(input)?,
2787                colon_token: input.parse()?,
2788            })
2789        }
2790    }
2791
2792    #[cfg(feature = "full")]
2793    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2794    impl Parse for Option<Label> {
2795        fn parse(input: ParseStream) -> Result<Self> {
2796            if input.peek(Lifetime) {
2797                input.parse().map(Some)
2798            } else {
2799                Ok(None)
2800            }
2801        }
2802    }
2803
2804    #[cfg(feature = "full")]
2805    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2806    impl Parse for ExprContinue {
2807        fn parse(input: ParseStream) -> Result<Self> {
2808            Ok(ExprContinue {
2809                attrs: Vec::new(),
2810                continue_token: input.parse()?,
2811                label: Lifetime::parse_optional_any(input),
2812            })
2813        }
2814    }
2815
2816    #[cfg(feature = "full")]
2817    fn expr_break(input: ParseStream, allow_struct: AllowStruct) -> Result<ExprBreak> {
2818        let break_token: Token![break] = input.parse()?;
2819
2820        let ahead = input.fork();
2821        let label = Lifetime::parse_optional_any(&ahead);
2822        if label.is_some() && ahead.peek(Token![:]) {
2823            // Not allowed: `break 'label: loop {...}`
2824            // Parentheses are required. `break ('label: loop {...})`
2825            let _: Expr = input.parse()?;
2826            let start_span = label.unwrap().apostrophe;
2827            let end_span = input.cursor().prev_span();
2828            return Err(crate::error::new2(
2829                start_span,
2830                end_span,
2831                "parentheses required",
2832            ));
2833        }
2834
2835        input.advance_to(&ahead);
2836        let expr = if Expr::peek(input) && (allow_struct.0 || !input.peek(token::Brace)) {
2837            Some(input.parse()?)
2838        } else {
2839            None
2840        };
2841
2842        Ok(ExprBreak {
2843            attrs: Vec::new(),
2844            break_token,
2845            label,
2846            expr,
2847        })
2848    }
2849
2850    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2851    impl Parse for FieldValue {
2852        fn parse(input: ParseStream) -> Result<Self> {
2853            let attrs = input.call(Attribute::parse_outer)?;
2854            let member: Member = input.parse()?;
2855            let (colon_token, value) = if input.peek(Token![:]) || !member.is_named() {
2856                let colon_token: Token![:] = input.parse()?;
2857                let value: Expr = input.parse()?;
2858                (Some(colon_token), value)
2859            } else if let Member::Named(ident) = &member {
2860                let value = Expr::Path(ExprPath {
2861                    attrs: Vec::new(),
2862                    qself: None,
2863                    path: Path::from(ident.clone()),
2864                });
2865                (None, value)
2866            } else {
2867                unreachable!()
2868            };
2869
2870            Ok(FieldValue {
2871                attrs,
2872                member,
2873                colon_token,
2874                expr: value,
2875            })
2876        }
2877    }
2878
2879    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2880    impl Parse for ExprStruct {
2881        fn parse(input: ParseStream) -> Result<Self> {
2882            let expr_style = true;
2883            let (qself, path) = path::parsing::qpath(input, expr_style)?;
2884            expr_struct_helper(input, qself, path)
2885        }
2886    }
2887
2888    fn expr_struct_helper(
2889        input: ParseStream,
2890        qself: Option<QSelf>,
2891        path: Path,
2892    ) -> Result<ExprStruct> {
2893        let content;
2894        let brace_token = braced!(content in input);
2895
2896        let mut fields = Punctuated::new();
2897        while !content.is_empty() {
2898            if content.peek(Token![..]) {
2899                return Ok(ExprStruct {
2900                    attrs: Vec::new(),
2901                    qself,
2902                    path,
2903                    brace_token,
2904                    fields,
2905                    dot2_token: Some(content.parse()?),
2906                    rest: if content.is_empty() {
2907                        None
2908                    } else {
2909                        Some(Box::new(content.parse()?))
2910                    },
2911                });
2912            }
2913
2914            fields.push(content.parse()?);
2915            if content.is_empty() {
2916                break;
2917            }
2918            let punct: Token![,] = content.parse()?;
2919            fields.push_punct(punct);
2920        }
2921
2922        Ok(ExprStruct {
2923            attrs: Vec::new(),
2924            qself,
2925            path,
2926            brace_token,
2927            fields,
2928            dot2_token: None,
2929            rest: None,
2930        })
2931    }
2932
2933    #[cfg(feature = "full")]
2934    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2935    impl Parse for ExprUnsafe {
2936        fn parse(input: ParseStream) -> Result<Self> {
2937            let unsafe_token: Token![unsafe] = input.parse()?;
2938
2939            let content;
2940            let brace_token = braced!(content in input);
2941            let inner_attrs = content.call(Attribute::parse_inner)?;
2942            let stmts = content.call(Block::parse_within)?;
2943
2944            Ok(ExprUnsafe {
2945                attrs: inner_attrs,
2946                unsafe_token,
2947                block: Block { brace_token, stmts },
2948            })
2949        }
2950    }
2951
2952    #[cfg(feature = "full")]
2953    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2954    impl Parse for ExprBlock {
2955        fn parse(input: ParseStream) -> Result<Self> {
2956            let mut attrs = input.call(Attribute::parse_outer)?;
2957            let label: Option<Label> = input.parse()?;
2958
2959            let content;
2960            let brace_token = braced!(content in input);
2961            attr::parsing::parse_inner(&content, &mut attrs)?;
2962            let stmts = content.call(Block::parse_within)?;
2963
2964            Ok(ExprBlock {
2965                attrs,
2966                label,
2967                block: Block { brace_token, stmts },
2968            })
2969        }
2970    }
2971
2972    #[cfg(feature = "full")]
2973    fn expr_range(input: ParseStream, allow_struct: AllowStruct) -> Result<ExprRange> {
2974        let limits: RangeLimits = input.parse()?;
2975        let end = parse_range_end(input, &limits, allow_struct)?;
2976        Ok(ExprRange {
2977            attrs: Vec::new(),
2978            start: None,
2979            limits,
2980            end,
2981        })
2982    }
2983
2984    #[cfg(feature = "full")]
2985    fn parse_range_end(
2986        input: ParseStream,
2987        limits: &RangeLimits,
2988        allow_struct: AllowStruct,
2989    ) -> Result<Option<Box<Expr>>> {
2990        if matches!(limits, RangeLimits::HalfOpen(_))
2991            && (input.is_empty()
2992                || input.peek(Token![,])
2993                || input.peek(Token![;])
2994                || input.peek(Token![.]) && !input.peek(Token![..])
2995                || input.peek(Token![?])
2996                || input.peek(Token![=>])
2997                || !allow_struct.0 && input.peek(token::Brace)
2998                || input.peek(Token![=])
2999                || input.peek(Token![+])
3000                || input.peek(Token![/])
3001                || input.peek(Token![%])
3002                || input.peek(Token![^])
3003                || input.peek(Token![>])
3004                || input.peek(Token![<=])
3005                || input.peek(Token![!=])
3006                || input.peek(Token![-=])
3007                || input.peek(Token![*=])
3008                || input.peek(Token![&=])
3009                || input.peek(Token![|=])
3010                || input.peek(Token![<<=])
3011                || input.peek(Token![as]))
3012        {
3013            Ok(None)
3014        } else {
3015            let end = parse_binop_rhs(input, allow_struct, Precedence::Range)?;
3016            Ok(Some(end))
3017        }
3018    }
3019
3020    #[cfg(feature = "full")]
3021    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
3022    impl Parse for RangeLimits {
3023        fn parse(input: ParseStream) -> Result<Self> {
3024            let lookahead = input.lookahead1();
3025            let dot_dot = lookahead.peek(Token![..]);
3026            let dot_dot_eq = dot_dot && lookahead.peek(Token![..=]);
3027            let dot_dot_dot = dot_dot && input.peek(Token![...]);
3028            if dot_dot_eq {
3029                input.parse().map(RangeLimits::Closed)
3030            } else if dot_dot && !dot_dot_dot {
3031                input.parse().map(RangeLimits::HalfOpen)
3032            } else {
3033                Err(lookahead.error())
3034            }
3035        }
3036    }
3037
3038    #[cfg(feature = "full")]
3039    impl RangeLimits {
3040        pub(crate) fn parse_obsolete(input: ParseStream) -> Result<Self> {
3041            let lookahead = input.lookahead1();
3042            let dot_dot = lookahead.peek(Token![..]);
3043            let dot_dot_eq = dot_dot && lookahead.peek(Token![..=]);
3044            let dot_dot_dot = dot_dot && input.peek(Token![...]);
3045            if dot_dot_eq {
3046                input.parse().map(RangeLimits::Closed)
3047            } else if dot_dot_dot {
3048                let dot3: Token![...] = input.parse()?;
3049                Ok(RangeLimits::Closed(Token![..=](dot3.spans)))
3050            } else if dot_dot {
3051                input.parse().map(RangeLimits::HalfOpen)
3052            } else {
3053                Err(lookahead.error())
3054            }
3055        }
3056    }
3057
3058    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
3059    impl Parse for ExprPath {
3060        fn parse(input: ParseStream) -> Result<Self> {
3061            #[cfg(not(feature = "full"))]
3062            let attrs = Vec::new();
3063            #[cfg(feature = "full")]
3064            let attrs = input.call(Attribute::parse_outer)?;
3065
3066            let expr_style = true;
3067            let (qself, path) = path::parsing::qpath(input, expr_style)?;
3068
3069            Ok(ExprPath { attrs, qself, path })
3070        }
3071    }
3072
3073    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
3074    impl Parse for Member {
3075        fn parse(input: ParseStream) -> Result<Self> {
3076            if input.peek(Ident) {
3077                input.parse().map(Member::Named)
3078            } else if input.peek(LitInt) {
3079                input.parse().map(Member::Unnamed)
3080            } else {
3081                Err(input.error("expected identifier or integer"))
3082            }
3083        }
3084    }
3085
3086    #[cfg(feature = "full")]
3087    impl Arm {
3088        pub(crate) fn parse_multiple(input: ParseStream) -> Result<Vec<Self>> {
3089            let mut arms = Vec::new();
3090            while !input.is_empty() {
3091                arms.push(input.call(Arm::parse)?);
3092            }
3093            Ok(arms)
3094        }
3095    }
3096
3097    #[cfg(feature = "full")]
3098    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
3099    impl Parse for Arm {
3100        fn parse(input: ParseStream) -> Result<Arm> {
3101            let requires_comma;
3102            Ok(Arm {
3103                attrs: input.call(Attribute::parse_outer)?,
3104                pat: Pat::parse_multi_with_leading_vert_and_guard(input)?,
3105                fat_arrow_token: input.parse()?,
3106                body: {
3107                    let body = Expr::parse_with_earlier_boundary_rule(input)?;
3108                    requires_comma = classify::requires_comma_to_be_match_arm(&body);
3109                    Box::new(body)
3110                },
3111                comma: {
3112                    if requires_comma && !input.is_empty() {
3113                        Some(input.parse()?)
3114                    } else {
3115                        input.parse()?
3116                    }
3117                },
3118            })
3119        }
3120    }
3121
3122    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
3123    impl Parse for Index {
3124        fn parse(input: ParseStream) -> Result<Self> {
3125            let lit: LitInt = input.parse()?;
3126            if lit.suffix().is_empty() {
3127                Ok(Index {
3128                    index: lit
3129                        .base10_digits()
3130                        .parse()
3131                        .map_err(|err| Error::new(lit.span(), err))?,
3132                    span: lit.span(),
3133                })
3134            } else {
3135                Err(Error::new(lit.span(), "expected unsuffixed integer"))
3136            }
3137        }
3138    }
3139
3140    fn multi_index(e: &mut Expr, dot_token: &mut Token![.], float: LitFloat) -> Result<bool> {
3141        let float_token = float.token();
3142        let float_span = float_token.span();
3143        let mut float_repr = float_token.to_string();
3144        let trailing_dot = float_repr.ends_with('.');
3145        if trailing_dot {
3146            float_repr.truncate(float_repr.len() - 1);
3147        }
3148
3149        let mut offset = 0;
3150        for part in float_repr.split('.') {
3151            let mut index: Index =
3152                crate::parse_str(part).map_err(|err| Error::new(float_span, err))?;
3153            let part_end = offset + part.len();
3154            index.span = float_token.subspan(offset..part_end).unwrap_or(float_span);
3155
3156            let base = mem::replace(e, Expr::PLACEHOLDER);
3157            *e = Expr::Field(ExprField {
3158                attrs: Vec::new(),
3159                base: Box::new(base),
3160                dot_token: Token![.](dot_token.span),
3161                member: Member::Unnamed(index),
3162            });
3163
3164            let dot_span = float_token
3165                .subspan(part_end..part_end + 1)
3166                .unwrap_or(float_span);
3167            *dot_token = Token![.](dot_span);
3168            offset = part_end + 1;
3169        }
3170
3171        Ok(!trailing_dot)
3172    }
3173
3174    fn check_cast(input: ParseStream) -> Result<()> {
3175        let kind = if input.peek(Token![.]) && !input.peek(Token![..]) {
3176            if input.peek2(Token![await]) {
3177                "`.await`"
3178            } else if input.peek2(Ident) && (input.peek3(token::Paren) || input.peek3(Token![::])) {
3179                "a method call"
3180            } else {
3181                "a field access"
3182            }
3183        } else if input.peek(Token![?]) {
3184            "`?`"
3185        } else if input.peek(token::Bracket) {
3186            "indexing"
3187        } else if input.peek(token::Paren) {
3188            "a function call"
3189        } else {
3190            return Ok(());
3191        };
3192        let msg = format!("casts cannot be followed by {}", kind);
3193        Err(input.error(msg))
3194    }
3195}
3196
3197#[cfg(feature = "printing")]
3198pub(crate) mod printing {
3199    use crate::attr::Attribute;
3200    #[cfg(feature = "full")]
3201    use crate::attr::FilterAttrs;
3202    #[cfg(feature = "full")]
3203    use crate::classify;
3204    #[cfg(feature = "full")]
3205    use crate::expr::{
3206        Arm, ExprArray, ExprAssign, ExprAsync, ExprAwait, ExprBlock, ExprBreak, ExprClosure,
3207        ExprConst, ExprContinue, ExprForLoop, ExprIf, ExprInfer, ExprLet, ExprLoop, ExprMatch,
3208        ExprRange, ExprRawAddr, ExprRepeat, ExprReturn, ExprTry, ExprTryBlock, ExprUnsafe,
3209        ExprWhile, ExprYield, Label, RangeLimits,
3210    };
3211    use crate::expr::{
3212        Expr, ExprBinary, ExprCall, ExprCast, ExprField, ExprGroup, ExprIndex, ExprLit, ExprMacro,
3213        ExprMethodCall, ExprParen, ExprPath, ExprReference, ExprStruct, ExprTuple, ExprUnary,
3214        FieldValue, Index, Member,
3215    };
3216    use crate::fixup::FixupContext;
3217    use crate::op::BinOp;
3218    use crate::path;
3219    use crate::path::printing::PathStyle;
3220    use crate::precedence::Precedence;
3221    use crate::token;
3222    #[cfg(feature = "full")]
3223    use crate::ty::ReturnType;
3224    use proc_macro2::{Literal, Span, TokenStream};
3225    use quote::{ToTokens, TokenStreamExt as _};
3226
3227    #[cfg(feature = "full")]
3228    pub(crate) fn outer_attrs_to_tokens(attrs: &[Attribute], tokens: &mut TokenStream) {
3229        tokens.append_all(attrs.outer());
3230    }
3231
3232    #[cfg(feature = "full")]
3233    fn inner_attrs_to_tokens(attrs: &[Attribute], tokens: &mut TokenStream) {
3234        tokens.append_all(attrs.inner());
3235    }
3236
3237    #[cfg(not(feature = "full"))]
3238    pub(crate) fn outer_attrs_to_tokens(_attrs: &[Attribute], _tokens: &mut TokenStream) {}
3239
3240    pub(crate) fn print_subexpression(
3241        expr: &Expr,
3242        needs_group: bool,
3243        tokens: &mut TokenStream,
3244        mut fixup: FixupContext,
3245    ) {
3246        if needs_group {
3247            // If we are surrounding the whole cond in parentheses, such as:
3248            //
3249            //     if (return Struct {}) {}
3250            //
3251            // then there is no need for parenthesizing the individual struct
3252            // expressions within. On the other hand if the whole cond is not
3253            // parenthesized, then print_expr must parenthesize exterior struct
3254            // literals.
3255            //
3256            //     if x == (Struct {}) {}
3257            //
3258            fixup = FixupContext::NONE;
3259        }
3260
3261        let do_print_expr = |tokens: &mut TokenStream| print_expr(expr, tokens, fixup);
3262
3263        if needs_group {
3264            token::Paren::default().surround(tokens, do_print_expr);
3265        } else {
3266            do_print_expr(tokens);
3267        }
3268    }
3269
3270    pub(crate) fn print_expr(expr: &Expr, tokens: &mut TokenStream, mut fixup: FixupContext) {
3271        #[cfg(feature = "full")]
3272        let needs_group = fixup.parenthesize(expr);
3273        #[cfg(not(feature = "full"))]
3274        let needs_group = false;
3275
3276        if needs_group {
3277            fixup = FixupContext::NONE;
3278        }
3279
3280        let do_print_expr = |tokens: &mut TokenStream| match expr {
3281            #[cfg(feature = "full")]
3282            Expr::Array(e) => e.to_tokens(tokens),
3283            #[cfg(feature = "full")]
3284            Expr::Assign(e) => print_expr_assign(e, tokens, fixup),
3285            #[cfg(feature = "full")]
3286            Expr::Async(e) => e.to_tokens(tokens),
3287            #[cfg(feature = "full")]
3288            Expr::Await(e) => print_expr_await(e, tokens, fixup),
3289            Expr::Binary(e) => print_expr_binary(e, tokens, fixup),
3290            #[cfg(feature = "full")]
3291            Expr::Block(e) => e.to_tokens(tokens),
3292            #[cfg(feature = "full")]
3293            Expr::Break(e) => print_expr_break(e, tokens, fixup),
3294            Expr::Call(e) => print_expr_call(e, tokens, fixup),
3295            Expr::Cast(e) => print_expr_cast(e, tokens, fixup),
3296            #[cfg(feature = "full")]
3297            Expr::Closure(e) => print_expr_closure(e, tokens, fixup),
3298            #[cfg(feature = "full")]
3299            Expr::Const(e) => e.to_tokens(tokens),
3300            #[cfg(feature = "full")]
3301            Expr::Continue(e) => e.to_tokens(tokens),
3302            Expr::Field(e) => print_expr_field(e, tokens, fixup),
3303            #[cfg(feature = "full")]
3304            Expr::ForLoop(e) => e.to_tokens(tokens),
3305            Expr::Group(e) => e.to_tokens(tokens),
3306            #[cfg(feature = "full")]
3307            Expr::If(e) => e.to_tokens(tokens),
3308            Expr::Index(e) => print_expr_index(e, tokens, fixup),
3309            #[cfg(feature = "full")]
3310            Expr::Infer(e) => e.to_tokens(tokens),
3311            #[cfg(feature = "full")]
3312            Expr::Let(e) => print_expr_let(e, tokens, fixup),
3313            Expr::Lit(e) => e.to_tokens(tokens),
3314            #[cfg(feature = "full")]
3315            Expr::Loop(e) => e.to_tokens(tokens),
3316            Expr::Macro(e) => e.to_tokens(tokens),
3317            #[cfg(feature = "full")]
3318            Expr::Match(e) => e.to_tokens(tokens),
3319            Expr::MethodCall(e) => print_expr_method_call(e, tokens, fixup),
3320            Expr::Paren(e) => e.to_tokens(tokens),
3321            Expr::Path(e) => e.to_tokens(tokens),
3322            #[cfg(feature = "full")]
3323            Expr::Range(e) => print_expr_range(e, tokens, fixup),
3324            #[cfg(feature = "full")]
3325            Expr::RawAddr(e) => print_expr_raw_addr(e, tokens, fixup),
3326            Expr::Reference(e) => print_expr_reference(e, tokens, fixup),
3327            #[cfg(feature = "full")]
3328            Expr::Repeat(e) => e.to_tokens(tokens),
3329            #[cfg(feature = "full")]
3330            Expr::Return(e) => print_expr_return(e, tokens, fixup),
3331            Expr::Struct(e) => e.to_tokens(tokens),
3332            #[cfg(feature = "full")]
3333            Expr::Try(e) => print_expr_try(e, tokens, fixup),
3334            #[cfg(feature = "full")]
3335            Expr::TryBlock(e) => e.to_tokens(tokens),
3336            Expr::Tuple(e) => e.to_tokens(tokens),
3337            Expr::Unary(e) => print_expr_unary(e, tokens, fixup),
3338            #[cfg(feature = "full")]
3339            Expr::Unsafe(e) => e.to_tokens(tokens),
3340            Expr::Verbatim(e) => e.to_tokens(tokens),
3341            #[cfg(feature = "full")]
3342            Expr::While(e) => e.to_tokens(tokens),
3343            #[cfg(feature = "full")]
3344            Expr::Yield(e) => print_expr_yield(e, tokens, fixup),
3345
3346            #[cfg(not(feature = "full"))]
3347            _ => unreachable!(),
3348        };
3349
3350        if needs_group {
3351            token::Paren::default().surround(tokens, do_print_expr);
3352        } else {
3353            do_print_expr(tokens);
3354        }
3355    }
3356
3357    #[cfg(feature = "full")]
3358    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3359    impl ToTokens for ExprArray {
3360        fn to_tokens(&self, tokens: &mut TokenStream) {
3361            outer_attrs_to_tokens(&self.attrs, tokens);
3362            self.bracket_token.surround(tokens, |tokens| {
3363                self.elems.to_tokens(tokens);
3364            });
3365        }
3366    }
3367
3368    #[cfg(feature = "full")]
3369    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3370    impl ToTokens for ExprAssign {
3371        fn to_tokens(&self, tokens: &mut TokenStream) {
3372            print_expr_assign(self, tokens, FixupContext::NONE);
3373        }
3374    }
3375
3376    #[cfg(feature = "full")]
3377    fn print_expr_assign(e: &ExprAssign, tokens: &mut TokenStream, mut fixup: FixupContext) {
3378        outer_attrs_to_tokens(&e.attrs, tokens);
3379
3380        let needs_group = !e.attrs.is_empty();
3381        if needs_group {
3382            fixup = FixupContext::NONE;
3383        }
3384
3385        let do_print_expr = |tokens: &mut TokenStream| {
3386            let (left_prec, left_fixup) = fixup.leftmost_subexpression_with_operator(
3387                &e.left,
3388                false,
3389                false,
3390                Precedence::Assign,
3391            );
3392            print_subexpression(&e.left, left_prec <= Precedence::Range, tokens, left_fixup);
3393            e.eq_token.to_tokens(tokens);
3394            print_expr(
3395                &e.right,
3396                tokens,
3397                fixup.rightmost_subexpression_fixup(false, false, Precedence::Assign),
3398            );
3399        };
3400
3401        if needs_group {
3402            token::Paren::default().surround(tokens, do_print_expr);
3403        } else {
3404            do_print_expr(tokens);
3405        }
3406    }
3407
3408    #[cfg(feature = "full")]
3409    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3410    impl ToTokens for ExprAsync {
3411        fn to_tokens(&self, tokens: &mut TokenStream) {
3412            outer_attrs_to_tokens(&self.attrs, tokens);
3413            self.async_token.to_tokens(tokens);
3414            self.capture.to_tokens(tokens);
3415            self.block.to_tokens(tokens);
3416        }
3417    }
3418
3419    #[cfg(feature = "full")]
3420    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3421    impl ToTokens for ExprAwait {
3422        fn to_tokens(&self, tokens: &mut TokenStream) {
3423            print_expr_await(self, tokens, FixupContext::NONE);
3424        }
3425    }
3426
3427    #[cfg(feature = "full")]
3428    fn print_expr_await(e: &ExprAwait, tokens: &mut TokenStream, fixup: FixupContext) {
3429        outer_attrs_to_tokens(&e.attrs, tokens);
3430        let (left_prec, left_fixup) = fixup.leftmost_subexpression_with_dot(&e.base);
3431        print_subexpression(
3432            &e.base,
3433            left_prec < Precedence::Unambiguous,
3434            tokens,
3435            left_fixup,
3436        );
3437        e.dot_token.to_tokens(tokens);
3438        e.await_token.to_tokens(tokens);
3439    }
3440
3441    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3442    impl ToTokens for ExprBinary {
3443        fn to_tokens(&self, tokens: &mut TokenStream) {
3444            print_expr_binary(self, tokens, FixupContext::NONE);
3445        }
3446    }
3447
3448    fn print_expr_binary(e: &ExprBinary, tokens: &mut TokenStream, mut fixup: FixupContext) {
3449        outer_attrs_to_tokens(&e.attrs, tokens);
3450
3451        let needs_group = !e.attrs.is_empty();
3452        if needs_group {
3453            fixup = FixupContext::NONE;
3454        }
3455
3456        let do_print_expr = |tokens: &mut TokenStream| {
3457            let binop_prec = Precedence::of_binop(&e.op);
3458            let (left_prec, left_fixup) = fixup.leftmost_subexpression_with_operator(
3459                &e.left,
3460                #[cfg(feature = "full")]
3461                match &e.op {
3462                    BinOp::Sub(_)
3463                    | BinOp::Mul(_)
3464                    | BinOp::And(_)
3465                    | BinOp::Or(_)
3466                    | BinOp::BitAnd(_)
3467                    | BinOp::BitOr(_)
3468                    | BinOp::Shl(_)
3469                    | BinOp::Lt(_) => true,
3470                    _ => false,
3471                },
3472                match &e.op {
3473                    BinOp::Shl(_) | BinOp::Lt(_) => true,
3474                    _ => false,
3475                },
3476                #[cfg(feature = "full")]
3477                binop_prec,
3478            );
3479            let left_needs_group = match binop_prec {
3480                Precedence::Assign => left_prec <= Precedence::Range,
3481                Precedence::Compare => left_prec <= binop_prec,
3482                _ => left_prec < binop_prec,
3483            };
3484
3485            let right_fixup = fixup.rightmost_subexpression_fixup(
3486                #[cfg(feature = "full")]
3487                false,
3488                #[cfg(feature = "full")]
3489                false,
3490                #[cfg(feature = "full")]
3491                binop_prec,
3492            );
3493            let right_needs_group = binop_prec != Precedence::Assign
3494                && right_fixup.rightmost_subexpression_precedence(&e.right) <= binop_prec;
3495
3496            print_subexpression(&e.left, left_needs_group, tokens, left_fixup);
3497            e.op.to_tokens(tokens);
3498            print_subexpression(&e.right, right_needs_group, tokens, right_fixup);
3499        };
3500
3501        if needs_group {
3502            token::Paren::default().surround(tokens, do_print_expr);
3503        } else {
3504            do_print_expr(tokens);
3505        }
3506    }
3507
3508    #[cfg(feature = "full")]
3509    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3510    impl ToTokens for ExprBlock {
3511        fn to_tokens(&self, tokens: &mut TokenStream) {
3512            outer_attrs_to_tokens(&self.attrs, tokens);
3513            self.label.to_tokens(tokens);
3514            self.block.brace_token.surround(tokens, |tokens| {
3515                inner_attrs_to_tokens(&self.attrs, tokens);
3516                tokens.append_all(&self.block.stmts);
3517            });
3518        }
3519    }
3520
3521    #[cfg(feature = "full")]
3522    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3523    impl ToTokens for ExprBreak {
3524        fn to_tokens(&self, tokens: &mut TokenStream) {
3525            print_expr_break(self, tokens, FixupContext::NONE);
3526        }
3527    }
3528
3529    #[cfg(feature = "full")]
3530    fn print_expr_break(e: &ExprBreak, tokens: &mut TokenStream, fixup: FixupContext) {
3531        outer_attrs_to_tokens(&e.attrs, tokens);
3532        e.break_token.to_tokens(tokens);
3533        e.label.to_tokens(tokens);
3534        if let Some(value) = &e.expr {
3535            print_subexpression(
3536                value,
3537                // Parenthesize `break 'inner: loop { break 'inner 1 } + 1`
3538                //                     ^---------------------------------^
3539                e.label.is_none() && classify::expr_leading_label(value),
3540                tokens,
3541                fixup.rightmost_subexpression_fixup(true, true, Precedence::Jump),
3542            );
3543        }
3544    }
3545
3546    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3547    impl ToTokens for ExprCall {
3548        fn to_tokens(&self, tokens: &mut TokenStream) {
3549            print_expr_call(self, tokens, FixupContext::NONE);
3550        }
3551    }
3552
3553    fn print_expr_call(e: &ExprCall, tokens: &mut TokenStream, fixup: FixupContext) {
3554        outer_attrs_to_tokens(&e.attrs, tokens);
3555
3556        let (left_prec, left_fixup) = fixup.leftmost_subexpression_with_operator(
3557            &e.func,
3558            #[cfg(feature = "full")]
3559            true,
3560            false,
3561            #[cfg(feature = "full")]
3562            Precedence::Unambiguous,
3563        );
3564        let needs_group = if let Expr::Field(func) = &*e.func {
3565            func.member.is_named()
3566        } else {
3567            left_prec < Precedence::Unambiguous
3568        };
3569        print_subexpression(&e.func, needs_group, tokens, left_fixup);
3570
3571        e.paren_token.surround(tokens, |tokens| {
3572            e.args.to_tokens(tokens);
3573        });
3574    }
3575
3576    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3577    impl ToTokens for ExprCast {
3578        fn to_tokens(&self, tokens: &mut TokenStream) {
3579            print_expr_cast(self, tokens, FixupContext::NONE);
3580        }
3581    }
3582
3583    fn print_expr_cast(e: &ExprCast, tokens: &mut TokenStream, mut fixup: FixupContext) {
3584        outer_attrs_to_tokens(&e.attrs, tokens);
3585
3586        let needs_group = !e.attrs.is_empty();
3587        if needs_group {
3588            fixup = FixupContext::NONE;
3589        }
3590
3591        let do_print_expr = |tokens: &mut TokenStream| {
3592            let (left_prec, left_fixup) = fixup.leftmost_subexpression_with_operator(
3593                &e.expr,
3594                #[cfg(feature = "full")]
3595                false,
3596                false,
3597                #[cfg(feature = "full")]
3598                Precedence::Cast,
3599            );
3600            print_subexpression(&e.expr, left_prec < Precedence::Cast, tokens, left_fixup);
3601            e.as_token.to_tokens(tokens);
3602            e.ty.to_tokens(tokens);
3603        };
3604
3605        if needs_group {
3606            token::Paren::default().surround(tokens, do_print_expr);
3607        } else {
3608            do_print_expr(tokens);
3609        }
3610    }
3611
3612    #[cfg(feature = "full")]
3613    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3614    impl ToTokens for ExprClosure {
3615        fn to_tokens(&self, tokens: &mut TokenStream) {
3616            print_expr_closure(self, tokens, FixupContext::NONE);
3617        }
3618    }
3619
3620    #[cfg(feature = "full")]
3621    fn print_expr_closure(e: &ExprClosure, tokens: &mut TokenStream, fixup: FixupContext) {
3622        outer_attrs_to_tokens(&e.attrs, tokens);
3623        e.lifetimes.to_tokens(tokens);
3624        e.constness.to_tokens(tokens);
3625        e.asyncness.to_tokens(tokens);
3626        e.capture.to_tokens(tokens);
3627        e.inputs_begin.to_tokens(tokens);
3628        e.inputs.to_tokens(tokens);
3629        e.inputs_end.to_tokens(tokens);
3630        e.output.to_tokens(tokens);
3631        if matches!(e.output, ReturnType::Default)
3632            || matches!(&*e.body, Expr::Block(body) if body.attrs.is_empty() && body.label.is_none())
3633        {
3634            print_expr(
3635                &e.body,
3636                tokens,
3637                fixup.rightmost_subexpression_fixup(false, false, Precedence::Jump),
3638            );
3639        } else {
3640            token::Brace::default().surround(tokens, |tokens| {
3641                print_expr(&e.body, tokens, FixupContext::new_stmt());
3642            });
3643        }
3644    }
3645
3646    #[cfg(feature = "full")]
3647    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3648    impl ToTokens for ExprConst {
3649        fn to_tokens(&self, tokens: &mut TokenStream) {
3650            outer_attrs_to_tokens(&self.attrs, tokens);
3651            self.const_token.to_tokens(tokens);
3652            self.block.brace_token.surround(tokens, |tokens| {
3653                inner_attrs_to_tokens(&self.attrs, tokens);
3654                tokens.append_all(&self.block.stmts);
3655            });
3656        }
3657    }
3658
3659    #[cfg(feature = "full")]
3660    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3661    impl ToTokens for ExprContinue {
3662        fn to_tokens(&self, tokens: &mut TokenStream) {
3663            outer_attrs_to_tokens(&self.attrs, tokens);
3664            self.continue_token.to_tokens(tokens);
3665            self.label.to_tokens(tokens);
3666        }
3667    }
3668
3669    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3670    impl ToTokens for ExprField {
3671        fn to_tokens(&self, tokens: &mut TokenStream) {
3672            print_expr_field(self, tokens, FixupContext::NONE);
3673        }
3674    }
3675
3676    fn print_expr_field(e: &ExprField, tokens: &mut TokenStream, fixup: FixupContext) {
3677        outer_attrs_to_tokens(&e.attrs, tokens);
3678        let (left_prec, left_fixup) = fixup.leftmost_subexpression_with_dot(&e.base);
3679        print_subexpression(
3680            &e.base,
3681            left_prec < Precedence::Unambiguous,
3682            tokens,
3683            left_fixup,
3684        );
3685        e.dot_token.to_tokens(tokens);
3686        e.member.to_tokens(tokens);
3687    }
3688
3689    #[cfg(feature = "full")]
3690    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3691    impl ToTokens for ExprForLoop {
3692        fn to_tokens(&self, tokens: &mut TokenStream) {
3693            outer_attrs_to_tokens(&self.attrs, tokens);
3694            self.label.to_tokens(tokens);
3695            self.for_token.to_tokens(tokens);
3696            self.pat.to_tokens(tokens);
3697            self.in_token.to_tokens(tokens);
3698            print_expr(&self.expr, tokens, FixupContext::new_condition());
3699            self.body.brace_token.surround(tokens, |tokens| {
3700                inner_attrs_to_tokens(&self.attrs, tokens);
3701                tokens.append_all(&self.body.stmts);
3702            });
3703        }
3704    }
3705
3706    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3707    impl ToTokens for ExprGroup {
3708        fn to_tokens(&self, tokens: &mut TokenStream) {
3709            outer_attrs_to_tokens(&self.attrs, tokens);
3710            self.group_token.surround(tokens, |tokens| {
3711                self.expr.to_tokens(tokens);
3712            });
3713        }
3714    }
3715
3716    #[cfg(feature = "full")]
3717    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3718    impl ToTokens for ExprIf {
3719        fn to_tokens(&self, tokens: &mut TokenStream) {
3720            outer_attrs_to_tokens(&self.attrs, tokens);
3721
3722            let mut expr = self;
3723            loop {
3724                expr.if_token.to_tokens(tokens);
3725                print_expr(&expr.cond, tokens, FixupContext::new_condition());
3726                expr.then_branch.to_tokens(tokens);
3727
3728                let (else_token, else_) = match &expr.else_branch {
3729                    Some(else_branch) => else_branch,
3730                    None => break,
3731                };
3732
3733                else_token.to_tokens(tokens);
3734                match &**else_ {
3735                    Expr::If(next) => {
3736                        expr = next;
3737                    }
3738                    Expr::Block(last) => {
3739                        last.to_tokens(tokens);
3740                        break;
3741                    }
3742                    // If this is not one of the valid expressions to exist in
3743                    // an else clause, wrap it in a block.
3744                    other => {
3745                        token::Brace::default().surround(tokens, |tokens| {
3746                            print_expr(other, tokens, FixupContext::new_stmt());
3747                        });
3748                        break;
3749                    }
3750                }
3751            }
3752        }
3753    }
3754
3755    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3756    impl ToTokens for ExprIndex {
3757        fn to_tokens(&self, tokens: &mut TokenStream) {
3758            print_expr_index(self, tokens, FixupContext::NONE);
3759        }
3760    }
3761
3762    fn print_expr_index(e: &ExprIndex, tokens: &mut TokenStream, fixup: FixupContext) {
3763        outer_attrs_to_tokens(&e.attrs, tokens);
3764        let (left_prec, left_fixup) = fixup.leftmost_subexpression_with_operator(
3765            &e.expr,
3766            #[cfg(feature = "full")]
3767            true,
3768            false,
3769            #[cfg(feature = "full")]
3770            Precedence::Unambiguous,
3771        );
3772        print_subexpression(
3773            &e.expr,
3774            left_prec < Precedence::Unambiguous,
3775            tokens,
3776            left_fixup,
3777        );
3778        e.bracket_token.surround(tokens, |tokens| {
3779            e.index.to_tokens(tokens);
3780        });
3781    }
3782
3783    #[cfg(feature = "full")]
3784    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3785    impl ToTokens for ExprInfer {
3786        fn to_tokens(&self, tokens: &mut TokenStream) {
3787            outer_attrs_to_tokens(&self.attrs, tokens);
3788            self.underscore_token.to_tokens(tokens);
3789        }
3790    }
3791
3792    #[cfg(feature = "full")]
3793    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3794    impl ToTokens for ExprLet {
3795        fn to_tokens(&self, tokens: &mut TokenStream) {
3796            print_expr_let(self, tokens, FixupContext::NONE);
3797        }
3798    }
3799
3800    #[cfg(feature = "full")]
3801    fn print_expr_let(e: &ExprLet, tokens: &mut TokenStream, fixup: FixupContext) {
3802        outer_attrs_to_tokens(&e.attrs, tokens);
3803        e.let_token.to_tokens(tokens);
3804        e.pat.to_tokens(tokens);
3805        e.eq_token.to_tokens(tokens);
3806        let (right_prec, right_fixup) = fixup.rightmost_subexpression(&e.expr, Precedence::Let);
3807        print_subexpression(&e.expr, right_prec < Precedence::Let, tokens, right_fixup);
3808    }
3809
3810    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3811    impl ToTokens for ExprLit {
3812        fn to_tokens(&self, tokens: &mut TokenStream) {
3813            outer_attrs_to_tokens(&self.attrs, tokens);
3814            self.lit.to_tokens(tokens);
3815        }
3816    }
3817
3818    #[cfg(feature = "full")]
3819    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3820    impl ToTokens for ExprLoop {
3821        fn to_tokens(&self, tokens: &mut TokenStream) {
3822            outer_attrs_to_tokens(&self.attrs, tokens);
3823            self.label.to_tokens(tokens);
3824            self.loop_token.to_tokens(tokens);
3825            self.body.brace_token.surround(tokens, |tokens| {
3826                inner_attrs_to_tokens(&self.attrs, tokens);
3827                tokens.append_all(&self.body.stmts);
3828            });
3829        }
3830    }
3831
3832    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3833    impl ToTokens for ExprMacro {
3834        fn to_tokens(&self, tokens: &mut TokenStream) {
3835            outer_attrs_to_tokens(&self.attrs, tokens);
3836            self.mac.to_tokens(tokens);
3837        }
3838    }
3839
3840    #[cfg(feature = "full")]
3841    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3842    impl ToTokens for ExprMatch {
3843        fn to_tokens(&self, tokens: &mut TokenStream) {
3844            outer_attrs_to_tokens(&self.attrs, tokens);
3845            self.match_token.to_tokens(tokens);
3846            print_expr(&self.expr, tokens, FixupContext::new_condition());
3847            self.brace_token.surround(tokens, |tokens| {
3848                inner_attrs_to_tokens(&self.attrs, tokens);
3849                for (i, arm) in self.arms.iter().enumerate() {
3850                    arm.to_tokens(tokens);
3851                    // Ensure that we have a comma after a non-block arm, except
3852                    // for the last one.
3853                    let is_last = i == self.arms.len() - 1;
3854                    if !is_last
3855                        && classify::requires_comma_to_be_match_arm(&arm.body)
3856                        && arm.comma.is_none()
3857                    {
3858                        <Token![,]>::default().to_tokens(tokens);
3859                    }
3860                }
3861            });
3862        }
3863    }
3864
3865    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3866    impl ToTokens for ExprMethodCall {
3867        fn to_tokens(&self, tokens: &mut TokenStream) {
3868            print_expr_method_call(self, tokens, FixupContext::NONE);
3869        }
3870    }
3871
3872    fn print_expr_method_call(e: &ExprMethodCall, tokens: &mut TokenStream, fixup: FixupContext) {
3873        outer_attrs_to_tokens(&e.attrs, tokens);
3874        let (left_prec, left_fixup) = fixup.leftmost_subexpression_with_dot(&e.receiver);
3875        print_subexpression(
3876            &e.receiver,
3877            left_prec < Precedence::Unambiguous,
3878            tokens,
3879            left_fixup,
3880        );
3881        e.dot_token.to_tokens(tokens);
3882        e.method.to_tokens(tokens);
3883        if let Some(turbofish) = &e.turbofish {
3884            path::printing::print_angle_bracketed_generic_arguments(
3885                tokens,
3886                turbofish,
3887                PathStyle::Expr,
3888            );
3889        }
3890        e.paren_token.surround(tokens, |tokens| {
3891            e.args.to_tokens(tokens);
3892        });
3893    }
3894
3895    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3896    impl ToTokens for ExprParen {
3897        fn to_tokens(&self, tokens: &mut TokenStream) {
3898            outer_attrs_to_tokens(&self.attrs, tokens);
3899            self.paren_token.surround(tokens, |tokens| {
3900                self.expr.to_tokens(tokens);
3901            });
3902        }
3903    }
3904
3905    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3906    impl ToTokens for ExprPath {
3907        fn to_tokens(&self, tokens: &mut TokenStream) {
3908            outer_attrs_to_tokens(&self.attrs, tokens);
3909            path::printing::print_qpath(tokens, &self.qself, &self.path, PathStyle::Expr);
3910        }
3911    }
3912
3913    #[cfg(feature = "full")]
3914    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3915    impl ToTokens for ExprRange {
3916        fn to_tokens(&self, tokens: &mut TokenStream) {
3917            print_expr_range(self, tokens, FixupContext::NONE);
3918        }
3919    }
3920
3921    #[cfg(feature = "full")]
3922    fn print_expr_range(e: &ExprRange, tokens: &mut TokenStream, mut fixup: FixupContext) {
3923        outer_attrs_to_tokens(&e.attrs, tokens);
3924
3925        let needs_group = !e.attrs.is_empty();
3926        if needs_group {
3927            fixup = FixupContext::NONE;
3928        }
3929
3930        let do_print_expr = |tokens: &mut TokenStream| {
3931            if let Some(start) = &e.start {
3932                let (left_prec, left_fixup) = fixup.leftmost_subexpression_with_operator(
3933                    start,
3934                    true,
3935                    false,
3936                    Precedence::Range,
3937                );
3938                print_subexpression(start, left_prec <= Precedence::Range, tokens, left_fixup);
3939            }
3940            e.limits.to_tokens(tokens);
3941            if let Some(end) = &e.end {
3942                let right_fixup =
3943                    fixup.rightmost_subexpression_fixup(false, true, Precedence::Range);
3944                let right_prec = right_fixup.rightmost_subexpression_precedence(end);
3945                print_subexpression(end, right_prec <= Precedence::Range, tokens, right_fixup);
3946            }
3947        };
3948
3949        if needs_group {
3950            token::Paren::default().surround(tokens, do_print_expr);
3951        } else {
3952            do_print_expr(tokens);
3953        }
3954    }
3955
3956    #[cfg(feature = "full")]
3957    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3958    impl ToTokens for ExprRawAddr {
3959        fn to_tokens(&self, tokens: &mut TokenStream) {
3960            print_expr_raw_addr(self, tokens, FixupContext::NONE);
3961        }
3962    }
3963
3964    #[cfg(feature = "full")]
3965    fn print_expr_raw_addr(e: &ExprRawAddr, tokens: &mut TokenStream, fixup: FixupContext) {
3966        outer_attrs_to_tokens(&e.attrs, tokens);
3967        e.and_token.to_tokens(tokens);
3968        e.raw.to_tokens(tokens);
3969        e.mutability.to_tokens(tokens);
3970        let (right_prec, right_fixup) = fixup.rightmost_subexpression(&e.expr, Precedence::Prefix);
3971        print_subexpression(
3972            &e.expr,
3973            right_prec < Precedence::Prefix,
3974            tokens,
3975            right_fixup,
3976        );
3977    }
3978
3979    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3980    impl ToTokens for ExprReference {
3981        fn to_tokens(&self, tokens: &mut TokenStream) {
3982            print_expr_reference(self, tokens, FixupContext::NONE);
3983        }
3984    }
3985
3986    fn print_expr_reference(e: &ExprReference, tokens: &mut TokenStream, fixup: FixupContext) {
3987        outer_attrs_to_tokens(&e.attrs, tokens);
3988        e.and_token.to_tokens(tokens);
3989        e.mutability.to_tokens(tokens);
3990        let (right_prec, right_fixup) = fixup.rightmost_subexpression(
3991            &e.expr,
3992            #[cfg(feature = "full")]
3993            Precedence::Prefix,
3994        );
3995        print_subexpression(
3996            &e.expr,
3997            right_prec < Precedence::Prefix,
3998            tokens,
3999            right_fixup,
4000        );
4001    }
4002
4003    #[cfg(feature = "full")]
4004    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
4005    impl ToTokens for ExprRepeat {
4006        fn to_tokens(&self, tokens: &mut TokenStream) {
4007            outer_attrs_to_tokens(&self.attrs, tokens);
4008            self.bracket_token.surround(tokens, |tokens| {
4009                self.expr.to_tokens(tokens);
4010                self.semi_token.to_tokens(tokens);
4011                self.len.to_tokens(tokens);
4012            });
4013        }
4014    }
4015
4016    #[cfg(feature = "full")]
4017    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
4018    impl ToTokens for ExprReturn {
4019        fn to_tokens(&self, tokens: &mut TokenStream) {
4020            print_expr_return(self, tokens, FixupContext::NONE);
4021        }
4022    }
4023
4024    #[cfg(feature = "full")]
4025    fn print_expr_return(e: &ExprReturn, tokens: &mut TokenStream, fixup: FixupContext) {
4026        outer_attrs_to_tokens(&e.attrs, tokens);
4027        e.return_token.to_tokens(tokens);
4028        if let Some(expr) = &e.expr {
4029            print_expr(
4030                expr,
4031                tokens,
4032                fixup.rightmost_subexpression_fixup(true, false, Precedence::Jump),
4033            );
4034        }
4035    }
4036
4037    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
4038    impl ToTokens for ExprStruct {
4039        fn to_tokens(&self, tokens: &mut TokenStream) {
4040            outer_attrs_to_tokens(&self.attrs, tokens);
4041            path::printing::print_qpath(tokens, &self.qself, &self.path, PathStyle::Expr);
4042            self.brace_token.surround(tokens, |tokens| {
4043                self.fields.to_tokens(tokens);
4044                if let Some(dot2_token) = &self.dot2_token {
4045                    dot2_token.to_tokens(tokens);
4046                } else if self.rest.is_some() {
4047                    Token![..](Span::call_site()).to_tokens(tokens);
4048                }
4049                self.rest.to_tokens(tokens);
4050            });
4051        }
4052    }
4053
4054    #[cfg(feature = "full")]
4055    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
4056    impl ToTokens for ExprTry {
4057        fn to_tokens(&self, tokens: &mut TokenStream) {
4058            print_expr_try(self, tokens, FixupContext::NONE);
4059        }
4060    }
4061
4062    #[cfg(feature = "full")]
4063    fn print_expr_try(e: &ExprTry, tokens: &mut TokenStream, fixup: FixupContext) {
4064        outer_attrs_to_tokens(&e.attrs, tokens);
4065        let (left_prec, left_fixup) = fixup.leftmost_subexpression_with_dot(&e.expr);
4066        print_subexpression(
4067            &e.expr,
4068            left_prec < Precedence::Unambiguous,
4069            tokens,
4070            left_fixup,
4071        );
4072        e.question_token.to_tokens(tokens);
4073    }
4074
4075    #[cfg(feature = "full")]
4076    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
4077    impl ToTokens for ExprTryBlock {
4078        fn to_tokens(&self, tokens: &mut TokenStream) {
4079            outer_attrs_to_tokens(&self.attrs, tokens);
4080            self.try_token.to_tokens(tokens);
4081            self.block.to_tokens(tokens);
4082        }
4083    }
4084
4085    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
4086    impl ToTokens for ExprTuple {
4087        fn to_tokens(&self, tokens: &mut TokenStream) {
4088            outer_attrs_to_tokens(&self.attrs, tokens);
4089            self.paren_token.surround(tokens, |tokens| {
4090                self.elems.to_tokens(tokens);
4091                // If we only have one argument, we need a trailing comma to
4092                // distinguish ExprTuple from ExprParen.
4093                if self.elems.len() == 1 && !self.elems.trailing_punct() {
4094                    <Token![,]>::default().to_tokens(tokens);
4095                }
4096            });
4097        }
4098    }
4099
4100    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
4101    impl ToTokens for ExprUnary {
4102        fn to_tokens(&self, tokens: &mut TokenStream) {
4103            print_expr_unary(self, tokens, FixupContext::NONE);
4104        }
4105    }
4106
4107    fn print_expr_unary(e: &ExprUnary, tokens: &mut TokenStream, fixup: FixupContext) {
4108        outer_attrs_to_tokens(&e.attrs, tokens);
4109        e.op.to_tokens(tokens);
4110        let (right_prec, right_fixup) = fixup.rightmost_subexpression(
4111            &e.expr,
4112            #[cfg(feature = "full")]
4113            Precedence::Prefix,
4114        );
4115        print_subexpression(
4116            &e.expr,
4117            right_prec < Precedence::Prefix,
4118            tokens,
4119            right_fixup,
4120        );
4121    }
4122
4123    #[cfg(feature = "full")]
4124    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
4125    impl ToTokens for ExprUnsafe {
4126        fn to_tokens(&self, tokens: &mut TokenStream) {
4127            outer_attrs_to_tokens(&self.attrs, tokens);
4128            self.unsafe_token.to_tokens(tokens);
4129            self.block.brace_token.surround(tokens, |tokens| {
4130                inner_attrs_to_tokens(&self.attrs, tokens);
4131                tokens.append_all(&self.block.stmts);
4132            });
4133        }
4134    }
4135
4136    #[cfg(feature = "full")]
4137    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
4138    impl ToTokens for ExprWhile {
4139        fn to_tokens(&self, tokens: &mut TokenStream) {
4140            outer_attrs_to_tokens(&self.attrs, tokens);
4141            self.label.to_tokens(tokens);
4142            self.while_token.to_tokens(tokens);
4143            print_expr(&self.cond, tokens, FixupContext::new_condition());
4144            self.body.brace_token.surround(tokens, |tokens| {
4145                inner_attrs_to_tokens(&self.attrs, tokens);
4146                tokens.append_all(&self.body.stmts);
4147            });
4148        }
4149    }
4150
4151    #[cfg(feature = "full")]
4152    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
4153    impl ToTokens for ExprYield {
4154        fn to_tokens(&self, tokens: &mut TokenStream) {
4155            print_expr_yield(self, tokens, FixupContext::NONE);
4156        }
4157    }
4158
4159    #[cfg(feature = "full")]
4160    fn print_expr_yield(e: &ExprYield, tokens: &mut TokenStream, fixup: FixupContext) {
4161        outer_attrs_to_tokens(&e.attrs, tokens);
4162        e.yield_token.to_tokens(tokens);
4163        if let Some(expr) = &e.expr {
4164            print_expr(
4165                expr,
4166                tokens,
4167                fixup.rightmost_subexpression_fixup(true, false, Precedence::Jump),
4168            );
4169        }
4170    }
4171
4172    #[cfg(feature = "full")]
4173    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
4174    impl ToTokens for Arm {
4175        fn to_tokens(&self, tokens: &mut TokenStream) {
4176            tokens.append_all(&self.attrs);
4177            self.pat.to_tokens(tokens);
4178            self.fat_arrow_token.to_tokens(tokens);
4179            print_expr(&self.body, tokens, FixupContext::new_match_arm());
4180            self.comma.to_tokens(tokens);
4181        }
4182    }
4183
4184    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
4185    impl ToTokens for FieldValue {
4186        fn to_tokens(&self, tokens: &mut TokenStream) {
4187            outer_attrs_to_tokens(&self.attrs, tokens);
4188            self.member.to_tokens(tokens);
4189            if let Some(colon_token) = &self.colon_token {
4190                colon_token.to_tokens(tokens);
4191                self.expr.to_tokens(tokens);
4192            }
4193        }
4194    }
4195
4196    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
4197    impl ToTokens for Index {
4198        fn to_tokens(&self, tokens: &mut TokenStream) {
4199            let mut lit = Literal::i64_unsuffixed(i64::from(self.index));
4200            lit.set_span(self.span);
4201            tokens.append(lit);
4202        }
4203    }
4204
4205    #[cfg(feature = "full")]
4206    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
4207    impl ToTokens for Label {
4208        fn to_tokens(&self, tokens: &mut TokenStream) {
4209            self.name.to_tokens(tokens);
4210            self.colon_token.to_tokens(tokens);
4211        }
4212    }
4213
4214    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
4215    impl ToTokens for Member {
4216        fn to_tokens(&self, tokens: &mut TokenStream) {
4217            match self {
4218                Member::Named(ident) => ident.to_tokens(tokens),
4219                Member::Unnamed(index) => index.to_tokens(tokens),
4220            }
4221        }
4222    }
4223
4224    #[cfg(feature = "full")]
4225    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
4226    impl ToTokens for RangeLimits {
4227        fn to_tokens(&self, tokens: &mut TokenStream) {
4228            match self {
4229                RangeLimits::HalfOpen(t) => t.to_tokens(tokens),
4230                RangeLimits::Closed(t) => t.to_tokens(tokens),
4231            }
4232        }
4233    }
4234}