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