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