]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/expr.rs
Rollup merge of #91608 - workingjubilee:fold-neon-fp, r=nagisa,Amanieu
[rust.git] / compiler / rustc_parse / src / parser / expr.rs
1 use super::diagnostics::SnapshotParser;
2 use super::pat::{CommaRecoveryMode, RecoverColon, RecoverComma, PARAM_EXPECTED};
3 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
4 use super::{
5     AttrWrapper, BlockMode, ClosureSpans, ForceCollect, Parser, PathStyle, Restrictions,
6     SemiColonMode, SeqSep, TokenExpectType, TokenType, TrailingToken,
7 };
8 use crate::maybe_recover_from_interpolated_ty_qpath;
9
10 use ast::token::DelimToken;
11 use rustc_ast::ptr::P;
12 use rustc_ast::token::{self, Token, TokenKind};
13 use rustc_ast::tokenstream::Spacing;
14 use rustc_ast::util::classify;
15 use rustc_ast::util::literal::LitError;
16 use rustc_ast::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity};
17 use rustc_ast::{self as ast, AttrStyle, AttrVec, CaptureBy, ExprField, Lit, UnOp, DUMMY_NODE_ID};
18 use rustc_ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty, TyKind};
19 use rustc_ast::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits};
20 use rustc_ast_pretty::pprust;
21 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, PResult};
22 use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP;
23 use rustc_session::lint::BuiltinLintDiagnostics;
24 use rustc_span::source_map::{self, Span, Spanned};
25 use rustc_span::symbol::{kw, sym, Ident, Symbol};
26 use rustc_span::{BytePos, Pos};
27 use std::mem;
28
29 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
30 /// dropped into the token stream, which happens while parsing the result of
31 /// macro expansion). Placement of these is not as complex as I feared it would
32 /// be. The important thing is to make sure that lookahead doesn't balk at
33 /// `token::Interpolated` tokens.
34 macro_rules! maybe_whole_expr {
35     ($p:expr) => {
36         if let token::Interpolated(nt) = &$p.token.kind {
37             match &**nt {
38                 token::NtExpr(e) | token::NtLiteral(e) => {
39                     let e = e.clone();
40                     $p.bump();
41                     return Ok(e);
42                 }
43                 token::NtPath(path) => {
44                     let path = path.clone();
45                     $p.bump();
46                     return Ok($p.mk_expr(
47                         $p.prev_token.span,
48                         ExprKind::Path(None, path),
49                         AttrVec::new(),
50                     ));
51                 }
52                 token::NtBlock(block) => {
53                     let block = block.clone();
54                     $p.bump();
55                     return Ok($p.mk_expr(
56                         $p.prev_token.span,
57                         ExprKind::Block(block, None),
58                         AttrVec::new(),
59                     ));
60                 }
61                 _ => {}
62             };
63         }
64     };
65 }
66
67 #[derive(Debug)]
68 pub(super) enum LhsExpr {
69     NotYetParsed,
70     AttributesParsed(AttrWrapper),
71     AlreadyParsed(P<Expr>),
72 }
73
74 impl From<Option<AttrWrapper>> for LhsExpr {
75     /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
76     /// and `None` into `LhsExpr::NotYetParsed`.
77     ///
78     /// This conversion does not allocate.
79     fn from(o: Option<AttrWrapper>) -> Self {
80         if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed }
81     }
82 }
83
84 impl From<P<Expr>> for LhsExpr {
85     /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
86     ///
87     /// This conversion does not allocate.
88     fn from(expr: P<Expr>) -> Self {
89         LhsExpr::AlreadyParsed(expr)
90     }
91 }
92
93 impl<'a> Parser<'a> {
94     /// Parses an expression.
95     #[inline]
96     pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
97         self.current_closure.take();
98
99         self.parse_expr_res(Restrictions::empty(), None)
100     }
101
102     /// Parses an expression, forcing tokens to be collected
103     pub fn parse_expr_force_collect(&mut self) -> PResult<'a, P<Expr>> {
104         self.collect_tokens_no_attrs(|this| this.parse_expr())
105     }
106
107     pub fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> {
108         self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
109     }
110
111     fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P<Expr>> {
112         match self.parse_expr() {
113             Ok(expr) => Ok(expr),
114             Err(mut err) => match self.token.ident() {
115                 Some((Ident { name: kw::Underscore, .. }, false))
116                     if self.look_ahead(1, |t| t == &token::Comma) =>
117                 {
118                     // Special-case handling of `foo(_, _, _)`
119                     err.emit();
120                     self.bump();
121                     Ok(self.mk_expr(self.prev_token.span, ExprKind::Err, AttrVec::new()))
122                 }
123                 _ => Err(err),
124             },
125         }
126     }
127
128     /// Parses a sequence of expressions delimited by parentheses.
129     fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
130         self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r)
131     }
132
133     /// Parses an expression, subject to the given restrictions.
134     #[inline]
135     pub(super) fn parse_expr_res(
136         &mut self,
137         r: Restrictions,
138         already_parsed_attrs: Option<AttrWrapper>,
139     ) -> PResult<'a, P<Expr>> {
140         self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
141     }
142
143     /// Parses an associative expression.
144     ///
145     /// This parses an expression accounting for associativity and precedence of the operators in
146     /// the expression.
147     #[inline]
148     fn parse_assoc_expr(
149         &mut self,
150         already_parsed_attrs: Option<AttrWrapper>,
151     ) -> PResult<'a, P<Expr>> {
152         self.parse_assoc_expr_with(0, already_parsed_attrs.into())
153     }
154
155     /// Parses an associative expression with operators of at least `min_prec` precedence.
156     pub(super) fn parse_assoc_expr_with(
157         &mut self,
158         min_prec: usize,
159         lhs: LhsExpr,
160     ) -> PResult<'a, P<Expr>> {
161         let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
162             expr
163         } else {
164             let attrs = match lhs {
165                 LhsExpr::AttributesParsed(attrs) => Some(attrs),
166                 _ => None,
167             };
168             if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
169                 return self.parse_prefix_range_expr(attrs);
170             } else {
171                 self.parse_prefix_expr(attrs)?
172             }
173         };
174         let last_type_ascription_set = self.last_type_ascription.is_some();
175
176         if !self.should_continue_as_assoc_expr(&lhs) {
177             self.last_type_ascription = None;
178             return Ok(lhs);
179         }
180
181         self.expected_tokens.push(TokenType::Operator);
182         while let Some(op) = self.check_assoc_op() {
183             // Adjust the span for interpolated LHS to point to the `$lhs` token
184             // and not to what it refers to.
185             let lhs_span = match self.prev_token.kind {
186                 TokenKind::Interpolated(..) => self.prev_token.span,
187                 _ => lhs.span,
188             };
189
190             let cur_op_span = self.token.span;
191             let restrictions = if op.node.is_assign_like() {
192                 self.restrictions & Restrictions::NO_STRUCT_LITERAL
193             } else {
194                 self.restrictions
195             };
196             let prec = op.node.precedence();
197             if prec < min_prec {
198                 break;
199             }
200             // Check for deprecated `...` syntax
201             if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq {
202                 self.err_dotdotdot_syntax(self.token.span);
203             }
204
205             if self.token == token::LArrow {
206                 self.err_larrow_operator(self.token.span);
207             }
208
209             self.bump();
210             if op.node.is_comparison() {
211                 if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
212                     return Ok(expr);
213                 }
214             }
215
216             // Look for JS' `===` and `!==` and recover
217             if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual)
218                 && self.token.kind == token::Eq
219                 && self.prev_token.span.hi() == self.token.span.lo()
220             {
221                 let sp = op.span.to(self.token.span);
222                 let sugg = match op.node {
223                     AssocOp::Equal => "==",
224                     AssocOp::NotEqual => "!=",
225                     _ => unreachable!(),
226                 };
227                 self.struct_span_err(sp, &format!("invalid comparison operator `{sugg}=`"))
228                     .span_suggestion_short(
229                         sp,
230                         &format!("`{s}=` is not a valid comparison operator, use `{s}`", s = sugg),
231                         sugg.to_string(),
232                         Applicability::MachineApplicable,
233                     )
234                     .emit();
235                 self.bump();
236             }
237
238             // Look for PHP's `<>` and recover
239             if op.node == AssocOp::Less
240                 && self.token.kind == token::Gt
241                 && self.prev_token.span.hi() == self.token.span.lo()
242             {
243                 let sp = op.span.to(self.token.span);
244                 self.struct_span_err(sp, "invalid comparison operator `<>`")
245                     .span_suggestion_short(
246                         sp,
247                         "`<>` is not a valid comparison operator, use `!=`",
248                         "!=".to_string(),
249                         Applicability::MachineApplicable,
250                     )
251                     .emit();
252                 self.bump();
253             }
254
255             // Look for C++'s `<=>` and recover
256             if op.node == AssocOp::LessEqual
257                 && self.token.kind == token::Gt
258                 && self.prev_token.span.hi() == self.token.span.lo()
259             {
260                 let sp = op.span.to(self.token.span);
261                 self.struct_span_err(sp, "invalid comparison operator `<=>`")
262                     .span_label(
263                         sp,
264                         "`<=>` is not a valid comparison operator, use `std::cmp::Ordering`",
265                     )
266                     .emit();
267                 self.bump();
268             }
269
270             let op = op.node;
271             // Special cases:
272             if op == AssocOp::As {
273                 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
274                 continue;
275             } else if op == AssocOp::Colon {
276                 lhs = self.parse_assoc_op_ascribe(lhs, lhs_span)?;
277                 continue;
278             } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
279                 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
280                 // generalise it to the Fixity::None code.
281                 lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?;
282                 break;
283             }
284
285             let fixity = op.fixity();
286             let prec_adjustment = match fixity {
287                 Fixity::Right => 0,
288                 Fixity::Left => 1,
289                 // We currently have no non-associative operators that are not handled above by
290                 // the special cases. The code is here only for future convenience.
291                 Fixity::None => 1,
292             };
293             let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
294                 this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
295             })?;
296
297             let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span);
298             lhs = match op {
299                 AssocOp::Add
300                 | AssocOp::Subtract
301                 | AssocOp::Multiply
302                 | AssocOp::Divide
303                 | AssocOp::Modulus
304                 | AssocOp::LAnd
305                 | AssocOp::LOr
306                 | AssocOp::BitXor
307                 | AssocOp::BitAnd
308                 | AssocOp::BitOr
309                 | AssocOp::ShiftLeft
310                 | AssocOp::ShiftRight
311                 | AssocOp::Equal
312                 | AssocOp::Less
313                 | AssocOp::LessEqual
314                 | AssocOp::NotEqual
315                 | AssocOp::Greater
316                 | AssocOp::GreaterEqual => {
317                     let ast_op = op.to_ast_binop().unwrap();
318                     let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
319                     self.mk_expr(span, binary, AttrVec::new())
320                 }
321                 AssocOp::Assign => {
322                     self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span), AttrVec::new())
323                 }
324                 AssocOp::AssignOp(k) => {
325                     let aop = match k {
326                         token::Plus => BinOpKind::Add,
327                         token::Minus => BinOpKind::Sub,
328                         token::Star => BinOpKind::Mul,
329                         token::Slash => BinOpKind::Div,
330                         token::Percent => BinOpKind::Rem,
331                         token::Caret => BinOpKind::BitXor,
332                         token::And => BinOpKind::BitAnd,
333                         token::Or => BinOpKind::BitOr,
334                         token::Shl => BinOpKind::Shl,
335                         token::Shr => BinOpKind::Shr,
336                     };
337                     let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
338                     self.mk_expr(span, aopexpr, AttrVec::new())
339                 }
340                 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
341                     self.span_bug(span, "AssocOp should have been handled by special case")
342                 }
343             };
344
345             if let Fixity::None = fixity {
346                 break;
347             }
348         }
349         if last_type_ascription_set {
350             self.last_type_ascription = None;
351         }
352         Ok(lhs)
353     }
354
355     fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
356         match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) {
357             // Semi-statement forms are odd:
358             // See https://github.com/rust-lang/rust/issues/29071
359             (true, None) => false,
360             (false, _) => true, // Continue parsing the expression.
361             // An exhaustive check is done in the following block, but these are checked first
362             // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
363             // want to keep their span info to improve diagnostics in these cases in a later stage.
364             (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
365             (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
366             (true, Some(AssocOp::Add)) // `{ 42 } + 42
367             // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
368             // `if x { a } else { b } && if y { c } else { d }`
369             if !self.look_ahead(1, |t| t.is_used_keyword()) => {
370                 // These cases are ambiguous and can't be identified in the parser alone.
371                 let sp = self.sess.source_map().start_point(self.token.span);
372                 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
373                 false
374             }
375             (true, Some(AssocOp::LAnd)) |
376             (true, Some(AssocOp::LOr)) |
377             (true, Some(AssocOp::BitOr)) => {
378                 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`. Separated from the
379                 // above due to #74233.
380                 // These cases are ambiguous and can't be identified in the parser alone.
381                 //
382                 // Bitwise AND is left out because guessing intent is hard. We can make
383                 // suggestions based on the assumption that double-refs are rarely intentional,
384                 // and closures are distinct enough that they don't get mixed up with their
385                 // return value.
386                 let sp = self.sess.source_map().start_point(self.token.span);
387                 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
388                 false
389             }
390             (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => false,
391             (true, Some(_)) => {
392                 self.error_found_expr_would_be_stmt(lhs);
393                 true
394             }
395         }
396     }
397
398     /// We've found an expression that would be parsed as a statement,
399     /// but the next token implies this should be parsed as an expression.
400     /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
401     fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
402         let mut err = self.struct_span_err(
403             self.token.span,
404             &format!("expected expression, found `{}`", pprust::token_to_string(&self.token),),
405         );
406         err.span_label(self.token.span, "expected expression");
407         self.sess.expr_parentheses_needed(&mut err, lhs.span);
408         err.emit();
409     }
410
411     /// Possibly translate the current token to an associative operator.
412     /// The method does not advance the current token.
413     ///
414     /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
415     fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
416         let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
417             // When parsing const expressions, stop parsing when encountering `>`.
418             (
419                 Some(
420                     AssocOp::ShiftRight
421                     | AssocOp::Greater
422                     | AssocOp::GreaterEqual
423                     | AssocOp::AssignOp(token::BinOpToken::Shr),
424                 ),
425                 _,
426             ) if self.restrictions.contains(Restrictions::CONST_EXPR) => {
427                 return None;
428             }
429             (Some(op), _) => (op, self.token.span),
430             (None, Some((Ident { name: sym::and, span }, false))) => {
431                 self.error_bad_logical_op("and", "&&", "conjunction");
432                 (AssocOp::LAnd, span)
433             }
434             (None, Some((Ident { name: sym::or, span }, false))) => {
435                 self.error_bad_logical_op("or", "||", "disjunction");
436                 (AssocOp::LOr, span)
437             }
438             _ => return None,
439         };
440         Some(source_map::respan(span, op))
441     }
442
443     /// Error on `and` and `or` suggesting `&&` and `||` respectively.
444     fn error_bad_logical_op(&self, bad: &str, good: &str, english: &str) {
445         self.struct_span_err(self.token.span, &format!("`{bad}` is not a logical operator"))
446             .span_suggestion_short(
447                 self.token.span,
448                 &format!("use `{good}` to perform logical {english}"),
449                 good.to_string(),
450                 Applicability::MachineApplicable,
451             )
452             .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators")
453             .emit();
454     }
455
456     /// Checks if this expression is a successfully parsed statement.
457     fn expr_is_complete(&self, e: &Expr) -> bool {
458         self.restrictions.contains(Restrictions::STMT_EXPR)
459             && !classify::expr_requires_semi_to_be_stmt(e)
460     }
461
462     /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
463     /// The other two variants are handled in `parse_prefix_range_expr` below.
464     fn parse_range_expr(
465         &mut self,
466         prec: usize,
467         lhs: P<Expr>,
468         op: AssocOp,
469         cur_op_span: Span,
470     ) -> PResult<'a, P<Expr>> {
471         let rhs = if self.is_at_start_of_range_notation_rhs() {
472             Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
473         } else {
474             None
475         };
476         let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
477         let span = self.mk_expr_sp(&lhs, lhs.span, rhs_span);
478         let limits =
479             if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed };
480         let range = self.mk_range(Some(lhs), rhs, limits);
481         Ok(self.mk_expr(span, range, AttrVec::new()))
482     }
483
484     fn is_at_start_of_range_notation_rhs(&self) -> bool {
485         if self.token.can_begin_expr() {
486             // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
487             if self.token == token::OpenDelim(token::Brace) {
488                 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
489             }
490             true
491         } else {
492             false
493         }
494     }
495
496     /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
497     fn parse_prefix_range_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
498         // Check for deprecated `...` syntax.
499         if self.token == token::DotDotDot {
500             self.err_dotdotdot_syntax(self.token.span);
501         }
502
503         debug_assert!(
504             [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
505             "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
506             self.token
507         );
508
509         let limits = match self.token.kind {
510             token::DotDot => RangeLimits::HalfOpen,
511             _ => RangeLimits::Closed,
512         };
513         let op = AssocOp::from_token(&self.token);
514         // FIXME: `parse_prefix_range_expr` is called when the current
515         // token is `DotDot`, `DotDotDot`, or `DotDotEq`. If we haven't already
516         // parsed attributes, then trying to parse them here will always fail.
517         // We should figure out how we want attributes on range expressions to work.
518         let attrs = self.parse_or_use_outer_attributes(attrs)?;
519         self.collect_tokens_for_expr(attrs, |this, attrs| {
520             let lo = this.token.span;
521             this.bump();
522             let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() {
523                 // RHS must be parsed with more associativity than the dots.
524                 this.parse_assoc_expr_with(op.unwrap().precedence() + 1, LhsExpr::NotYetParsed)
525                     .map(|x| (lo.to(x.span), Some(x)))?
526             } else {
527                 (lo, None)
528             };
529             let range = this.mk_range(None, opt_end, limits);
530             Ok(this.mk_expr(span, range, attrs.into()))
531         })
532     }
533
534     /// Parses a prefix-unary-operator expr.
535     fn parse_prefix_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
536         let attrs = self.parse_or_use_outer_attributes(attrs)?;
537         let lo = self.token.span;
538
539         macro_rules! make_it {
540             ($this:ident, $attrs:expr, |this, _| $body:expr) => {
541                 $this.collect_tokens_for_expr($attrs, |$this, attrs| {
542                     let (hi, ex) = $body?;
543                     Ok($this.mk_expr(lo.to(hi), ex, attrs.into()))
544                 })
545             };
546         }
547
548         let this = self;
549
550         // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
551         match this.token.uninterpolate().kind {
552             token::Not => make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Not)), // `!expr`
553             token::Tilde => make_it!(this, attrs, |this, _| this.recover_tilde_expr(lo)), // `~expr`
554             token::BinOp(token::Minus) => {
555                 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Neg))
556             } // `-expr`
557             token::BinOp(token::Star) => {
558                 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Deref))
559             } // `*expr`
560             token::BinOp(token::And) | token::AndAnd => {
561                 make_it!(this, attrs, |this, _| this.parse_borrow_expr(lo))
562             }
563             token::BinOp(token::Plus) if this.look_ahead(1, |tok| tok.is_numeric_lit()) => {
564                 let mut err = this.struct_span_err(lo, "leading `+` is not supported");
565                 err.span_label(lo, "unexpected `+`");
566
567                 // a block on the LHS might have been intended to be an expression instead
568                 if let Some(sp) = this.sess.ambiguous_block_expr_parse.borrow().get(&lo) {
569                     this.sess.expr_parentheses_needed(&mut err, *sp);
570                 } else {
571                     err.span_suggestion_verbose(
572                         lo,
573                         "try removing the `+`",
574                         "".to_string(),
575                         Applicability::MachineApplicable,
576                     );
577                 }
578                 err.emit();
579
580                 this.bump();
581                 this.parse_prefix_expr(None)
582             } // `+expr`
583             token::Ident(..) if this.token.is_keyword(kw::Box) => {
584                 make_it!(this, attrs, |this, _| this.parse_box_expr(lo))
585             }
586             token::Ident(..) if this.is_mistaken_not_ident_negation() => {
587                 make_it!(this, attrs, |this, _| this.recover_not_expr(lo))
588             }
589             _ => return this.parse_dot_or_call_expr(Some(attrs)),
590         }
591     }
592
593     fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P<Expr>)> {
594         self.bump();
595         let expr = self.parse_prefix_expr(None);
596         let (span, expr) = self.interpolated_or_expr_span(expr)?;
597         Ok((lo.to(span), expr))
598     }
599
600     fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
601         let (span, expr) = self.parse_prefix_expr_common(lo)?;
602         Ok((span, self.mk_unary(op, expr)))
603     }
604
605     // Recover on `!` suggesting for bitwise negation instead.
606     fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
607         self.struct_span_err(lo, "`~` cannot be used as a unary operator")
608             .span_suggestion_short(
609                 lo,
610                 "use `!` to perform bitwise not",
611                 "!".to_owned(),
612                 Applicability::MachineApplicable,
613             )
614             .emit();
615
616         self.parse_unary_expr(lo, UnOp::Not)
617     }
618
619     /// Parse `box expr`.
620     fn parse_box_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
621         let (span, expr) = self.parse_prefix_expr_common(lo)?;
622         self.sess.gated_spans.gate(sym::box_syntax, span);
623         Ok((span, ExprKind::Box(expr)))
624     }
625
626     fn is_mistaken_not_ident_negation(&self) -> bool {
627         let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
628             // These tokens can start an expression after `!`, but
629             // can't continue an expression after an ident
630             token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
631             token::Literal(..) | token::Pound => true,
632             _ => t.is_whole_expr(),
633         };
634         self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
635     }
636
637     /// Recover on `not expr` in favor of `!expr`.
638     fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
639         // Emit the error...
640         let not_token = self.look_ahead(1, |t| t.clone());
641         self.struct_span_err(
642             not_token.span,
643             &format!("unexpected {} after identifier", super::token_descr(&not_token)),
644         )
645         .span_suggestion_short(
646             // Span the `not` plus trailing whitespace to avoid
647             // trailing whitespace after the `!` in our suggestion
648             self.sess.source_map().span_until_non_whitespace(lo.to(not_token.span)),
649             "use `!` to perform logical negation",
650             "!".to_owned(),
651             Applicability::MachineApplicable,
652         )
653         .emit();
654
655         // ...and recover!
656         self.parse_unary_expr(lo, UnOp::Not)
657     }
658
659     /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
660     fn interpolated_or_expr_span(
661         &self,
662         expr: PResult<'a, P<Expr>>,
663     ) -> PResult<'a, (Span, P<Expr>)> {
664         expr.map(|e| {
665             (
666                 match self.prev_token.kind {
667                     TokenKind::Interpolated(..) => self.prev_token.span,
668                     _ => e.span,
669                 },
670                 e,
671             )
672         })
673     }
674
675     fn parse_assoc_op_cast(
676         &mut self,
677         lhs: P<Expr>,
678         lhs_span: Span,
679         expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind,
680     ) -> PResult<'a, P<Expr>> {
681         let mk_expr = |this: &mut Self, lhs: P<Expr>, rhs: P<Ty>| {
682             this.mk_expr(
683                 this.mk_expr_sp(&lhs, lhs_span, rhs.span),
684                 expr_kind(lhs, rhs),
685                 AttrVec::new(),
686             )
687         };
688
689         // Save the state of the parser before parsing type normally, in case there is a
690         // LessThan comparison after this cast.
691         let parser_snapshot_before_type = self.clone();
692         let cast_expr = match self.parse_as_cast_ty() {
693             Ok(rhs) => mk_expr(self, lhs, rhs),
694             Err(type_err) => {
695                 // Rewind to before attempting to parse the type with generics, to recover
696                 // from situations like `x as usize < y` in which we first tried to parse
697                 // `usize < y` as a type with generic arguments.
698                 let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
699
700                 // Check for typo of `'a: loop { break 'a }` with a missing `'`.
701                 match (&lhs.kind, &self.token.kind) {
702                     (
703                         // `foo: `
704                         ExprKind::Path(None, ast::Path { segments, .. }),
705                         TokenKind::Ident(kw::For | kw::Loop | kw::While, false),
706                     ) if segments.len() == 1 => {
707                         let snapshot = self.create_snapshot_for_diagnostic();
708                         let label = Label {
709                             ident: Ident::from_str_and_span(
710                                 &format!("'{}", segments[0].ident),
711                                 segments[0].ident.span,
712                             ),
713                         };
714                         match self.parse_labeled_expr(label, AttrVec::new(), false) {
715                             Ok(expr) => {
716                                 type_err.cancel();
717                                 self.struct_span_err(label.ident.span, "malformed loop label")
718                                     .span_suggestion(
719                                         label.ident.span,
720                                         "use the correct loop label format",
721                                         label.ident.to_string(),
722                                         Applicability::MachineApplicable,
723                                     )
724                                     .emit();
725                                 return Ok(expr);
726                             }
727                             Err(err) => {
728                                 err.cancel();
729                                 self.restore_snapshot(snapshot);
730                             }
731                         }
732                     }
733                     _ => {}
734                 }
735
736                 match self.parse_path(PathStyle::Expr) {
737                     Ok(path) => {
738                         let (op_noun, op_verb) = match self.token.kind {
739                             token::Lt => ("comparison", "comparing"),
740                             token::BinOp(token::Shl) => ("shift", "shifting"),
741                             _ => {
742                                 // We can end up here even without `<` being the next token, for
743                                 // example because `parse_ty_no_plus` returns `Err` on keywords,
744                                 // but `parse_path` returns `Ok` on them due to error recovery.
745                                 // Return original error and parser state.
746                                 *self = parser_snapshot_after_type;
747                                 return Err(type_err);
748                             }
749                         };
750
751                         // Successfully parsed the type path leaving a `<` yet to parse.
752                         type_err.cancel();
753
754                         // Report non-fatal diagnostics, keep `x as usize` as an expression
755                         // in AST and continue parsing.
756                         let msg = format!(
757                             "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
758                             pprust::path_to_string(&path),
759                             op_noun,
760                         );
761                         let span_after_type = parser_snapshot_after_type.token.span;
762                         let expr =
763                             mk_expr(self, lhs, self.mk_ty(path.span, TyKind::Path(None, path)));
764
765                         self.struct_span_err(self.token.span, &msg)
766                             .span_label(
767                                 self.look_ahead(1, |t| t.span).to(span_after_type),
768                                 "interpreted as generic arguments",
769                             )
770                             .span_label(self.token.span, format!("not interpreted as {op_noun}"))
771                             .multipart_suggestion(
772                                 &format!("try {op_verb} the cast value"),
773                                 vec![
774                                     (expr.span.shrink_to_lo(), "(".to_string()),
775                                     (expr.span.shrink_to_hi(), ")".to_string()),
776                                 ],
777                                 Applicability::MachineApplicable,
778                             )
779                             .emit();
780
781                         expr
782                     }
783                     Err(path_err) => {
784                         // Couldn't parse as a path, return original error and parser state.
785                         path_err.cancel();
786                         *self = parser_snapshot_after_type;
787                         return Err(type_err);
788                     }
789                 }
790             }
791         };
792
793         self.parse_and_disallow_postfix_after_cast(cast_expr)
794     }
795
796     /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
797     /// then emits an error and returns the newly parsed tree.
798     /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
799     fn parse_and_disallow_postfix_after_cast(
800         &mut self,
801         cast_expr: P<Expr>,
802     ) -> PResult<'a, P<Expr>> {
803         let span = cast_expr.span;
804         let maybe_ascription_span = if let ExprKind::Type(ascripted_expr, _) = &cast_expr.kind {
805             Some(ascripted_expr.span.shrink_to_hi().with_hi(span.hi()))
806         } else {
807             None
808         };
809
810         // Save the memory location of expr before parsing any following postfix operators.
811         // This will be compared with the memory location of the output expression.
812         // If they different we can assume we parsed another expression because the existing expression is not reallocated.
813         let addr_before = &*cast_expr as *const _ as usize;
814         let with_postfix = self.parse_dot_or_call_expr_with_(cast_expr, span)?;
815         let changed = addr_before != &*with_postfix as *const _ as usize;
816
817         // Check if an illegal postfix operator has been added after the cast.
818         // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator.
819         if !matches!(with_postfix.kind, ExprKind::Cast(_, _) | ExprKind::Type(_, _)) || changed {
820             let msg = format!(
821                 "casts cannot be followed by {}",
822                 match with_postfix.kind {
823                     ExprKind::Index(_, _) => "indexing",
824                     ExprKind::Try(_) => "`?`",
825                     ExprKind::Field(_, _) => "a field access",
826                     ExprKind::MethodCall(_, _, _) => "a method call",
827                     ExprKind::Call(_, _) => "a function call",
828                     ExprKind::Await(_) => "`.await`",
829                     ExprKind::Err => return Ok(with_postfix),
830                     _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"),
831                 }
832             );
833             let mut err = self.struct_span_err(span, &msg);
834
835             let suggest_parens = |err: &mut DiagnosticBuilder<'_, _>| {
836                 let suggestions = vec![
837                     (span.shrink_to_lo(), "(".to_string()),
838                     (span.shrink_to_hi(), ")".to_string()),
839                 ];
840                 err.multipart_suggestion(
841                     "try surrounding the expression in parentheses",
842                     suggestions,
843                     Applicability::MachineApplicable,
844                 );
845             };
846
847             // If type ascription is "likely an error", the user will already be getting a useful
848             // help message, and doesn't need a second.
849             if self.last_type_ascription.map_or(false, |last_ascription| last_ascription.1) {
850                 self.maybe_annotate_with_ascription(&mut err, false);
851             } else if let Some(ascription_span) = maybe_ascription_span {
852                 let is_nightly = self.sess.unstable_features.is_nightly_build();
853                 if is_nightly {
854                     suggest_parens(&mut err);
855                 }
856                 err.span_suggestion(
857                     ascription_span,
858                     &format!(
859                         "{}remove the type ascription",
860                         if is_nightly { "alternatively, " } else { "" }
861                     ),
862                     String::new(),
863                     if is_nightly {
864                         Applicability::MaybeIncorrect
865                     } else {
866                         Applicability::MachineApplicable
867                     },
868                 );
869             } else {
870                 suggest_parens(&mut err);
871             }
872             err.emit();
873         };
874         Ok(with_postfix)
875     }
876
877     fn parse_assoc_op_ascribe(&mut self, lhs: P<Expr>, lhs_span: Span) -> PResult<'a, P<Expr>> {
878         let maybe_path = self.could_ascription_be_path(&lhs.kind);
879         self.last_type_ascription = Some((self.prev_token.span, maybe_path));
880         let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
881         self.sess.gated_spans.gate(sym::type_ascription, lhs.span);
882         Ok(lhs)
883     }
884
885     /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
886     fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
887         self.expect_and()?;
888         let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
889         let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
890         let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo);
891         let expr = self.parse_prefix_expr(None);
892         let (hi, expr) = self.interpolated_or_expr_span(expr)?;
893         let span = lo.to(hi);
894         if let Some(lt) = lifetime {
895             self.error_remove_borrow_lifetime(span, lt.ident.span);
896         }
897         Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
898     }
899
900     fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
901         self.struct_span_err(span, "borrow expressions cannot be annotated with lifetimes")
902             .span_label(lt_span, "annotated with lifetime here")
903             .span_suggestion(
904                 lt_span,
905                 "remove the lifetime annotation",
906                 String::new(),
907                 Applicability::MachineApplicable,
908             )
909             .emit();
910     }
911
912     /// Parse `mut?` or `raw [ const | mut ]`.
913     fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) {
914         if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) {
915             // `raw [ const | mut ]`.
916             let found_raw = self.eat_keyword(kw::Raw);
917             assert!(found_raw);
918             let mutability = self.parse_const_or_mut().unwrap();
919             self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span));
920             (ast::BorrowKind::Raw, mutability)
921         } else {
922             // `mut?`
923             (ast::BorrowKind::Ref, self.parse_mutability())
924         }
925     }
926
927     /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
928     fn parse_dot_or_call_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
929         let attrs = self.parse_or_use_outer_attributes(attrs)?;
930         self.collect_tokens_for_expr(attrs, |this, attrs| {
931             let base = this.parse_bottom_expr();
932             let (span, base) = this.interpolated_or_expr_span(base)?;
933             this.parse_dot_or_call_expr_with(base, span, attrs)
934         })
935     }
936
937     pub(super) fn parse_dot_or_call_expr_with(
938         &mut self,
939         e0: P<Expr>,
940         lo: Span,
941         mut attrs: Vec<ast::Attribute>,
942     ) -> PResult<'a, P<Expr>> {
943         // Stitch the list of outer attributes onto the return value.
944         // A little bit ugly, but the best way given the current code
945         // structure
946         self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| {
947             expr.map(|mut expr| {
948                 attrs.extend::<Vec<_>>(expr.attrs.into());
949                 expr.attrs = attrs.into();
950                 expr
951             })
952         })
953     }
954
955     fn parse_dot_or_call_expr_with_(&mut self, mut e: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
956         loop {
957             if self.eat(&token::Question) {
958                 // `expr?`
959                 e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e), AttrVec::new());
960                 continue;
961             }
962             if self.eat(&token::Dot) {
963                 // expr.f
964                 e = self.parse_dot_suffix_expr(lo, e)?;
965                 continue;
966             }
967             if self.expr_is_complete(&e) {
968                 return Ok(e);
969             }
970             e = match self.token.kind {
971                 token::OpenDelim(token::Paren) => self.parse_fn_call_expr(lo, e),
972                 token::OpenDelim(token::Bracket) => self.parse_index_expr(lo, e)?,
973                 _ => return Ok(e),
974             }
975         }
976     }
977
978     fn look_ahead_type_ascription_as_field(&mut self) -> bool {
979         self.look_ahead(1, |t| t.is_ident())
980             && self.look_ahead(2, |t| t == &token::Colon)
981             && self.look_ahead(3, |t| t.can_begin_expr())
982     }
983
984     fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
985         match self.token.uninterpolate().kind {
986             token::Ident(..) => self.parse_dot_suffix(base, lo),
987             token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
988                 Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix, None))
989             }
990             token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => {
991                 Ok(self.parse_tuple_field_access_expr_float(lo, base, symbol, suffix))
992             }
993             _ => {
994                 self.error_unexpected_after_dot();
995                 Ok(base)
996             }
997         }
998     }
999
1000     fn error_unexpected_after_dot(&self) {
1001         // FIXME Could factor this out into non_fatal_unexpected or something.
1002         let actual = pprust::token_to_string(&self.token);
1003         self.struct_span_err(self.token.span, &format!("unexpected token: `{actual}`")).emit();
1004     }
1005
1006     // We need an identifier or integer, but the next token is a float.
1007     // Break the float into components to extract the identifier or integer.
1008     // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
1009     // parts unless those parts are processed immediately. `TokenCursor` should either
1010     // support pushing "future tokens" (would be also helpful to `break_and_eat`), or
1011     // we should break everything including floats into more basic proc-macro style
1012     // tokens in the lexer (probably preferable).
1013     fn parse_tuple_field_access_expr_float(
1014         &mut self,
1015         lo: Span,
1016         base: P<Expr>,
1017         float: Symbol,
1018         suffix: Option<Symbol>,
1019     ) -> P<Expr> {
1020         #[derive(Debug)]
1021         enum FloatComponent {
1022             IdentLike(String),
1023             Punct(char),
1024         }
1025         use FloatComponent::*;
1026
1027         let float_str = float.as_str();
1028         let mut components = Vec::new();
1029         let mut ident_like = String::new();
1030         for c in float_str.chars() {
1031             if c == '_' || c.is_ascii_alphanumeric() {
1032                 ident_like.push(c);
1033             } else if matches!(c, '.' | '+' | '-') {
1034                 if !ident_like.is_empty() {
1035                     components.push(IdentLike(mem::take(&mut ident_like)));
1036                 }
1037                 components.push(Punct(c));
1038             } else {
1039                 panic!("unexpected character in a float token: {:?}", c)
1040             }
1041         }
1042         if !ident_like.is_empty() {
1043             components.push(IdentLike(ident_like));
1044         }
1045
1046         // With proc macros the span can refer to anything, the source may be too short,
1047         // or too long, or non-ASCII. It only makes sense to break our span into components
1048         // if its underlying text is identical to our float literal.
1049         let span = self.token.span;
1050         let can_take_span_apart =
1051             || self.span_to_snippet(span).as_deref() == Ok(float_str).as_deref();
1052
1053         match &*components {
1054             // 1e2
1055             [IdentLike(i)] => {
1056                 self.parse_tuple_field_access_expr(lo, base, Symbol::intern(&i), suffix, None)
1057             }
1058             // 1.
1059             [IdentLike(i), Punct('.')] => {
1060                 let (ident_span, dot_span) = if can_take_span_apart() {
1061                     let (span, ident_len) = (span.data(), BytePos::from_usize(i.len()));
1062                     let ident_span = span.with_hi(span.lo + ident_len);
1063                     let dot_span = span.with_lo(span.lo + ident_len);
1064                     (ident_span, dot_span)
1065                 } else {
1066                     (span, span)
1067                 };
1068                 assert!(suffix.is_none());
1069                 let symbol = Symbol::intern(&i);
1070                 self.token = Token::new(token::Ident(symbol, false), ident_span);
1071                 let next_token = (Token::new(token::Dot, dot_span), self.token_spacing);
1072                 self.parse_tuple_field_access_expr(lo, base, symbol, None, Some(next_token))
1073             }
1074             // 1.2 | 1.2e3
1075             [IdentLike(i1), Punct('.'), IdentLike(i2)] => {
1076                 let (ident1_span, dot_span, ident2_span) = if can_take_span_apart() {
1077                     let (span, ident1_len) = (span.data(), BytePos::from_usize(i1.len()));
1078                     let ident1_span = span.with_hi(span.lo + ident1_len);
1079                     let dot_span = span
1080                         .with_lo(span.lo + ident1_len)
1081                         .with_hi(span.lo + ident1_len + BytePos(1));
1082                     let ident2_span = self.token.span.with_lo(span.lo + ident1_len + BytePos(1));
1083                     (ident1_span, dot_span, ident2_span)
1084                 } else {
1085                     (span, span, span)
1086                 };
1087                 let symbol1 = Symbol::intern(&i1);
1088                 self.token = Token::new(token::Ident(symbol1, false), ident1_span);
1089                 // This needs to be `Spacing::Alone` to prevent regressions.
1090                 // See issue #76399 and PR #76285 for more details
1091                 let next_token1 = (Token::new(token::Dot, dot_span), Spacing::Alone);
1092                 let base1 =
1093                     self.parse_tuple_field_access_expr(lo, base, symbol1, None, Some(next_token1));
1094                 let symbol2 = Symbol::intern(&i2);
1095                 let next_token2 = Token::new(token::Ident(symbol2, false), ident2_span);
1096                 self.bump_with((next_token2, self.token_spacing)); // `.`
1097                 self.parse_tuple_field_access_expr(lo, base1, symbol2, suffix, None)
1098             }
1099             // 1e+ | 1e- (recovered)
1100             [IdentLike(_), Punct('+' | '-')] |
1101             // 1e+2 | 1e-2
1102             [IdentLike(_), Punct('+' | '-'), IdentLike(_)] |
1103             // 1.2e+ | 1.2e-
1104             [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-')] |
1105             // 1.2e+3 | 1.2e-3
1106             [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-'), IdentLike(_)] => {
1107                 // See the FIXME about `TokenCursor` above.
1108                 self.error_unexpected_after_dot();
1109                 base
1110             }
1111             _ => panic!("unexpected components in a float token: {:?}", components),
1112         }
1113     }
1114
1115     fn parse_tuple_field_access_expr(
1116         &mut self,
1117         lo: Span,
1118         base: P<Expr>,
1119         field: Symbol,
1120         suffix: Option<Symbol>,
1121         next_token: Option<(Token, Spacing)>,
1122     ) -> P<Expr> {
1123         match next_token {
1124             Some(next_token) => self.bump_with(next_token),
1125             None => self.bump(),
1126         }
1127         let span = self.prev_token.span;
1128         let field = ExprKind::Field(base, Ident::new(field, span));
1129         self.expect_no_suffix(span, "a tuple index", suffix);
1130         self.mk_expr(lo.to(span), field, AttrVec::new())
1131     }
1132
1133     /// Parse a function call expression, `expr(...)`.
1134     fn parse_fn_call_expr(&mut self, lo: Span, fun: P<Expr>) -> P<Expr> {
1135         let snapshot = if self.token.kind == token::OpenDelim(token::Paren)
1136             && self.look_ahead_type_ascription_as_field()
1137         {
1138             Some((self.create_snapshot_for_diagnostic(), fun.kind.clone()))
1139         } else {
1140             None
1141         };
1142         let open_paren = self.token.span;
1143
1144         let mut seq = self.parse_paren_expr_seq().map(|args| {
1145             self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args), AttrVec::new())
1146         });
1147         if let Some(expr) =
1148             self.maybe_recover_struct_lit_bad_delims(lo, open_paren, &mut seq, snapshot)
1149         {
1150             return expr;
1151         }
1152         self.recover_seq_parse_error(token::Paren, lo, seq)
1153     }
1154
1155     /// If we encounter a parser state that looks like the user has written a `struct` literal with
1156     /// parentheses instead of braces, recover the parser state and provide suggestions.
1157     #[instrument(skip(self, seq, snapshot), level = "trace")]
1158     fn maybe_recover_struct_lit_bad_delims(
1159         &mut self,
1160         lo: Span,
1161         open_paren: Span,
1162         seq: &mut PResult<'a, P<Expr>>,
1163         snapshot: Option<(SnapshotParser<'a>, ExprKind)>,
1164     ) -> Option<P<Expr>> {
1165         match (seq.as_mut(), snapshot) {
1166             (Err(err), Some((mut snapshot, ExprKind::Path(None, path)))) => {
1167                 let name = pprust::path_to_string(&path);
1168                 snapshot.bump(); // `(`
1169                 match snapshot.parse_struct_fields(path, false, token::Paren) {
1170                     Ok((fields, ..)) if snapshot.eat(&token::CloseDelim(token::Paren)) => {
1171                         // We are certain we have `Enum::Foo(a: 3, b: 4)`, suggest
1172                         // `Enum::Foo { a: 3, b: 4 }` or `Enum::Foo(3, 4)`.
1173                         self.restore_snapshot(snapshot);
1174                         let close_paren = self.prev_token.span;
1175                         let span = lo.to(self.prev_token.span);
1176                         if !fields.is_empty() {
1177                             let replacement_err = self.struct_span_err(
1178                                 span,
1179                                 "invalid `struct` delimiters or `fn` call arguments",
1180                             );
1181                             mem::replace(err, replacement_err).cancel();
1182
1183                             err.multipart_suggestion(
1184                                 &format!("if `{name}` is a struct, use braces as delimiters"),
1185                                 vec![
1186                                     (open_paren, " { ".to_string()),
1187                                     (close_paren, " }".to_string()),
1188                                 ],
1189                                 Applicability::MaybeIncorrect,
1190                             );
1191                             err.multipart_suggestion(
1192                                 &format!("if `{name}` is a function, use the arguments directly"),
1193                                 fields
1194                                     .into_iter()
1195                                     .map(|field| (field.span.until(field.expr.span), String::new()))
1196                                     .collect(),
1197                                 Applicability::MaybeIncorrect,
1198                             );
1199                             err.emit();
1200                         } else {
1201                             err.emit();
1202                         }
1203                         return Some(self.mk_expr_err(span));
1204                     }
1205                     Ok(_) => {}
1206                     Err(mut err) => {
1207                         err.emit();
1208                     }
1209                 }
1210             }
1211             _ => {}
1212         }
1213         None
1214     }
1215
1216     /// Parse an indexing expression `expr[...]`.
1217     fn parse_index_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
1218         self.bump(); // `[`
1219         let index = self.parse_expr()?;
1220         self.expect(&token::CloseDelim(token::Bracket))?;
1221         Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_index(base, index), AttrVec::new()))
1222     }
1223
1224     /// Assuming we have just parsed `.`, continue parsing into an expression.
1225     fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
1226         if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) {
1227             return Ok(self.mk_await_expr(self_arg, lo));
1228         }
1229
1230         let fn_span_lo = self.token.span;
1231         let mut segment = self.parse_path_segment(PathStyle::Expr, None)?;
1232         self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(token::Paren)]);
1233         self.check_turbofish_missing_angle_brackets(&mut segment);
1234
1235         if self.check(&token::OpenDelim(token::Paren)) {
1236             // Method call `expr.f()`
1237             let mut args = self.parse_paren_expr_seq()?;
1238             args.insert(0, self_arg);
1239
1240             let fn_span = fn_span_lo.to(self.prev_token.span);
1241             let span = lo.to(self.prev_token.span);
1242             Ok(self.mk_expr(span, ExprKind::MethodCall(segment, args, fn_span), AttrVec::new()))
1243         } else {
1244             // Field access `expr.f`
1245             if let Some(args) = segment.args {
1246                 self.struct_span_err(
1247                     args.span(),
1248                     "field expressions cannot have generic arguments",
1249                 )
1250                 .emit();
1251             }
1252
1253             let span = lo.to(self.prev_token.span);
1254             Ok(self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), AttrVec::new()))
1255         }
1256     }
1257
1258     /// At the bottom (top?) of the precedence hierarchy,
1259     /// Parses things like parenthesized exprs, macros, `return`, etc.
1260     ///
1261     /// N.B., this does not parse outer attributes, and is private because it only works
1262     /// correctly if called from `parse_dot_or_call_expr()`.
1263     fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1264         maybe_recover_from_interpolated_ty_qpath!(self, true);
1265         maybe_whole_expr!(self);
1266
1267         // Outer attributes are already parsed and will be
1268         // added to the return value after the fact.
1269         //
1270         // Therefore, prevent sub-parser from parsing
1271         // attributes by giving them an empty "already-parsed" list.
1272         let attrs = AttrVec::new();
1273
1274         // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
1275         let lo = self.token.span;
1276         if let token::Literal(_) = self.token.kind {
1277             // This match arm is a special-case of the `_` match arm below and
1278             // could be removed without changing functionality, but it's faster
1279             // to have it here, especially for programs with large constants.
1280             self.parse_lit_expr(attrs)
1281         } else if self.check(&token::OpenDelim(token::Paren)) {
1282             self.parse_tuple_parens_expr(attrs)
1283         } else if self.check(&token::OpenDelim(token::Brace)) {
1284             self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs)
1285         } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) {
1286             self.parse_closure_expr(attrs).map_err(|mut err| {
1287                 // If the input is something like `if a { 1 } else { 2 } | if a { 3 } else { 4 }`
1288                 // then suggest parens around the lhs.
1289                 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&lo) {
1290                     self.sess.expr_parentheses_needed(&mut err, *sp);
1291                 }
1292                 err
1293             })
1294         } else if self.check(&token::OpenDelim(token::Bracket)) {
1295             self.parse_array_or_repeat_expr(attrs, token::Bracket)
1296         } else if self.check_path() {
1297             self.parse_path_start_expr(attrs)
1298         } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
1299             self.parse_closure_expr(attrs)
1300         } else if self.eat_keyword(kw::If) {
1301             self.parse_if_expr(attrs)
1302         } else if self.check_keyword(kw::For) {
1303             if self.choose_generics_over_qpath(1) {
1304                 // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery,
1305                 // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns.
1306                 // When `for <Foo as Bar>::Proj in $expr $block` is wanted,
1307                 // you can disambiguate in favor of a pattern with `(...)`.
1308                 self.recover_quantified_closure_expr(attrs)
1309             } else {
1310                 assert!(self.eat_keyword(kw::For));
1311                 self.parse_for_expr(None, self.prev_token.span, attrs)
1312             }
1313         } else if self.eat_keyword(kw::While) {
1314             self.parse_while_expr(None, self.prev_token.span, attrs)
1315         } else if let Some(label) = self.eat_label() {
1316             self.parse_labeled_expr(label, attrs, true)
1317         } else if self.eat_keyword(kw::Loop) {
1318             let sp = self.prev_token.span;
1319             self.parse_loop_expr(None, self.prev_token.span, attrs).map_err(|mut err| {
1320                 err.span_label(sp, "while parsing this `loop` expression");
1321                 err
1322             })
1323         } else if self.eat_keyword(kw::Continue) {
1324             let kind = ExprKind::Continue(self.eat_label());
1325             Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1326         } else if self.eat_keyword(kw::Match) {
1327             let match_sp = self.prev_token.span;
1328             self.parse_match_expr(attrs).map_err(|mut err| {
1329                 err.span_label(match_sp, "while parsing this `match` expression");
1330                 err
1331             })
1332         } else if self.eat_keyword(kw::Unsafe) {
1333             let sp = self.prev_token.span;
1334             self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs)
1335                 .map_err(|mut err| {
1336                     err.span_label(sp, "while parsing this `unsafe` expression");
1337                     err
1338                 })
1339         } else if self.check_inline_const(0) {
1340             self.parse_const_block(lo.to(self.token.span), false)
1341         } else if self.is_do_catch_block() {
1342             self.recover_do_catch(attrs)
1343         } else if self.is_try_block() {
1344             self.expect_keyword(kw::Try)?;
1345             self.parse_try_block(lo, attrs)
1346         } else if self.eat_keyword(kw::Return) {
1347             self.parse_return_expr(attrs)
1348         } else if self.eat_keyword(kw::Break) {
1349             self.parse_break_expr(attrs)
1350         } else if self.eat_keyword(kw::Yield) {
1351             self.parse_yield_expr(attrs)
1352         } else if self.eat_keyword(kw::Let) {
1353             self.parse_let_expr(attrs)
1354         } else if self.eat_keyword(kw::Underscore) {
1355             Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore, attrs))
1356         } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1357             // Don't complain about bare semicolons after unclosed braces
1358             // recovery in order to keep the error count down. Fixing the
1359             // delimiters will possibly also fix the bare semicolon found in
1360             // expression context. For example, silence the following error:
1361             //
1362             //     error: expected expression, found `;`
1363             //      --> file.rs:2:13
1364             //       |
1365             //     2 |     foo(bar(;
1366             //       |             ^ expected expression
1367             self.bump();
1368             Ok(self.mk_expr_err(self.token.span))
1369         } else if self.token.uninterpolated_span().rust_2018() {
1370             // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1371             if self.check_keyword(kw::Async) {
1372                 if self.is_async_block() {
1373                     // Check for `async {` and `async move {`.
1374                     self.parse_async_block(attrs)
1375                 } else {
1376                     self.parse_closure_expr(attrs)
1377                 }
1378             } else if self.eat_keyword(kw::Await) {
1379                 self.recover_incorrect_await_syntax(lo, self.prev_token.span, attrs)
1380             } else {
1381                 self.parse_lit_expr(attrs)
1382             }
1383         } else {
1384             self.parse_lit_expr(attrs)
1385         }
1386     }
1387
1388     fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1389         let lo = self.token.span;
1390         match self.parse_opt_lit() {
1391             Some(literal) => {
1392                 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs);
1393                 self.maybe_recover_from_bad_qpath(expr, true)
1394             }
1395             None => self.try_macro_suggestion(),
1396         }
1397     }
1398
1399     fn parse_tuple_parens_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1400         let lo = self.token.span;
1401         self.expect(&token::OpenDelim(token::Paren))?;
1402         let (es, trailing_comma) = match self.parse_seq_to_end(
1403             &token::CloseDelim(token::Paren),
1404             SeqSep::trailing_allowed(token::Comma),
1405             |p| p.parse_expr_catch_underscore(),
1406         ) {
1407             Ok(x) => x,
1408             Err(err) => return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err))),
1409         };
1410         let kind = if es.len() == 1 && !trailing_comma {
1411             // `(e)` is parenthesized `e`.
1412             ExprKind::Paren(es.into_iter().next().unwrap())
1413         } else {
1414             // `(e,)` is a tuple with only one field, `e`.
1415             ExprKind::Tup(es)
1416         };
1417         let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1418         self.maybe_recover_from_bad_qpath(expr, true)
1419     }
1420
1421     fn parse_array_or_repeat_expr(
1422         &mut self,
1423         attrs: AttrVec,
1424         close_delim: token::DelimToken,
1425     ) -> PResult<'a, P<Expr>> {
1426         let lo = self.token.span;
1427         self.bump(); // `[` or other open delim
1428
1429         let close = &token::CloseDelim(close_delim);
1430         let kind = if self.eat(close) {
1431             // Empty vector
1432             ExprKind::Array(Vec::new())
1433         } else {
1434             // Non-empty vector
1435             let first_expr = self.parse_expr()?;
1436             if self.eat(&token::Semi) {
1437                 // Repeating array syntax: `[ 0; 512 ]`
1438                 let count = self.parse_anon_const_expr()?;
1439                 self.expect(close)?;
1440                 ExprKind::Repeat(first_expr, count)
1441             } else if self.eat(&token::Comma) {
1442                 // Vector with two or more elements.
1443                 let sep = SeqSep::trailing_allowed(token::Comma);
1444                 let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1445                 let mut exprs = vec![first_expr];
1446                 exprs.extend(remaining_exprs);
1447                 ExprKind::Array(exprs)
1448             } else {
1449                 // Vector with one element
1450                 self.expect(close)?;
1451                 ExprKind::Array(vec![first_expr])
1452             }
1453         };
1454         let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1455         self.maybe_recover_from_bad_qpath(expr, true)
1456     }
1457
1458     fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1459         let (qself, path) = if self.eat_lt() {
1460             let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
1461             (Some(qself), path)
1462         } else {
1463             (None, self.parse_path(PathStyle::Expr)?)
1464         };
1465         let lo = path.span;
1466
1467         // `!`, as an operator, is prefix, so we know this isn't that.
1468         let (hi, kind) = if self.eat(&token::Not) {
1469             // MACRO INVOCATION expression
1470             if qself.is_some() {
1471                 self.struct_span_err(path.span, "macros cannot use qualified paths").emit();
1472             }
1473             let mac = MacCall {
1474                 path,
1475                 args: self.parse_mac_args()?,
1476                 prior_type_ascription: self.last_type_ascription,
1477             };
1478             (self.prev_token.span, ExprKind::MacCall(mac))
1479         } else if self.check(&token::OpenDelim(token::Brace)) {
1480             if let Some(expr) = self.maybe_parse_struct_expr(qself.as_ref(), &path, &attrs) {
1481                 if qself.is_some() {
1482                     self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
1483                 }
1484                 return expr;
1485             } else {
1486                 (path.span, ExprKind::Path(qself, path))
1487             }
1488         } else {
1489             (path.span, ExprKind::Path(qself, path))
1490         };
1491
1492         let expr = self.mk_expr(lo.to(hi), kind, attrs);
1493         self.maybe_recover_from_bad_qpath(expr, true)
1494     }
1495
1496     /// Parse `'label: $expr`. The label is already parsed.
1497     fn parse_labeled_expr(
1498         &mut self,
1499         label: Label,
1500         attrs: AttrVec,
1501         mut consume_colon: bool,
1502     ) -> PResult<'a, P<Expr>> {
1503         let lo = label.ident.span;
1504         let label = Some(label);
1505         let ate_colon = self.eat(&token::Colon);
1506         let expr = if self.eat_keyword(kw::While) {
1507             self.parse_while_expr(label, lo, attrs)
1508         } else if self.eat_keyword(kw::For) {
1509             self.parse_for_expr(label, lo, attrs)
1510         } else if self.eat_keyword(kw::Loop) {
1511             self.parse_loop_expr(label, lo, attrs)
1512         } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1513             self.parse_block_expr(label, lo, BlockCheckMode::Default, attrs)
1514         } else if !ate_colon && (self.check(&TokenKind::Comma) || self.check(&TokenKind::Gt)) {
1515             // We're probably inside of a `Path<'a>` that needs a turbofish
1516             let msg = "expected `while`, `for`, `loop` or `{` after a label";
1517             self.struct_span_err(self.token.span, msg).span_label(self.token.span, msg).emit();
1518             consume_colon = false;
1519             Ok(self.mk_expr_err(lo))
1520         } else {
1521             let msg = "expected `while`, `for`, `loop` or `{` after a label";
1522             self.struct_span_err(self.token.span, msg).span_label(self.token.span, msg).emit();
1523             // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1524             self.parse_expr()
1525         }?;
1526
1527         if !ate_colon && consume_colon {
1528             self.error_labeled_expr_must_be_followed_by_colon(lo, expr.span);
1529         }
1530
1531         Ok(expr)
1532     }
1533
1534     fn error_labeled_expr_must_be_followed_by_colon(&self, lo: Span, span: Span) {
1535         self.struct_span_err(span, "labeled expression must be followed by `:`")
1536             .span_label(lo, "the label")
1537             .span_suggestion_short(
1538                 lo.shrink_to_hi(),
1539                 "add `:` after the label",
1540                 ": ".to_string(),
1541                 Applicability::MachineApplicable,
1542             )
1543             .note("labels are used before loops and blocks, allowing e.g., `break 'label` to them")
1544             .emit();
1545     }
1546
1547     /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1548     fn recover_do_catch(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1549         let lo = self.token.span;
1550
1551         self.bump(); // `do`
1552         self.bump(); // `catch`
1553
1554         let span_dc = lo.to(self.prev_token.span);
1555         self.struct_span_err(span_dc, "found removed `do catch` syntax")
1556             .span_suggestion(
1557                 span_dc,
1558                 "replace with the new syntax",
1559                 "try".to_string(),
1560                 Applicability::MachineApplicable,
1561             )
1562             .note("following RFC #2388, the new non-placeholder syntax is `try`")
1563             .emit();
1564
1565         self.parse_try_block(lo, attrs)
1566     }
1567
1568     /// Parse an expression if the token can begin one.
1569     fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1570         Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1571     }
1572
1573     /// Parse `"return" expr?`.
1574     fn parse_return_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1575         let lo = self.prev_token.span;
1576         let kind = ExprKind::Ret(self.parse_expr_opt()?);
1577         let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1578         self.maybe_recover_from_bad_qpath(expr, true)
1579     }
1580
1581     /// Parse `"break" (('label (:? expr)?) | expr?)` with `"break"` token already eaten.
1582     /// If the label is followed immediately by a `:` token, the label and `:` are
1583     /// parsed as part of the expression (i.e. a labeled loop). The language team has
1584     /// decided in #87026 to require parentheses as a visual aid to avoid confusion if
1585     /// the break expression of an unlabeled break is a labeled loop (as in
1586     /// `break 'lbl: loop {}`); a labeled break with an unlabeled loop as its value
1587     /// expression only gets a warning for compatibility reasons; and a labeled break
1588     /// with a labeled loop does not even get a warning because there is no ambiguity.
1589     fn parse_break_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1590         let lo = self.prev_token.span;
1591         let mut label = self.eat_label();
1592         let kind = if label.is_some() && self.token == token::Colon {
1593             // The value expression can be a labeled loop, see issue #86948, e.g.:
1594             // `loop { break 'label: loop { break 'label 42; }; }`
1595             let lexpr = self.parse_labeled_expr(label.take().unwrap(), AttrVec::new(), true)?;
1596             self.struct_span_err(
1597                 lexpr.span,
1598                 "parentheses are required around this expression to avoid confusion with a labeled break expression",
1599             )
1600             .multipart_suggestion(
1601                 "wrap the expression in parentheses",
1602                 vec![
1603                     (lexpr.span.shrink_to_lo(), "(".to_string()),
1604                     (lexpr.span.shrink_to_hi(), ")".to_string()),
1605                 ],
1606                 Applicability::MachineApplicable,
1607             )
1608             .emit();
1609             Some(lexpr)
1610         } else if self.token != token::OpenDelim(token::Brace)
1611             || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1612         {
1613             let expr = self.parse_expr_opt()?;
1614             if let Some(ref expr) = expr {
1615                 if label.is_some()
1616                     && matches!(
1617                         expr.kind,
1618                         ExprKind::While(_, _, None)
1619                             | ExprKind::ForLoop(_, _, _, None)
1620                             | ExprKind::Loop(_, None)
1621                             | ExprKind::Block(_, None)
1622                     )
1623                 {
1624                     self.sess.buffer_lint_with_diagnostic(
1625                         BREAK_WITH_LABEL_AND_LOOP,
1626                         lo.to(expr.span),
1627                         ast::CRATE_NODE_ID,
1628                         "this labeled break expression is easy to confuse with an unlabeled break with a labeled value expression",
1629                         BuiltinLintDiagnostics::BreakWithLabelAndLoop(expr.span),
1630                     );
1631                 }
1632             }
1633             expr
1634         } else {
1635             None
1636         };
1637         let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind), attrs);
1638         self.maybe_recover_from_bad_qpath(expr, true)
1639     }
1640
1641     /// Parse `"yield" expr?`.
1642     fn parse_yield_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1643         let lo = self.prev_token.span;
1644         let kind = ExprKind::Yield(self.parse_expr_opt()?);
1645         let span = lo.to(self.prev_token.span);
1646         self.sess.gated_spans.gate(sym::generators, span);
1647         let expr = self.mk_expr(span, kind, attrs);
1648         self.maybe_recover_from_bad_qpath(expr, true)
1649     }
1650
1651     /// Returns a string literal if the next token is a string literal.
1652     /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1653     /// and returns `None` if the next token is not literal at all.
1654     pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
1655         match self.parse_opt_lit() {
1656             Some(lit) => match lit.kind {
1657                 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1658                     style,
1659                     symbol: lit.token.symbol,
1660                     suffix: lit.token.suffix,
1661                     span: lit.span,
1662                     symbol_unescaped,
1663                 }),
1664                 _ => Err(Some(lit)),
1665             },
1666             None => Err(None),
1667         }
1668     }
1669
1670     pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> {
1671         self.parse_opt_lit().ok_or_else(|| {
1672             if let token::Interpolated(inner) = &self.token.kind {
1673                 let expr = match inner.as_ref() {
1674                     token::NtExpr(expr) => Some(expr),
1675                     token::NtLiteral(expr) => Some(expr),
1676                     _ => None,
1677                 };
1678                 if let Some(expr) = expr {
1679                     if matches!(expr.kind, ExprKind::Err) {
1680                         let mut err = self
1681                             .diagnostic()
1682                             .struct_span_err(self.token.span, &"invalid interpolated expression");
1683                         err.downgrade_to_delayed_bug();
1684                         return err;
1685                     }
1686                 }
1687             }
1688             let msg = format!("unexpected token: {}", super::token_descr(&self.token));
1689             self.struct_span_err(self.token.span, &msg)
1690         })
1691     }
1692
1693     /// Matches `lit = true | false | token_lit`.
1694     /// Returns `None` if the next token is not a literal.
1695     pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
1696         let mut recovered = None;
1697         if self.token == token::Dot {
1698             // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1699             // dot would follow an optional literal, so we do this unconditionally.
1700             recovered = self.look_ahead(1, |next_token| {
1701                 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1702                     next_token.kind
1703                 {
1704                     if self.token.span.hi() == next_token.span.lo() {
1705                         let s = String::from("0.") + symbol.as_str();
1706                         let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1707                         return Some(Token::new(kind, self.token.span.to(next_token.span)));
1708                     }
1709                 }
1710                 None
1711             });
1712             if let Some(token) = &recovered {
1713                 self.bump();
1714                 self.error_float_lits_must_have_int_part(&token);
1715             }
1716         }
1717
1718         let token = recovered.as_ref().unwrap_or(&self.token);
1719         match Lit::from_token(token) {
1720             Ok(lit) => {
1721                 self.bump();
1722                 Some(lit)
1723             }
1724             Err(LitError::NotLiteral) => None,
1725             Err(err) => {
1726                 let span = token.span;
1727                 let token::Literal(lit) = token.kind else {
1728                     unreachable!();
1729                 };
1730                 self.bump();
1731                 self.report_lit_error(err, lit, span);
1732                 // Pack possible quotes and prefixes from the original literal into
1733                 // the error literal's symbol so they can be pretty-printed faithfully.
1734                 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1735                 let symbol = Symbol::intern(&suffixless_lit.to_string());
1736                 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1737                 Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!()))
1738             }
1739         }
1740     }
1741
1742     fn error_float_lits_must_have_int_part(&self, token: &Token) {
1743         self.struct_span_err(token.span, "float literals must have an integer part")
1744             .span_suggestion(
1745                 token.span,
1746                 "must have an integer part",
1747                 pprust::token_to_string(token).into(),
1748                 Applicability::MachineApplicable,
1749             )
1750             .emit();
1751     }
1752
1753     fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) {
1754         // Checks if `s` looks like i32 or u1234 etc.
1755         fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1756             s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
1757         }
1758
1759         // Try to lowercase the prefix if it's a valid base prefix.
1760         fn fix_base_capitalisation(s: &str) -> Option<String> {
1761             if let Some(stripped) = s.strip_prefix('B') {
1762                 Some(format!("0b{stripped}"))
1763             } else if let Some(stripped) = s.strip_prefix('O') {
1764                 Some(format!("0o{stripped}"))
1765             } else if let Some(stripped) = s.strip_prefix('X') {
1766                 Some(format!("0x{stripped}"))
1767             } else {
1768                 None
1769             }
1770         }
1771
1772         let token::Lit { kind, suffix, .. } = lit;
1773         match err {
1774             // `NotLiteral` is not an error by itself, so we don't report
1775             // it and give the parser opportunity to try something else.
1776             LitError::NotLiteral => {}
1777             // `LexerError` *is* an error, but it was already reported
1778             // by lexer, so here we don't report it the second time.
1779             LitError::LexerError => {}
1780             LitError::InvalidSuffix => {
1781                 self.expect_no_suffix(
1782                     span,
1783                     &format!("{} {} literal", kind.article(), kind.descr()),
1784                     suffix,
1785                 );
1786             }
1787             LitError::InvalidIntSuffix => {
1788                 let suf = suffix.expect("suffix error with no suffix");
1789                 let suf = suf.as_str();
1790                 if looks_like_width_suffix(&['i', 'u'], &suf) {
1791                     // If it looks like a width, try to be helpful.
1792                     let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
1793                     self.struct_span_err(span, &msg)
1794                         .help("valid widths are 8, 16, 32, 64 and 128")
1795                         .emit();
1796                 } else if let Some(fixed) = fix_base_capitalisation(suf) {
1797                     let msg = "invalid base prefix for number literal";
1798
1799                     self.struct_span_err(span, &msg)
1800                         .note("base prefixes (`0xff`, `0b1010`, `0o755`) are lowercase")
1801                         .span_suggestion(
1802                             span,
1803                             "try making the prefix lowercase",
1804                             fixed,
1805                             Applicability::MaybeIncorrect,
1806                         )
1807                         .emit();
1808                 } else {
1809                     let msg = format!("invalid suffix `{suf}` for number literal");
1810                     self.struct_span_err(span, &msg)
1811                         .span_label(span, format!("invalid suffix `{suf}`"))
1812                         .help("the suffix must be one of the numeric types (`u32`, `isize`, `f32`, etc.)")
1813                         .emit();
1814                 }
1815             }
1816             LitError::InvalidFloatSuffix => {
1817                 let suf = suffix.expect("suffix error with no suffix");
1818                 let suf = suf.as_str();
1819                 if looks_like_width_suffix(&['f'], suf) {
1820                     // If it looks like a width, try to be helpful.
1821                     let msg = format!("invalid width `{}` for float literal", &suf[1..]);
1822                     self.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit();
1823                 } else {
1824                     let msg = format!("invalid suffix `{suf}` for float literal");
1825                     self.struct_span_err(span, &msg)
1826                         .span_label(span, format!("invalid suffix `{suf}`"))
1827                         .help("valid suffixes are `f32` and `f64`")
1828                         .emit();
1829                 }
1830             }
1831             LitError::NonDecimalFloat(base) => {
1832                 let descr = match base {
1833                     16 => "hexadecimal",
1834                     8 => "octal",
1835                     2 => "binary",
1836                     _ => unreachable!(),
1837                 };
1838                 self.struct_span_err(span, &format!("{descr} float literal is not supported"))
1839                     .span_label(span, "not supported")
1840                     .emit();
1841             }
1842             LitError::IntTooLarge => {
1843                 self.struct_span_err(span, "integer literal is too large").emit();
1844             }
1845         }
1846     }
1847
1848     pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) {
1849         if let Some(suf) = suffix {
1850             let mut err = if kind == "a tuple index"
1851                 && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf)
1852             {
1853                 // #59553: warn instead of reject out of hand to allow the fix to percolate
1854                 // through the ecosystem when people fix their macros
1855                 let mut err = self
1856                     .sess
1857                     .span_diagnostic
1858                     .struct_span_warn(sp, &format!("suffixes on {kind} are invalid"));
1859                 err.note(&format!(
1860                     "`{}` is *temporarily* accepted on tuple index fields as it was \
1861                         incorrectly accepted on stable for a few releases",
1862                     suf,
1863                 ));
1864                 err.help(
1865                     "on proc macros, you'll want to use `syn::Index::from` or \
1866                         `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1867                         to tuple field access",
1868                 );
1869                 err.note(
1870                     "see issue #60210 <https://github.com/rust-lang/rust/issues/60210> \
1871                      for more information",
1872                 );
1873                 err
1874             } else {
1875                 self.struct_span_err(sp, &format!("suffixes on {kind} are invalid"))
1876                     .forget_guarantee()
1877             };
1878             err.span_label(sp, format!("invalid suffix `{suf}`"));
1879             err.emit();
1880         }
1881     }
1882
1883     /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1884     /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
1885     pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1886         maybe_whole_expr!(self);
1887
1888         let lo = self.token.span;
1889         let minus_present = self.eat(&token::BinOp(token::Minus));
1890         let lit = self.parse_lit()?;
1891         let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new());
1892
1893         if minus_present {
1894             Ok(self.mk_expr(
1895                 lo.to(self.prev_token.span),
1896                 self.mk_unary(UnOp::Neg, expr),
1897                 AttrVec::new(),
1898             ))
1899         } else {
1900             Ok(expr)
1901         }
1902     }
1903
1904     fn is_array_like_block(&mut self) -> bool {
1905         self.look_ahead(1, |t| matches!(t.kind, TokenKind::Ident(..) | TokenKind::Literal(_)))
1906             && self.look_ahead(2, |t| t == &token::Comma)
1907             && self.look_ahead(3, |t| t.can_begin_expr())
1908     }
1909
1910     /// Emits a suggestion if it looks like the user meant an array but
1911     /// accidentally used braces, causing the code to be interpreted as a block
1912     /// expression.
1913     fn maybe_suggest_brackets_instead_of_braces(
1914         &mut self,
1915         lo: Span,
1916         attrs: AttrVec,
1917     ) -> Option<P<Expr>> {
1918         let mut snapshot = self.create_snapshot_for_diagnostic();
1919         match snapshot.parse_array_or_repeat_expr(attrs, token::Brace) {
1920             Ok(arr) => {
1921                 let hi = snapshot.prev_token.span;
1922                 self.struct_span_err(
1923                     arr.span,
1924                     "this code is interpreted as a block expression, not an array",
1925                 )
1926                 .multipart_suggestion(
1927                     "try using [] instead of {}",
1928                     vec![(lo, "[".to_owned()), (hi, "]".to_owned())],
1929                     Applicability::MaybeIncorrect,
1930                 )
1931                 .note("to define an array, one would use square brackets instead of curly braces")
1932                 .emit();
1933
1934                 self.restore_snapshot(snapshot);
1935                 Some(self.mk_expr_err(arr.span))
1936             }
1937             Err(e) => {
1938                 e.cancel();
1939                 None
1940             }
1941         }
1942     }
1943
1944     /// Parses a block or unsafe block.
1945     pub(super) fn parse_block_expr(
1946         &mut self,
1947         opt_label: Option<Label>,
1948         lo: Span,
1949         blk_mode: BlockCheckMode,
1950         mut attrs: AttrVec,
1951     ) -> PResult<'a, P<Expr>> {
1952         if self.is_array_like_block() {
1953             if let Some(arr) = self.maybe_suggest_brackets_instead_of_braces(lo, attrs.clone()) {
1954                 return Ok(arr);
1955             }
1956         }
1957
1958         if let Some(label) = opt_label {
1959             self.sess.gated_spans.gate(sym::label_break_value, label.ident.span);
1960         }
1961
1962         if self.token.is_whole_block() {
1963             self.struct_span_err(self.token.span, "cannot use a `block` macro fragment here")
1964                 .span_label(lo.to(self.token.span), "the `block` fragment is within this context")
1965                 .emit();
1966         }
1967
1968         let (inner_attrs, blk) = self.parse_block_common(lo, blk_mode)?;
1969         attrs.extend(inner_attrs);
1970         Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs))
1971     }
1972
1973     /// Recover on an explicitly quantified closure expression, e.g., `for<'a> |x: &'a u8| *x + 1`.
1974     fn recover_quantified_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1975         let lo = self.token.span;
1976         let _ = self.parse_late_bound_lifetime_defs()?;
1977         let span_for = lo.to(self.prev_token.span);
1978         let closure = self.parse_closure_expr(attrs)?;
1979
1980         self.struct_span_err(span_for, "cannot introduce explicit parameters for a closure")
1981             .span_label(closure.span, "the parameters are attached to this closure")
1982             .span_suggestion(
1983                 span_for,
1984                 "remove the parameters",
1985                 String::new(),
1986                 Applicability::MachineApplicable,
1987             )
1988             .emit();
1989
1990         Ok(self.mk_expr_err(lo.to(closure.span)))
1991     }
1992
1993     /// Parses a closure expression (e.g., `move |args| expr`).
1994     fn parse_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1995         let lo = self.token.span;
1996
1997         let movability =
1998             if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
1999
2000         let asyncness = if self.token.uninterpolated_span().rust_2018() {
2001             self.parse_asyncness()
2002         } else {
2003             Async::No
2004         };
2005
2006         let capture_clause = self.parse_capture_clause()?;
2007         let decl = self.parse_fn_block_decl()?;
2008         let decl_hi = self.prev_token.span;
2009         let mut body = match decl.output {
2010             FnRetTy::Default(_) => {
2011                 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
2012                 self.parse_expr_res(restrictions, None)?
2013             }
2014             _ => {
2015                 // If an explicit return type is given, require a block to appear (RFC 968).
2016                 let body_lo = self.token.span;
2017                 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, AttrVec::new())?
2018             }
2019         };
2020
2021         if let Async::Yes { span, .. } = asyncness {
2022             // Feature-gate `async ||` closures.
2023             self.sess.gated_spans.gate(sym::async_closure, span);
2024         }
2025
2026         if self.token.kind == TokenKind::Semi && self.token_cursor.frame.delim == DelimToken::Paren
2027         {
2028             // It is likely that the closure body is a block but where the
2029             // braces have been removed. We will recover and eat the next
2030             // statements later in the parsing process.
2031             body = self.mk_expr_err(body.span);
2032         }
2033
2034         let body_span = body.span;
2035
2036         let closure = self.mk_expr(
2037             lo.to(body.span),
2038             ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
2039             attrs,
2040         );
2041
2042         // Disable recovery for closure body
2043         let spans =
2044             ClosureSpans { whole_closure: closure.span, closing_pipe: decl_hi, body: body_span };
2045         self.current_closure = Some(spans);
2046
2047         Ok(closure)
2048     }
2049
2050     /// Parses an optional `move` prefix to a closure-like construct.
2051     fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> {
2052         if self.eat_keyword(kw::Move) {
2053             // Check for `move async` and recover
2054             if self.check_keyword(kw::Async) {
2055                 let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
2056                 Err(self.incorrect_move_async_order_found(move_async_span))
2057             } else {
2058                 Ok(CaptureBy::Value)
2059             }
2060         } else {
2061             Ok(CaptureBy::Ref)
2062         }
2063     }
2064
2065     /// Parses the `|arg, arg|` header of a closure.
2066     fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
2067         let inputs = if self.eat(&token::OrOr) {
2068             Vec::new()
2069         } else {
2070             self.expect(&token::BinOp(token::Or))?;
2071             let args = self
2072                 .parse_seq_to_before_tokens(
2073                     &[&token::BinOp(token::Or), &token::OrOr],
2074                     SeqSep::trailing_allowed(token::Comma),
2075                     TokenExpectType::NoExpect,
2076                     |p| p.parse_fn_block_param(),
2077                 )?
2078                 .0;
2079             self.expect_or()?;
2080             args
2081         };
2082         let output =
2083             self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes, RecoverReturnSign::Yes)?;
2084
2085         Ok(P(FnDecl { inputs, output }))
2086     }
2087
2088     /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
2089     fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
2090         let lo = self.token.span;
2091         let attrs = self.parse_outer_attributes()?;
2092         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2093             let pat = this.parse_pat_no_top_alt(PARAM_EXPECTED)?;
2094             let ty = if this.eat(&token::Colon) {
2095                 this.parse_ty()?
2096             } else {
2097                 this.mk_ty(this.prev_token.span, TyKind::Infer)
2098             };
2099
2100             Ok((
2101                 Param {
2102                     attrs: attrs.into(),
2103                     ty,
2104                     pat,
2105                     span: lo.to(this.token.span),
2106                     id: DUMMY_NODE_ID,
2107                     is_placeholder: false,
2108                 },
2109                 TrailingToken::MaybeComma,
2110             ))
2111         })
2112     }
2113
2114     /// Parses an `if` expression (`if` token already eaten).
2115     fn parse_if_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
2116         let lo = self.prev_token.span;
2117         let cond = self.parse_cond_expr()?;
2118
2119         let missing_then_block_binop_span = || {
2120             match cond.kind {
2121                 ExprKind::Binary(Spanned { span: binop_span, .. }, _, ref right)
2122                     if let ExprKind::Block(..) = right.kind => Some(binop_span),
2123                 _ => None
2124             }
2125         };
2126
2127         // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
2128         // verify that the last statement is either an implicit return (no `;`) or an explicit
2129         // return. This won't catch blocks with an explicit `return`, but that would be caught by
2130         // the dead code lint.
2131         let thn = if self.token.is_keyword(kw::Else) || !cond.returns() {
2132             if let Some(binop_span) = missing_then_block_binop_span() {
2133                 self.error_missing_if_then_block(lo, None, Some(binop_span)).emit();
2134                 self.mk_block_err(cond.span)
2135             } else {
2136                 self.error_missing_if_cond(lo, cond.span)
2137             }
2138         } else {
2139             let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
2140             let not_block = self.token != token::OpenDelim(token::Brace);
2141             let block = self.parse_block().map_err(|err| {
2142                 if not_block {
2143                     self.error_missing_if_then_block(lo, Some(err), missing_then_block_binop_span())
2144                 } else {
2145                     err
2146                 }
2147             })?;
2148             self.error_on_if_block_attrs(lo, false, block.span, &attrs);
2149             block
2150         };
2151         let els = if self.eat_keyword(kw::Else) { Some(self.parse_else_expr()?) } else { None };
2152         Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els), attrs))
2153     }
2154
2155     fn error_missing_if_then_block(
2156         &self,
2157         if_span: Span,
2158         err: Option<DiagnosticBuilder<'a, ErrorGuaranteed>>,
2159         binop_span: Option<Span>,
2160     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2161         let msg = "this `if` expression has a condition, but no block";
2162
2163         let mut err = if let Some(mut err) = err {
2164             err.span_label(if_span, msg);
2165             err
2166         } else {
2167             self.struct_span_err(if_span, msg)
2168         };
2169
2170         if let Some(binop_span) = binop_span {
2171             err.span_help(binop_span, "maybe you forgot the right operand of the condition?");
2172         }
2173
2174         err
2175     }
2176
2177     fn error_missing_if_cond(&self, lo: Span, span: Span) -> P<ast::Block> {
2178         let sp = self.sess.source_map().next_point(lo);
2179         self.struct_span_err(sp, "missing condition for `if` expression")
2180             .span_label(sp, "expected if condition here")
2181             .emit();
2182         self.mk_block_err(span)
2183     }
2184
2185     /// Parses the condition of a `if` or `while` expression.
2186     fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
2187         let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
2188
2189         if let ExprKind::Let(..) = cond.kind {
2190             // Remove the last feature gating of a `let` expression since it's stable.
2191             self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2192         }
2193
2194         Ok(cond)
2195     }
2196
2197     /// Parses a `let $pat = $expr` pseudo-expression.
2198     /// The `let` token has already been eaten.
2199     fn parse_let_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
2200         let lo = self.prev_token.span;
2201         let pat = self.parse_pat_allow_top_alt(
2202             None,
2203             RecoverComma::Yes,
2204             RecoverColon::Yes,
2205             CommaRecoveryMode::LikelyTuple,
2206         )?;
2207         self.expect(&token::Eq)?;
2208         let expr = self.with_res(self.restrictions | Restrictions::NO_STRUCT_LITERAL, |this| {
2209             this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
2210         })?;
2211         let span = lo.to(expr.span);
2212         self.sess.gated_spans.gate(sym::let_chains, span);
2213         Ok(self.mk_expr(span, ExprKind::Let(pat, expr, span), attrs))
2214     }
2215
2216     /// Parses an `else { ... }` expression (`else` token already eaten).
2217     fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
2218         let ctx_span = self.prev_token.span; // `else`
2219         let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
2220         let expr = if self.eat_keyword(kw::If) {
2221             self.parse_if_expr(AttrVec::new())?
2222         } else {
2223             let blk = self.parse_block()?;
2224             self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new())
2225         };
2226         self.error_on_if_block_attrs(ctx_span, true, expr.span, &attrs);
2227         Ok(expr)
2228     }
2229
2230     fn error_on_if_block_attrs(
2231         &self,
2232         ctx_span: Span,
2233         is_ctx_else: bool,
2234         branch_span: Span,
2235         attrs: &[ast::Attribute],
2236     ) {
2237         let (span, last) = match attrs {
2238             [] => return,
2239             [x0 @ xn] | [x0, .., xn] => (x0.span.to(xn.span), xn.span),
2240         };
2241         let ctx = if is_ctx_else { "else" } else { "if" };
2242         self.struct_span_err(last, "outer attributes are not allowed on `if` and `else` branches")
2243             .span_label(branch_span, "the attributes are attached to this branch")
2244             .span_label(ctx_span, format!("the branch belongs to this `{ctx}`"))
2245             .span_suggestion(
2246                 span,
2247                 "remove the attributes",
2248                 String::new(),
2249                 Applicability::MachineApplicable,
2250             )
2251             .emit();
2252     }
2253
2254     /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
2255     fn parse_for_expr(
2256         &mut self,
2257         opt_label: Option<Label>,
2258         lo: Span,
2259         mut attrs: AttrVec,
2260     ) -> PResult<'a, P<Expr>> {
2261         // Record whether we are about to parse `for (`.
2262         // This is used below for recovery in case of `for ( $stuff ) $block`
2263         // in which case we will suggest `for $stuff $block`.
2264         let begin_paren = match self.token.kind {
2265             token::OpenDelim(token::Paren) => Some(self.token.span),
2266             _ => None,
2267         };
2268
2269         let pat = self.parse_pat_allow_top_alt(
2270             None,
2271             RecoverComma::Yes,
2272             RecoverColon::Yes,
2273             CommaRecoveryMode::LikelyTuple,
2274         )?;
2275         if !self.eat_keyword(kw::In) {
2276             self.error_missing_in_for_loop();
2277         }
2278         self.check_for_for_in_in_typo(self.prev_token.span);
2279         let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
2280
2281         let pat = self.recover_parens_around_for_head(pat, begin_paren);
2282
2283         let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
2284         attrs.extend(iattrs);
2285
2286         let kind = ExprKind::ForLoop(pat, expr, loop_block, opt_label);
2287         Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
2288     }
2289
2290     fn error_missing_in_for_loop(&mut self) {
2291         let (span, msg, sugg) = if self.token.is_ident_named(sym::of) {
2292             // Possibly using JS syntax (#75311).
2293             let span = self.token.span;
2294             self.bump();
2295             (span, "try using `in` here instead", "in")
2296         } else {
2297             (self.prev_token.span.between(self.token.span), "try adding `in` here", " in ")
2298         };
2299         self.struct_span_err(span, "missing `in` in `for` loop")
2300             .span_suggestion_short(
2301                 span,
2302                 msg,
2303                 sugg.into(),
2304                 // Has been misleading, at least in the past (closed Issue #48492).
2305                 Applicability::MaybeIncorrect,
2306             )
2307             .emit();
2308     }
2309
2310     /// Parses a `while` or `while let` expression (`while` token already eaten).
2311     fn parse_while_expr(
2312         &mut self,
2313         opt_label: Option<Label>,
2314         lo: Span,
2315         mut attrs: AttrVec,
2316     ) -> PResult<'a, P<Expr>> {
2317         let cond = self.parse_cond_expr().map_err(|mut err| {
2318             err.span_label(lo, "while parsing the condition of this `while` expression");
2319             err
2320         })?;
2321         let (iattrs, body) = self.parse_inner_attrs_and_block().map_err(|mut err| {
2322             err.span_label(lo, "while parsing the body of this `while` expression");
2323             err.span_label(cond.span, "this `while` condition successfully parsed");
2324             err
2325         })?;
2326         attrs.extend(iattrs);
2327         Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::While(cond, body, opt_label), attrs))
2328     }
2329
2330     /// Parses `loop { ... }` (`loop` token already eaten).
2331     fn parse_loop_expr(
2332         &mut self,
2333         opt_label: Option<Label>,
2334         lo: Span,
2335         mut attrs: AttrVec,
2336     ) -> PResult<'a, P<Expr>> {
2337         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2338         attrs.extend(iattrs);
2339         Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::Loop(body, opt_label), attrs))
2340     }
2341
2342     crate fn eat_label(&mut self) -> Option<Label> {
2343         self.token.lifetime().map(|ident| {
2344             self.bump();
2345             Label { ident }
2346         })
2347     }
2348
2349     /// Parses a `match ... { ... }` expression (`match` token already eaten).
2350     fn parse_match_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2351         let match_span = self.prev_token.span;
2352         let lo = self.prev_token.span;
2353         let scrutinee = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
2354         if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
2355             if self.token == token::Semi {
2356                 e.span_suggestion_short(
2357                     match_span,
2358                     "try removing this `match`",
2359                     String::new(),
2360                     Applicability::MaybeIncorrect, // speculative
2361                 );
2362             }
2363             if self.maybe_recover_unexpected_block_label() {
2364                 e.cancel();
2365                 self.bump();
2366             } else {
2367                 return Err(e);
2368             }
2369         }
2370         attrs.extend(self.parse_inner_attributes()?);
2371
2372         let mut arms: Vec<Arm> = Vec::new();
2373         while self.token != token::CloseDelim(token::Brace) {
2374             match self.parse_arm() {
2375                 Ok(arm) => arms.push(arm),
2376                 Err(mut e) => {
2377                     // Recover by skipping to the end of the block.
2378                     e.emit();
2379                     self.recover_stmt();
2380                     let span = lo.to(self.token.span);
2381                     if self.token == token::CloseDelim(token::Brace) {
2382                         self.bump();
2383                     }
2384                     return Ok(self.mk_expr(span, ExprKind::Match(scrutinee, arms), attrs));
2385                 }
2386             }
2387         }
2388         let hi = self.token.span;
2389         self.bump();
2390         Ok(self.mk_expr(lo.to(hi), ExprKind::Match(scrutinee, arms), attrs))
2391     }
2392
2393     /// Attempt to recover from match arm body with statements and no surrounding braces.
2394     fn parse_arm_body_missing_braces(
2395         &mut self,
2396         first_expr: &P<Expr>,
2397         arrow_span: Span,
2398     ) -> Option<P<Expr>> {
2399         if self.token.kind != token::Semi {
2400             return None;
2401         }
2402         let start_snapshot = self.create_snapshot_for_diagnostic();
2403         let semi_sp = self.token.span;
2404         self.bump(); // `;`
2405         let mut stmts =
2406             vec![self.mk_stmt(first_expr.span, ast::StmtKind::Expr(first_expr.clone()))];
2407         let err = |this: &mut Parser<'_>, stmts: Vec<ast::Stmt>| {
2408             let span = stmts[0].span.to(stmts[stmts.len() - 1].span);
2409             let mut err = this.struct_span_err(span, "`match` arm body without braces");
2410             let (these, s, are) =
2411                 if stmts.len() > 1 { ("these", "s", "are") } else { ("this", "", "is") };
2412             err.span_label(
2413                 span,
2414                 &format!(
2415                     "{these} statement{s} {are} not surrounded by a body",
2416                     these = these,
2417                     s = s,
2418                     are = are
2419                 ),
2420             );
2421             err.span_label(arrow_span, "while parsing the `match` arm starting here");
2422             if stmts.len() > 1 {
2423                 err.multipart_suggestion(
2424                     &format!("surround the statement{s} with a body"),
2425                     vec![
2426                         (span.shrink_to_lo(), "{ ".to_string()),
2427                         (span.shrink_to_hi(), " }".to_string()),
2428                     ],
2429                     Applicability::MachineApplicable,
2430                 );
2431             } else {
2432                 err.span_suggestion(
2433                     semi_sp,
2434                     "use a comma to end a `match` arm expression",
2435                     ",".to_string(),
2436                     Applicability::MachineApplicable,
2437                 );
2438             }
2439             err.emit();
2440             this.mk_expr_err(span)
2441         };
2442         // We might have either a `,` -> `;` typo, or a block without braces. We need
2443         // a more subtle parsing strategy.
2444         loop {
2445             if self.token.kind == token::CloseDelim(token::Brace) {
2446                 // We have reached the closing brace of the `match` expression.
2447                 return Some(err(self, stmts));
2448             }
2449             if self.token.kind == token::Comma {
2450                 self.restore_snapshot(start_snapshot);
2451                 return None;
2452             }
2453             let pre_pat_snapshot = self.create_snapshot_for_diagnostic();
2454             match self.parse_pat_no_top_alt(None) {
2455                 Ok(_pat) => {
2456                     if self.token.kind == token::FatArrow {
2457                         // Reached arm end.
2458                         self.restore_snapshot(pre_pat_snapshot);
2459                         return Some(err(self, stmts));
2460                     }
2461                 }
2462                 Err(err) => {
2463                     err.cancel();
2464                 }
2465             }
2466
2467             self.restore_snapshot(pre_pat_snapshot);
2468             match self.parse_stmt_without_recovery(true, ForceCollect::No) {
2469                 // Consume statements for as long as possible.
2470                 Ok(Some(stmt)) => {
2471                     stmts.push(stmt);
2472                 }
2473                 Ok(None) => {
2474                     self.restore_snapshot(start_snapshot);
2475                     break;
2476                 }
2477                 // We couldn't parse either yet another statement missing it's
2478                 // enclosing block nor the next arm's pattern or closing brace.
2479                 Err(stmt_err) => {
2480                     stmt_err.cancel();
2481                     self.restore_snapshot(start_snapshot);
2482                     break;
2483                 }
2484             }
2485         }
2486         None
2487     }
2488
2489     pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
2490         fn check_let_expr(expr: &Expr) -> (bool, bool) {
2491             match expr.kind {
2492                 ExprKind::Binary(_, ref lhs, ref rhs) => {
2493                     let lhs_rslt = check_let_expr(lhs);
2494                     let rhs_rslt = check_let_expr(rhs);
2495                     (lhs_rslt.0 || rhs_rslt.0, false)
2496                 }
2497                 ExprKind::Let(..) => (true, true),
2498                 _ => (false, true),
2499             }
2500         }
2501         let attrs = self.parse_outer_attributes()?;
2502         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2503             let lo = this.token.span;
2504             let pat = this.parse_pat_allow_top_alt(
2505                 None,
2506                 RecoverComma::Yes,
2507                 RecoverColon::Yes,
2508                 CommaRecoveryMode::EitherTupleOrPipe,
2509             )?;
2510             let guard = if this.eat_keyword(kw::If) {
2511                 let if_span = this.prev_token.span;
2512                 let cond = this.parse_expr()?;
2513                 let (has_let_expr, does_not_have_bin_op) = check_let_expr(&cond);
2514                 if has_let_expr {
2515                     if does_not_have_bin_op {
2516                         // Remove the last feature gating of a `let` expression since it's stable.
2517                         this.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2518                     }
2519                     let span = if_span.to(cond.span);
2520                     this.sess.gated_spans.gate(sym::if_let_guard, span);
2521                 }
2522                 Some(cond)
2523             } else {
2524                 None
2525             };
2526             let arrow_span = this.token.span;
2527             if let Err(mut err) = this.expect(&token::FatArrow) {
2528                 // We might have a `=>` -> `=` or `->` typo (issue #89396).
2529                 if TokenKind::FatArrow
2530                     .similar_tokens()
2531                     .map_or(false, |similar_tokens| similar_tokens.contains(&this.token.kind))
2532                 {
2533                     err.span_suggestion(
2534                         this.token.span,
2535                         "try using a fat arrow here",
2536                         "=>".to_string(),
2537                         Applicability::MaybeIncorrect,
2538                     );
2539                     err.emit();
2540                     this.bump();
2541                 } else {
2542                     return Err(err);
2543                 }
2544             }
2545             let arm_start_span = this.token.span;
2546
2547             let expr = this.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| {
2548                 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2549                 err
2550             })?;
2551
2552             let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
2553                 && this.token != token::CloseDelim(token::Brace);
2554
2555             let hi = this.prev_token.span;
2556
2557             if require_comma {
2558                 let sm = this.sess.source_map();
2559                 if let Some(body) = this.parse_arm_body_missing_braces(&expr, arrow_span) {
2560                     let span = body.span;
2561                     return Ok((
2562                         ast::Arm {
2563                             attrs: attrs.into(),
2564                             pat,
2565                             guard,
2566                             body,
2567                             span,
2568                             id: DUMMY_NODE_ID,
2569                             is_placeholder: false,
2570                         },
2571                         TrailingToken::None,
2572                     ));
2573                 }
2574                 this.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]).map_err(
2575                     |mut err| {
2576                         match (sm.span_to_lines(expr.span), sm.span_to_lines(arm_start_span)) {
2577                             (Ok(ref expr_lines), Ok(ref arm_start_lines))
2578                                 if arm_start_lines.lines[0].end_col
2579                                     == expr_lines.lines[0].end_col
2580                                     && expr_lines.lines.len() == 2
2581                                     && this.token == token::FatArrow =>
2582                             {
2583                                 // We check whether there's any trailing code in the parse span,
2584                                 // if there isn't, we very likely have the following:
2585                                 //
2586                                 // X |     &Y => "y"
2587                                 //   |        --    - missing comma
2588                                 //   |        |
2589                                 //   |        arrow_span
2590                                 // X |     &X => "x"
2591                                 //   |      - ^^ self.token.span
2592                                 //   |      |
2593                                 //   |      parsed until here as `"y" & X`
2594                                 err.span_suggestion_short(
2595                                     arm_start_span.shrink_to_hi(),
2596                                     "missing a comma here to end this `match` arm",
2597                                     ",".to_owned(),
2598                                     Applicability::MachineApplicable,
2599                                 );
2600                             }
2601                             _ => {
2602                                 err.span_label(
2603                                     arrow_span,
2604                                     "while parsing the `match` arm starting here",
2605                                 );
2606                             }
2607                         }
2608                         err
2609                     },
2610                 )?;
2611             } else {
2612                 this.eat(&token::Comma);
2613             }
2614
2615             Ok((
2616                 ast::Arm {
2617                     attrs: attrs.into(),
2618                     pat,
2619                     guard,
2620                     body: expr,
2621                     span: lo.to(hi),
2622                     id: DUMMY_NODE_ID,
2623                     is_placeholder: false,
2624                 },
2625                 TrailingToken::None,
2626             ))
2627         })
2628     }
2629
2630     /// Parses a `try {...}` expression (`try` token already eaten).
2631     fn parse_try_block(&mut self, span_lo: Span, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2632         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2633         attrs.extend(iattrs);
2634         if self.eat_keyword(kw::Catch) {
2635             let mut error = self.struct_span_err(
2636                 self.prev_token.span,
2637                 "keyword `catch` cannot follow a `try` block",
2638             );
2639             error.help("try using `match` on the result of the `try` block instead");
2640             error.emit();
2641             Err(error)
2642         } else {
2643             let span = span_lo.to(body.span);
2644             self.sess.gated_spans.gate(sym::try_blocks, span);
2645             Ok(self.mk_expr(span, ExprKind::TryBlock(body), attrs))
2646         }
2647     }
2648
2649     fn is_do_catch_block(&self) -> bool {
2650         self.token.is_keyword(kw::Do)
2651             && self.is_keyword_ahead(1, &[kw::Catch])
2652             && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2653             && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
2654     }
2655
2656     fn is_try_block(&self) -> bool {
2657         self.token.is_keyword(kw::Try)
2658             && self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2659             && self.token.uninterpolated_span().rust_2018()
2660     }
2661
2662     /// Parses an `async move? {...}` expression.
2663     fn parse_async_block(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2664         let lo = self.token.span;
2665         self.expect_keyword(kw::Async)?;
2666         let capture_clause = self.parse_capture_clause()?;
2667         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2668         attrs.extend(iattrs);
2669         let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);
2670         Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
2671     }
2672
2673     fn is_async_block(&self) -> bool {
2674         self.token.is_keyword(kw::Async)
2675             && ((
2676                 // `async move {`
2677                 self.is_keyword_ahead(1, &[kw::Move])
2678                     && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2679             ) || (
2680                 // `async {`
2681                 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2682             ))
2683     }
2684
2685     fn is_certainly_not_a_block(&self) -> bool {
2686         self.look_ahead(1, |t| t.is_ident())
2687             && (
2688                 // `{ ident, ` cannot start a block.
2689                 self.look_ahead(2, |t| t == &token::Comma)
2690                     || self.look_ahead(2, |t| t == &token::Colon)
2691                         && (
2692                             // `{ ident: token, ` cannot start a block.
2693                             self.look_ahead(4, |t| t == &token::Comma) ||
2694                 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
2695                 self.look_ahead(3, |t| !t.can_begin_type())
2696                         )
2697             )
2698     }
2699
2700     fn maybe_parse_struct_expr(
2701         &mut self,
2702         qself: Option<&ast::QSelf>,
2703         path: &ast::Path,
2704         attrs: &AttrVec,
2705     ) -> Option<PResult<'a, P<Expr>>> {
2706         let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2707         if struct_allowed || self.is_certainly_not_a_block() {
2708             if let Err(err) = self.expect(&token::OpenDelim(token::Brace)) {
2709                 return Some(Err(err));
2710             }
2711             let expr = self.parse_struct_expr(qself.cloned(), path.clone(), attrs.clone(), true);
2712             if let (Ok(expr), false) = (&expr, struct_allowed) {
2713                 // This is a struct literal, but we don't can't accept them here.
2714                 self.error_struct_lit_not_allowed_here(path.span, expr.span);
2715             }
2716             return Some(expr);
2717         }
2718         None
2719     }
2720
2721     fn error_struct_lit_not_allowed_here(&self, lo: Span, sp: Span) {
2722         self.struct_span_err(sp, "struct literals are not allowed here")
2723             .multipart_suggestion(
2724                 "surround the struct literal with parentheses",
2725                 vec![(lo.shrink_to_lo(), "(".to_string()), (sp.shrink_to_hi(), ")".to_string())],
2726                 Applicability::MachineApplicable,
2727             )
2728             .emit();
2729     }
2730
2731     pub(super) fn parse_struct_fields(
2732         &mut self,
2733         pth: ast::Path,
2734         recover: bool,
2735         close_delim: token::DelimToken,
2736     ) -> PResult<'a, (Vec<ExprField>, ast::StructRest, bool)> {
2737         let mut fields = Vec::new();
2738         let mut base = ast::StructRest::None;
2739         let mut recover_async = false;
2740
2741         let mut async_block_err = |e: &mut Diagnostic, span: Span| {
2742             recover_async = true;
2743             e.span_label(span, "`async` blocks are only allowed in Rust 2018 or later");
2744             e.help_use_latest_edition();
2745         };
2746
2747         while self.token != token::CloseDelim(close_delim) {
2748             if self.eat(&token::DotDot) {
2749                 let exp_span = self.prev_token.span;
2750                 // We permit `.. }` on the left-hand side of a destructuring assignment.
2751                 if self.check(&token::CloseDelim(close_delim)) {
2752                     base = ast::StructRest::Rest(self.prev_token.span.shrink_to_hi());
2753                     break;
2754                 }
2755                 match self.parse_expr() {
2756                     Ok(e) => base = ast::StructRest::Base(e),
2757                     Err(mut e) if recover => {
2758                         e.emit();
2759                         self.recover_stmt();
2760                     }
2761                     Err(e) => return Err(e),
2762                 }
2763                 self.recover_struct_comma_after_dotdot(exp_span);
2764                 break;
2765             }
2766
2767             let recovery_field = self.find_struct_error_after_field_looking_code();
2768             let parsed_field = match self.parse_expr_field() {
2769                 Ok(f) => Some(f),
2770                 Err(mut e) => {
2771                     if pth == kw::Async {
2772                         async_block_err(&mut e, pth.span);
2773                     } else {
2774                         e.span_label(pth.span, "while parsing this struct");
2775                     }
2776                     e.emit();
2777
2778                     // If the next token is a comma, then try to parse
2779                     // what comes next as additional fields, rather than
2780                     // bailing out until next `}`.
2781                     if self.token != token::Comma {
2782                         self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2783                         if self.token != token::Comma {
2784                             break;
2785                         }
2786                     }
2787                     None
2788                 }
2789             };
2790
2791             match self.expect_one_of(&[token::Comma], &[token::CloseDelim(close_delim)]) {
2792                 Ok(_) => {
2793                     if let Some(f) = parsed_field.or(recovery_field) {
2794                         // Only include the field if there's no parse error for the field name.
2795                         fields.push(f);
2796                     }
2797                 }
2798                 Err(mut e) => {
2799                     if pth == kw::Async {
2800                         async_block_err(&mut e, pth.span);
2801                     } else {
2802                         e.span_label(pth.span, "while parsing this struct");
2803                         if let Some(f) = recovery_field {
2804                             fields.push(f);
2805                             e.span_suggestion(
2806                                 self.prev_token.span.shrink_to_hi(),
2807                                 "try adding a comma",
2808                                 ",".into(),
2809                                 Applicability::MachineApplicable,
2810                             );
2811                         }
2812                     }
2813                     if !recover {
2814                         return Err(e);
2815                     }
2816                     e.emit();
2817                     self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2818                     self.eat(&token::Comma);
2819                 }
2820             }
2821         }
2822         Ok((fields, base, recover_async))
2823     }
2824
2825     /// Precondition: already parsed the '{'.
2826     pub(super) fn parse_struct_expr(
2827         &mut self,
2828         qself: Option<ast::QSelf>,
2829         pth: ast::Path,
2830         attrs: AttrVec,
2831         recover: bool,
2832     ) -> PResult<'a, P<Expr>> {
2833         let lo = pth.span;
2834         let (fields, base, recover_async) =
2835             self.parse_struct_fields(pth.clone(), recover, token::Brace)?;
2836         let span = lo.to(self.token.span);
2837         self.expect(&token::CloseDelim(token::Brace))?;
2838         let expr = if recover_async {
2839             ExprKind::Err
2840         } else {
2841             ExprKind::Struct(P(ast::StructExpr { qself, path: pth, fields, rest: base }))
2842         };
2843         Ok(self.mk_expr(span, expr, attrs))
2844     }
2845
2846     /// Use in case of error after field-looking code: `S { foo: () with a }`.
2847     fn find_struct_error_after_field_looking_code(&self) -> Option<ExprField> {
2848         match self.token.ident() {
2849             Some((ident, is_raw))
2850                 if (is_raw || !ident.is_reserved())
2851                     && self.look_ahead(1, |t| *t == token::Colon) =>
2852             {
2853                 Some(ast::ExprField {
2854                     ident,
2855                     span: self.token.span,
2856                     expr: self.mk_expr_err(self.token.span),
2857                     is_shorthand: false,
2858                     attrs: AttrVec::new(),
2859                     id: DUMMY_NODE_ID,
2860                     is_placeholder: false,
2861                 })
2862             }
2863             _ => None,
2864         }
2865     }
2866
2867     fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
2868         if self.token != token::Comma {
2869             return;
2870         }
2871         self.struct_span_err(
2872             span.to(self.prev_token.span),
2873             "cannot use a comma after the base struct",
2874         )
2875         .span_suggestion_short(
2876             self.token.span,
2877             "remove this comma",
2878             String::new(),
2879             Applicability::MachineApplicable,
2880         )
2881         .note("the base struct must always be the last field")
2882         .emit();
2883         self.recover_stmt();
2884     }
2885
2886     /// Parses `ident (COLON expr)?`.
2887     fn parse_expr_field(&mut self) -> PResult<'a, ExprField> {
2888         let attrs = self.parse_outer_attributes()?;
2889         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2890             let lo = this.token.span;
2891
2892             // Check if a colon exists one ahead. This means we're parsing a fieldname.
2893             let is_shorthand = !this.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
2894             let (ident, expr) = if is_shorthand {
2895                 // Mimic `x: x` for the `x` field shorthand.
2896                 let ident = this.parse_ident_common(false)?;
2897                 let path = ast::Path::from_ident(ident);
2898                 (ident, this.mk_expr(ident.span, ExprKind::Path(None, path), AttrVec::new()))
2899             } else {
2900                 let ident = this.parse_field_name()?;
2901                 this.error_on_eq_field_init(ident);
2902                 this.bump(); // `:`
2903                 (ident, this.parse_expr()?)
2904             };
2905
2906             Ok((
2907                 ast::ExprField {
2908                     ident,
2909                     span: lo.to(expr.span),
2910                     expr,
2911                     is_shorthand,
2912                     attrs: attrs.into(),
2913                     id: DUMMY_NODE_ID,
2914                     is_placeholder: false,
2915                 },
2916                 TrailingToken::MaybeComma,
2917             ))
2918         })
2919     }
2920
2921     /// Check for `=`. This means the source incorrectly attempts to
2922     /// initialize a field with an eq rather than a colon.
2923     fn error_on_eq_field_init(&self, field_name: Ident) {
2924         if self.token != token::Eq {
2925             return;
2926         }
2927
2928         self.struct_span_err(self.token.span, "expected `:`, found `=`")
2929             .span_suggestion(
2930                 field_name.span.shrink_to_hi().to(self.token.span),
2931                 "replace equals symbol with a colon",
2932                 ":".to_string(),
2933                 Applicability::MachineApplicable,
2934             )
2935             .emit();
2936     }
2937
2938     fn err_dotdotdot_syntax(&self, span: Span) {
2939         self.struct_span_err(span, "unexpected token: `...`")
2940             .span_suggestion(
2941                 span,
2942                 "use `..` for an exclusive range",
2943                 "..".to_owned(),
2944                 Applicability::MaybeIncorrect,
2945             )
2946             .span_suggestion(
2947                 span,
2948                 "or `..=` for an inclusive range",
2949                 "..=".to_owned(),
2950                 Applicability::MaybeIncorrect,
2951             )
2952             .emit();
2953     }
2954
2955     fn err_larrow_operator(&self, span: Span) {
2956         self.struct_span_err(span, "unexpected token: `<-`")
2957             .span_suggestion(
2958                 span,
2959                 "if you meant to write a comparison against a negative value, add a \
2960              space in between `<` and `-`",
2961                 "< -".to_string(),
2962                 Applicability::MaybeIncorrect,
2963             )
2964             .emit();
2965     }
2966
2967     fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2968         ExprKind::AssignOp(binop, lhs, rhs)
2969     }
2970
2971     fn mk_range(
2972         &mut self,
2973         start: Option<P<Expr>>,
2974         end: Option<P<Expr>>,
2975         limits: RangeLimits,
2976     ) -> ExprKind {
2977         if end.is_none() && limits == RangeLimits::Closed {
2978             self.inclusive_range_with_incorrect_end(self.prev_token.span);
2979             ExprKind::Err
2980         } else {
2981             ExprKind::Range(start, end, limits)
2982         }
2983     }
2984
2985     fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
2986         ExprKind::Unary(unop, expr)
2987     }
2988
2989     fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2990         ExprKind::Binary(binop, lhs, rhs)
2991     }
2992
2993     fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
2994         ExprKind::Index(expr, idx)
2995     }
2996
2997     fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
2998         ExprKind::Call(f, args)
2999     }
3000
3001     fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> P<Expr> {
3002         let span = lo.to(self.prev_token.span);
3003         let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), AttrVec::new());
3004         self.recover_from_await_method_call();
3005         await_expr
3006     }
3007
3008     crate fn mk_expr(&self, span: Span, kind: ExprKind, attrs: AttrVec) -> P<Expr> {
3009         P(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None })
3010     }
3011
3012     pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
3013         self.mk_expr(span, ExprKind::Err, AttrVec::new())
3014     }
3015
3016     /// Create expression span ensuring the span of the parent node
3017     /// is larger than the span of lhs and rhs, including the attributes.
3018     fn mk_expr_sp(&self, lhs: &P<Expr>, lhs_span: Span, rhs_span: Span) -> Span {
3019         lhs.attrs
3020             .iter()
3021             .find(|a| a.style == AttrStyle::Outer)
3022             .map_or(lhs_span, |a| a.span)
3023             .to(rhs_span)
3024     }
3025
3026     fn collect_tokens_for_expr(
3027         &mut self,
3028         attrs: AttrWrapper,
3029         f: impl FnOnce(&mut Self, Vec<ast::Attribute>) -> PResult<'a, P<Expr>>,
3030     ) -> PResult<'a, P<Expr>> {
3031         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
3032             let res = f(this, attrs)?;
3033             let trailing = if this.restrictions.contains(Restrictions::STMT_EXPR)
3034                 && this.token.kind == token::Semi
3035             {
3036                 TrailingToken::Semi
3037             } else {
3038                 // FIXME - pass this through from the place where we know
3039                 // we need a comma, rather than assuming that `#[attr] expr,`
3040                 // always captures a trailing comma
3041                 TrailingToken::MaybeComma
3042             };
3043             Ok((res, trailing))
3044         })
3045     }
3046 }