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