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