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