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