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