]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/expr.rs
Add support for using qualified paths with structs in expression and pattern
[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.check_path() {
1112             self.parse_path_start_expr(attrs)
1113         } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
1114             self.parse_closure_expr(attrs)
1115         } else if self.eat_keyword(kw::If) {
1116             self.parse_if_expr(attrs)
1117         } else if self.check_keyword(kw::For) {
1118             if self.choose_generics_over_qpath(1) {
1119                 // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery,
1120                 // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns.
1121                 // When `for <Foo as Bar>::Proj in $expr $block` is wanted,
1122                 // you can disambiguate in favor of a pattern with `(...)`.
1123                 self.recover_quantified_closure_expr(attrs)
1124             } else {
1125                 assert!(self.eat_keyword(kw::For));
1126                 self.parse_for_expr(None, self.prev_token.span, attrs)
1127             }
1128         } else if self.eat_keyword(kw::While) {
1129             self.parse_while_expr(None, self.prev_token.span, attrs)
1130         } else if let Some(label) = self.eat_label() {
1131             self.parse_labeled_expr(label, attrs, true)
1132         } else if self.eat_keyword(kw::Loop) {
1133             self.parse_loop_expr(None, self.prev_token.span, attrs)
1134         } else if self.eat_keyword(kw::Continue) {
1135             let kind = ExprKind::Continue(self.eat_label());
1136             Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1137         } else if self.eat_keyword(kw::Match) {
1138             let match_sp = self.prev_token.span;
1139             self.parse_match_expr(attrs).map_err(|mut err| {
1140                 err.span_label(match_sp, "while parsing this match expression");
1141                 err
1142             })
1143         } else if self.eat_keyword(kw::Unsafe) {
1144             self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs)
1145         } else if self.check_inline_const(0) {
1146             self.parse_const_block(lo.to(self.token.span))
1147         } else if self.is_do_catch_block() {
1148             self.recover_do_catch(attrs)
1149         } else if self.is_try_block() {
1150             self.expect_keyword(kw::Try)?;
1151             self.parse_try_block(lo, attrs)
1152         } else if self.eat_keyword(kw::Return) {
1153             self.parse_return_expr(attrs)
1154         } else if self.eat_keyword(kw::Break) {
1155             self.parse_break_expr(attrs)
1156         } else if self.eat_keyword(kw::Yield) {
1157             self.parse_yield_expr(attrs)
1158         } else if self.eat_keyword(kw::Let) {
1159             self.parse_let_expr(attrs)
1160         } else if self.eat_keyword(kw::Underscore) {
1161             self.sess.gated_spans.gate(sym::destructuring_assignment, self.prev_token.span);
1162             Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore, attrs))
1163         } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1164             // Don't complain about bare semicolons after unclosed braces
1165             // recovery in order to keep the error count down. Fixing the
1166             // delimiters will possibly also fix the bare semicolon found in
1167             // expression context. For example, silence the following error:
1168             //
1169             //     error: expected expression, found `;`
1170             //      --> file.rs:2:13
1171             //       |
1172             //     2 |     foo(bar(;
1173             //       |             ^ expected expression
1174             self.bump();
1175             Ok(self.mk_expr_err(self.token.span))
1176         } else if self.token.uninterpolated_span().rust_2018() {
1177             // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1178             if self.check_keyword(kw::Async) {
1179                 if self.is_async_block() {
1180                     // Check for `async {` and `async move {`.
1181                     self.parse_async_block(attrs)
1182                 } else {
1183                     self.parse_closure_expr(attrs)
1184                 }
1185             } else if self.eat_keyword(kw::Await) {
1186                 self.recover_incorrect_await_syntax(lo, self.prev_token.span, attrs)
1187             } else {
1188                 self.parse_lit_expr(attrs)
1189             }
1190         } else {
1191             self.parse_lit_expr(attrs)
1192         }
1193     }
1194
1195     fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1196         let lo = self.token.span;
1197         match self.parse_opt_lit() {
1198             Some(literal) => {
1199                 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs);
1200                 self.maybe_recover_from_bad_qpath(expr, true)
1201             }
1202             None => self.try_macro_suggestion(),
1203         }
1204     }
1205
1206     fn parse_tuple_parens_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1207         let lo = self.token.span;
1208         self.expect(&token::OpenDelim(token::Paren))?;
1209         let (es, trailing_comma) = match self.parse_seq_to_end(
1210             &token::CloseDelim(token::Paren),
1211             SeqSep::trailing_allowed(token::Comma),
1212             |p| p.parse_expr_catch_underscore(),
1213         ) {
1214             Ok(x) => x,
1215             Err(err) => return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err))),
1216         };
1217         let kind = if es.len() == 1 && !trailing_comma {
1218             // `(e)` is parenthesized `e`.
1219             ExprKind::Paren(es.into_iter().next().unwrap())
1220         } else {
1221             // `(e,)` is a tuple with only one field, `e`.
1222             ExprKind::Tup(es)
1223         };
1224         let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1225         self.maybe_recover_from_bad_qpath(expr, true)
1226     }
1227
1228     fn parse_array_or_repeat_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1229         let lo = self.token.span;
1230         self.bump(); // `[`
1231
1232         let close = &token::CloseDelim(token::Bracket);
1233         let kind = if self.eat(close) {
1234             // Empty vector
1235             ExprKind::Array(Vec::new())
1236         } else {
1237             // Non-empty vector
1238             let first_expr = self.parse_expr()?;
1239             if self.eat(&token::Semi) {
1240                 // Repeating array syntax: `[ 0; 512 ]`
1241                 let count = self.parse_anon_const_expr()?;
1242                 self.expect(close)?;
1243                 ExprKind::Repeat(first_expr, count)
1244             } else if self.eat(&token::Comma) {
1245                 // Vector with two or more elements.
1246                 let sep = SeqSep::trailing_allowed(token::Comma);
1247                 let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1248                 let mut exprs = vec![first_expr];
1249                 exprs.extend(remaining_exprs);
1250                 ExprKind::Array(exprs)
1251             } else {
1252                 // Vector with one element
1253                 self.expect(close)?;
1254                 ExprKind::Array(vec![first_expr])
1255             }
1256         };
1257         let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1258         self.maybe_recover_from_bad_qpath(expr, true)
1259     }
1260
1261     fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1262         let (qself, path) = if self.eat_lt() {
1263             let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
1264             (Some(qself), path)
1265         } else {
1266             (None, self.parse_path(PathStyle::Expr)?)
1267         };
1268         let lo = path.span;
1269
1270         // `!`, as an operator, is prefix, so we know this isn't that.
1271         let (hi, kind) = if self.eat(&token::Not) {
1272             // MACRO INVOCATION expression
1273             if qself.is_some() {
1274                 self.struct_span_err(path.span, "macros cannot use qualified paths").emit();
1275             }
1276             let mac = MacCall {
1277                 path,
1278                 args: self.parse_mac_args()?,
1279                 prior_type_ascription: self.last_type_ascription,
1280             };
1281             (self.prev_token.span, ExprKind::MacCall(mac))
1282         } else if self.check(&token::OpenDelim(token::Brace)) {
1283             if let Some(expr) = self.maybe_parse_struct_expr(qself.as_ref(), &path, &attrs) {
1284                 if qself.is_some() {
1285                     self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
1286                 }
1287                 return expr;
1288             } else {
1289                 (path.span, ExprKind::Path(qself, path))
1290             }
1291         } else {
1292             (path.span, ExprKind::Path(qself, path))
1293         };
1294
1295         let expr = self.mk_expr(lo.to(hi), kind, attrs);
1296         self.maybe_recover_from_bad_qpath(expr, true)
1297     }
1298
1299     /// Parse `'label: $expr`. The label is already parsed.
1300     fn parse_labeled_expr(
1301         &mut self,
1302         label: Label,
1303         attrs: AttrVec,
1304         consume_colon: bool,
1305     ) -> PResult<'a, P<Expr>> {
1306         let lo = label.ident.span;
1307         let label = Some(label);
1308         let ate_colon = self.eat(&token::Colon);
1309         let expr = if self.eat_keyword(kw::While) {
1310             self.parse_while_expr(label, lo, attrs)
1311         } else if self.eat_keyword(kw::For) {
1312             self.parse_for_expr(label, lo, attrs)
1313         } else if self.eat_keyword(kw::Loop) {
1314             self.parse_loop_expr(label, lo, attrs)
1315         } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1316             self.parse_block_expr(label, lo, BlockCheckMode::Default, attrs)
1317         } else {
1318             let msg = "expected `while`, `for`, `loop` or `{` after a label";
1319             self.struct_span_err(self.token.span, msg).span_label(self.token.span, msg).emit();
1320             // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1321             self.parse_expr()
1322         }?;
1323
1324         if !ate_colon && consume_colon {
1325             self.error_labeled_expr_must_be_followed_by_colon(lo, expr.span);
1326         }
1327
1328         Ok(expr)
1329     }
1330
1331     fn error_labeled_expr_must_be_followed_by_colon(&self, lo: Span, span: Span) {
1332         self.struct_span_err(span, "labeled expression must be followed by `:`")
1333             .span_label(lo, "the label")
1334             .span_suggestion_short(
1335                 lo.shrink_to_hi(),
1336                 "add `:` after the label",
1337                 ": ".to_string(),
1338                 Applicability::MachineApplicable,
1339             )
1340             .note("labels are used before loops and blocks, allowing e.g., `break 'label` to them")
1341             .emit();
1342     }
1343
1344     /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1345     fn recover_do_catch(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1346         let lo = self.token.span;
1347
1348         self.bump(); // `do`
1349         self.bump(); // `catch`
1350
1351         let span_dc = lo.to(self.prev_token.span);
1352         self.struct_span_err(span_dc, "found removed `do catch` syntax")
1353             .span_suggestion(
1354                 span_dc,
1355                 "replace with the new syntax",
1356                 "try".to_string(),
1357                 Applicability::MachineApplicable,
1358             )
1359             .note("following RFC #2388, the new non-placeholder syntax is `try`")
1360             .emit();
1361
1362         self.parse_try_block(lo, attrs)
1363     }
1364
1365     /// Parse an expression if the token can begin one.
1366     fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1367         Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1368     }
1369
1370     /// Parse `"return" expr?`.
1371     fn parse_return_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1372         let lo = self.prev_token.span;
1373         let kind = ExprKind::Ret(self.parse_expr_opt()?);
1374         let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1375         self.maybe_recover_from_bad_qpath(expr, true)
1376     }
1377
1378     /// Parse `"('label ":")? break expr?`.
1379     fn parse_break_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1380         let lo = self.prev_token.span;
1381         let label = self.eat_label();
1382         let kind = if self.token != token::OpenDelim(token::Brace)
1383             || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1384         {
1385             self.parse_expr_opt()?
1386         } else {
1387             None
1388         };
1389         let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind), attrs);
1390         self.maybe_recover_from_bad_qpath(expr, true)
1391     }
1392
1393     /// Parse `"yield" expr?`.
1394     fn parse_yield_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1395         let lo = self.prev_token.span;
1396         let kind = ExprKind::Yield(self.parse_expr_opt()?);
1397         let span = lo.to(self.prev_token.span);
1398         self.sess.gated_spans.gate(sym::generators, span);
1399         let expr = self.mk_expr(span, kind, attrs);
1400         self.maybe_recover_from_bad_qpath(expr, true)
1401     }
1402
1403     /// Returns a string literal if the next token is a string literal.
1404     /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1405     /// and returns `None` if the next token is not literal at all.
1406     pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
1407         match self.parse_opt_lit() {
1408             Some(lit) => match lit.kind {
1409                 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1410                     style,
1411                     symbol: lit.token.symbol,
1412                     suffix: lit.token.suffix,
1413                     span: lit.span,
1414                     symbol_unescaped,
1415                 }),
1416                 _ => Err(Some(lit)),
1417             },
1418             None => Err(None),
1419         }
1420     }
1421
1422     pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> {
1423         self.parse_opt_lit().ok_or_else(|| {
1424             let msg = format!("unexpected token: {}", super::token_descr(&self.token));
1425             self.struct_span_err(self.token.span, &msg)
1426         })
1427     }
1428
1429     /// Matches `lit = true | false | token_lit`.
1430     /// Returns `None` if the next token is not a literal.
1431     pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
1432         let mut recovered = None;
1433         if self.token == token::Dot {
1434             // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1435             // dot would follow an optional literal, so we do this unconditionally.
1436             recovered = self.look_ahead(1, |next_token| {
1437                 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1438                     next_token.kind
1439                 {
1440                     if self.token.span.hi() == next_token.span.lo() {
1441                         let s = String::from("0.") + &symbol.as_str();
1442                         let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1443                         return Some(Token::new(kind, self.token.span.to(next_token.span)));
1444                     }
1445                 }
1446                 None
1447             });
1448             if let Some(token) = &recovered {
1449                 self.bump();
1450                 self.error_float_lits_must_have_int_part(&token);
1451             }
1452         }
1453
1454         let token = recovered.as_ref().unwrap_or(&self.token);
1455         match Lit::from_token(token) {
1456             Ok(lit) => {
1457                 self.bump();
1458                 Some(lit)
1459             }
1460             Err(LitError::NotLiteral) => None,
1461             Err(err) => {
1462                 let span = token.span;
1463                 let lit = match token.kind {
1464                     token::Literal(lit) => lit,
1465                     _ => unreachable!(),
1466                 };
1467                 self.bump();
1468                 self.report_lit_error(err, lit, span);
1469                 // Pack possible quotes and prefixes from the original literal into
1470                 // the error literal's symbol so they can be pretty-printed faithfully.
1471                 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1472                 let symbol = Symbol::intern(&suffixless_lit.to_string());
1473                 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1474                 Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!()))
1475             }
1476         }
1477     }
1478
1479     fn error_float_lits_must_have_int_part(&self, token: &Token) {
1480         self.struct_span_err(token.span, "float literals must have an integer part")
1481             .span_suggestion(
1482                 token.span,
1483                 "must have an integer part",
1484                 pprust::token_to_string(token),
1485                 Applicability::MachineApplicable,
1486             )
1487             .emit();
1488     }
1489
1490     fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) {
1491         // Checks if `s` looks like i32 or u1234 etc.
1492         fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1493             s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
1494         }
1495
1496         let token::Lit { kind, suffix, .. } = lit;
1497         match err {
1498             // `NotLiteral` is not an error by itself, so we don't report
1499             // it and give the parser opportunity to try something else.
1500             LitError::NotLiteral => {}
1501             // `LexerError` *is* an error, but it was already reported
1502             // by lexer, so here we don't report it the second time.
1503             LitError::LexerError => {}
1504             LitError::InvalidSuffix => {
1505                 self.expect_no_suffix(
1506                     span,
1507                     &format!("{} {} literal", kind.article(), kind.descr()),
1508                     suffix,
1509                 );
1510             }
1511             LitError::InvalidIntSuffix => {
1512                 let suf = suffix.expect("suffix error with no suffix").as_str();
1513                 if looks_like_width_suffix(&['i', 'u'], &suf) {
1514                     // If it looks like a width, try to be helpful.
1515                     let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
1516                     self.struct_span_err(span, &msg)
1517                         .help("valid widths are 8, 16, 32, 64 and 128")
1518                         .emit();
1519                 } else {
1520                     let msg = format!("invalid suffix `{}` for number literal", suf);
1521                     self.struct_span_err(span, &msg)
1522                         .span_label(span, format!("invalid suffix `{}`", suf))
1523                         .help("the suffix must be one of the numeric types (`u32`, `isize`, `f32`, etc.)")
1524                         .emit();
1525                 }
1526             }
1527             LitError::InvalidFloatSuffix => {
1528                 let suf = suffix.expect("suffix error with no suffix").as_str();
1529                 if looks_like_width_suffix(&['f'], &suf) {
1530                     // If it looks like a width, try to be helpful.
1531                     let msg = format!("invalid width `{}` for float literal", &suf[1..]);
1532                     self.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit();
1533                 } else {
1534                     let msg = format!("invalid suffix `{}` for float literal", suf);
1535                     self.struct_span_err(span, &msg)
1536                         .span_label(span, format!("invalid suffix `{}`", suf))
1537                         .help("valid suffixes are `f32` and `f64`")
1538                         .emit();
1539                 }
1540             }
1541             LitError::NonDecimalFloat(base) => {
1542                 let descr = match base {
1543                     16 => "hexadecimal",
1544                     8 => "octal",
1545                     2 => "binary",
1546                     _ => unreachable!(),
1547                 };
1548                 self.struct_span_err(span, &format!("{} float literal is not supported", descr))
1549                     .span_label(span, "not supported")
1550                     .emit();
1551             }
1552             LitError::IntTooLarge => {
1553                 self.struct_span_err(span, "integer literal is too large").emit();
1554             }
1555         }
1556     }
1557
1558     pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) {
1559         if let Some(suf) = suffix {
1560             let mut err = if kind == "a tuple index"
1561                 && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf)
1562             {
1563                 // #59553: warn instead of reject out of hand to allow the fix to percolate
1564                 // through the ecosystem when people fix their macros
1565                 let mut err = self
1566                     .sess
1567                     .span_diagnostic
1568                     .struct_span_warn(sp, &format!("suffixes on {} are invalid", kind));
1569                 err.note(&format!(
1570                     "`{}` is *temporarily* accepted on tuple index fields as it was \
1571                         incorrectly accepted on stable for a few releases",
1572                     suf,
1573                 ));
1574                 err.help(
1575                     "on proc macros, you'll want to use `syn::Index::from` or \
1576                         `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1577                         to tuple field access",
1578                 );
1579                 err.note(
1580                     "see issue #60210 <https://github.com/rust-lang/rust/issues/60210> \
1581                      for more information",
1582                 );
1583                 err
1584             } else {
1585                 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1586             };
1587             err.span_label(sp, format!("invalid suffix `{}`", suf));
1588             err.emit();
1589         }
1590     }
1591
1592     /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1593     /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
1594     pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1595         maybe_whole_expr!(self);
1596
1597         let lo = self.token.span;
1598         let minus_present = self.eat(&token::BinOp(token::Minus));
1599         let lit = self.parse_lit()?;
1600         let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new());
1601
1602         if minus_present {
1603             Ok(self.mk_expr(
1604                 lo.to(self.prev_token.span),
1605                 self.mk_unary(UnOp::Neg, expr),
1606                 AttrVec::new(),
1607             ))
1608         } else {
1609             Ok(expr)
1610         }
1611     }
1612
1613     /// Parses a block or unsafe block.
1614     pub(super) fn parse_block_expr(
1615         &mut self,
1616         opt_label: Option<Label>,
1617         lo: Span,
1618         blk_mode: BlockCheckMode,
1619         mut attrs: AttrVec,
1620     ) -> PResult<'a, P<Expr>> {
1621         if let Some(label) = opt_label {
1622             self.sess.gated_spans.gate(sym::label_break_value, label.ident.span);
1623         }
1624
1625         if self.token.is_whole_block() {
1626             self.struct_span_err(self.token.span, "cannot use a `block` macro fragment here")
1627                 .span_label(lo.to(self.token.span), "the `block` fragment is within this context")
1628                 .emit();
1629         }
1630
1631         let (inner_attrs, blk) = self.parse_block_common(lo, blk_mode)?;
1632         attrs.extend(inner_attrs);
1633         Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs))
1634     }
1635
1636     /// Recover on an explicitly quantified closure expression, e.g., `for<'a> |x: &'a u8| *x + 1`.
1637     fn recover_quantified_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1638         let lo = self.token.span;
1639         let _ = self.parse_late_bound_lifetime_defs()?;
1640         let span_for = lo.to(self.prev_token.span);
1641         let closure = self.parse_closure_expr(attrs)?;
1642
1643         self.struct_span_err(span_for, "cannot introduce explicit parameters for a closure")
1644             .span_label(closure.span, "the parameters are attached to this closure")
1645             .span_suggestion(
1646                 span_for,
1647                 "remove the parameters",
1648                 String::new(),
1649                 Applicability::MachineApplicable,
1650             )
1651             .emit();
1652
1653         Ok(self.mk_expr_err(lo.to(closure.span)))
1654     }
1655
1656     /// Parses a closure expression (e.g., `move |args| expr`).
1657     fn parse_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1658         let lo = self.token.span;
1659
1660         let movability =
1661             if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
1662
1663         let asyncness = if self.token.uninterpolated_span().rust_2018() {
1664             self.parse_asyncness()
1665         } else {
1666             Async::No
1667         };
1668
1669         let capture_clause = self.parse_capture_clause()?;
1670         let decl = self.parse_fn_block_decl()?;
1671         let decl_hi = self.prev_token.span;
1672         let body = match decl.output {
1673             FnRetTy::Default(_) => {
1674                 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
1675                 self.parse_expr_res(restrictions, None)?
1676             }
1677             _ => {
1678                 // If an explicit return type is given, require a block to appear (RFC 968).
1679                 let body_lo = self.token.span;
1680                 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, AttrVec::new())?
1681             }
1682         };
1683
1684         if let Async::Yes { span, .. } = asyncness {
1685             // Feature-gate `async ||` closures.
1686             self.sess.gated_spans.gate(sym::async_closure, span);
1687         }
1688
1689         Ok(self.mk_expr(
1690             lo.to(body.span),
1691             ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
1692             attrs,
1693         ))
1694     }
1695
1696     /// Parses an optional `move` prefix to a closure-like construct.
1697     fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> {
1698         if self.eat_keyword(kw::Move) {
1699             // Check for `move async` and recover
1700             if self.check_keyword(kw::Async) {
1701                 let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
1702                 Err(self.incorrect_move_async_order_found(move_async_span))
1703             } else {
1704                 Ok(CaptureBy::Value)
1705             }
1706         } else {
1707             Ok(CaptureBy::Ref)
1708         }
1709     }
1710
1711     /// Parses the `|arg, arg|` header of a closure.
1712     fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
1713         let inputs = if self.eat(&token::OrOr) {
1714             Vec::new()
1715         } else {
1716             self.expect(&token::BinOp(token::Or))?;
1717             let args = self
1718                 .parse_seq_to_before_tokens(
1719                     &[&token::BinOp(token::Or), &token::OrOr],
1720                     SeqSep::trailing_allowed(token::Comma),
1721                     TokenExpectType::NoExpect,
1722                     |p| p.parse_fn_block_param(),
1723                 )?
1724                 .0;
1725             self.expect_or()?;
1726             args
1727         };
1728         let output =
1729             self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes, RecoverReturnSign::Yes)?;
1730
1731         Ok(P(FnDecl { inputs, output }))
1732     }
1733
1734     /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1735     fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
1736         let lo = self.token.span;
1737         let attrs = self.parse_outer_attributes()?;
1738         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1739             let pat = this.parse_pat_no_top_alt(PARAM_EXPECTED)?;
1740             let ty = if this.eat(&token::Colon) {
1741                 this.parse_ty()?
1742             } else {
1743                 this.mk_ty(this.prev_token.span, TyKind::Infer)
1744             };
1745
1746             Ok((
1747                 Param {
1748                     attrs: attrs.into(),
1749                     ty,
1750                     pat,
1751                     span: lo.to(this.token.span),
1752                     id: DUMMY_NODE_ID,
1753                     is_placeholder: false,
1754                 },
1755                 TrailingToken::MaybeComma,
1756             ))
1757         })
1758     }
1759
1760     /// Parses an `if` expression (`if` token already eaten).
1761     fn parse_if_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1762         let lo = self.prev_token.span;
1763         let cond = self.parse_cond_expr()?;
1764
1765         // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1766         // verify that the last statement is either an implicit return (no `;`) or an explicit
1767         // return. This won't catch blocks with an explicit `return`, but that would be caught by
1768         // the dead code lint.
1769         let thn = if self.eat_keyword(kw::Else) || !cond.returns() {
1770             self.error_missing_if_cond(lo, cond.span)
1771         } else {
1772             let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
1773             let not_block = self.token != token::OpenDelim(token::Brace);
1774             let block = self.parse_block().map_err(|mut err| {
1775                 if not_block {
1776                     err.span_label(lo, "this `if` expression has a condition, but no block");
1777                     if let ExprKind::Binary(_, _, ref right) = cond.kind {
1778                         if let ExprKind::Block(_, _) = right.kind {
1779                             err.help("maybe you forgot the right operand of the condition?");
1780                         }
1781                     }
1782                 }
1783                 err
1784             })?;
1785             self.error_on_if_block_attrs(lo, false, block.span, &attrs);
1786             block
1787         };
1788         let els = if self.eat_keyword(kw::Else) { Some(self.parse_else_expr()?) } else { None };
1789         Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els), attrs))
1790     }
1791
1792     fn error_missing_if_cond(&self, lo: Span, span: Span) -> P<ast::Block> {
1793         let sp = self.sess.source_map().next_point(lo);
1794         self.struct_span_err(sp, "missing condition for `if` expression")
1795             .span_label(sp, "expected if condition here")
1796             .emit();
1797         self.mk_block_err(span)
1798     }
1799
1800     /// Parses the condition of a `if` or `while` expression.
1801     fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
1802         let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1803
1804         if let ExprKind::Let(..) = cond.kind {
1805             // Remove the last feature gating of a `let` expression since it's stable.
1806             self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
1807         }
1808
1809         Ok(cond)
1810     }
1811
1812     /// Parses a `let $pat = $expr` pseudo-expression.
1813     /// The `let` token has already been eaten.
1814     fn parse_let_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1815         let lo = self.prev_token.span;
1816         let pat = self.parse_pat_allow_top_alt(None, RecoverComma::Yes)?;
1817         self.expect(&token::Eq)?;
1818         let expr = self.with_res(self.restrictions | Restrictions::NO_STRUCT_LITERAL, |this| {
1819             this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
1820         })?;
1821         let span = lo.to(expr.span);
1822         self.sess.gated_spans.gate(sym::let_chains, span);
1823         Ok(self.mk_expr(span, ExprKind::Let(pat, expr), attrs))
1824     }
1825
1826     /// Parses an `else { ... }` expression (`else` token already eaten).
1827     fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
1828         let ctx_span = self.prev_token.span; // `else`
1829         let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
1830         let expr = if self.eat_keyword(kw::If) {
1831             self.parse_if_expr(AttrVec::new())?
1832         } else {
1833             let blk = self.parse_block()?;
1834             self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new())
1835         };
1836         self.error_on_if_block_attrs(ctx_span, true, expr.span, &attrs);
1837         Ok(expr)
1838     }
1839
1840     fn error_on_if_block_attrs(
1841         &self,
1842         ctx_span: Span,
1843         is_ctx_else: bool,
1844         branch_span: Span,
1845         attrs: &[ast::Attribute],
1846     ) {
1847         let (span, last) = match attrs {
1848             [] => return,
1849             [x0 @ xn] | [x0, .., xn] => (x0.span.to(xn.span), xn.span),
1850         };
1851         let ctx = if is_ctx_else { "else" } else { "if" };
1852         self.struct_span_err(last, "outer attributes are not allowed on `if` and `else` branches")
1853             .span_label(branch_span, "the attributes are attached to this branch")
1854             .span_label(ctx_span, format!("the branch belongs to this `{}`", ctx))
1855             .span_suggestion(
1856                 span,
1857                 "remove the attributes",
1858                 String::new(),
1859                 Applicability::MachineApplicable,
1860             )
1861             .emit();
1862     }
1863
1864     /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
1865     fn parse_for_expr(
1866         &mut self,
1867         opt_label: Option<Label>,
1868         lo: Span,
1869         mut attrs: AttrVec,
1870     ) -> PResult<'a, P<Expr>> {
1871         // Record whether we are about to parse `for (`.
1872         // This is used below for recovery in case of `for ( $stuff ) $block`
1873         // in which case we will suggest `for $stuff $block`.
1874         let begin_paren = match self.token.kind {
1875             token::OpenDelim(token::Paren) => Some(self.token.span),
1876             _ => None,
1877         };
1878
1879         let pat = self.parse_pat_allow_top_alt(None, RecoverComma::Yes)?;
1880         if !self.eat_keyword(kw::In) {
1881             self.error_missing_in_for_loop();
1882         }
1883         self.check_for_for_in_in_typo(self.prev_token.span);
1884         let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1885
1886         let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
1887
1888         let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
1889         attrs.extend(iattrs);
1890
1891         let kind = ExprKind::ForLoop(pat, expr, loop_block, opt_label);
1892         Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1893     }
1894
1895     fn error_missing_in_for_loop(&mut self) {
1896         let (span, msg, sugg) = if self.token.is_ident_named(sym::of) {
1897             // Possibly using JS syntax (#75311).
1898             let span = self.token.span;
1899             self.bump();
1900             (span, "try using `in` here instead", "in")
1901         } else {
1902             (self.prev_token.span.between(self.token.span), "try adding `in` here", " in ")
1903         };
1904         self.struct_span_err(span, "missing `in` in `for` loop")
1905             .span_suggestion_short(
1906                 span,
1907                 msg,
1908                 sugg.into(),
1909                 // Has been misleading, at least in the past (closed Issue #48492).
1910                 Applicability::MaybeIncorrect,
1911             )
1912             .emit();
1913     }
1914
1915     /// Parses a `while` or `while let` expression (`while` token already eaten).
1916     fn parse_while_expr(
1917         &mut self,
1918         opt_label: Option<Label>,
1919         lo: Span,
1920         mut attrs: AttrVec,
1921     ) -> PResult<'a, P<Expr>> {
1922         let cond = self.parse_cond_expr()?;
1923         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1924         attrs.extend(iattrs);
1925         Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::While(cond, body, opt_label), attrs))
1926     }
1927
1928     /// Parses `loop { ... }` (`loop` token already eaten).
1929     fn parse_loop_expr(
1930         &mut self,
1931         opt_label: Option<Label>,
1932         lo: Span,
1933         mut attrs: AttrVec,
1934     ) -> PResult<'a, P<Expr>> {
1935         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1936         attrs.extend(iattrs);
1937         Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::Loop(body, opt_label), attrs))
1938     }
1939
1940     fn eat_label(&mut self) -> Option<Label> {
1941         self.token.lifetime().map(|ident| {
1942             self.bump();
1943             Label { ident }
1944         })
1945     }
1946
1947     /// Parses a `match ... { ... }` expression (`match` token already eaten).
1948     fn parse_match_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1949         let match_span = self.prev_token.span;
1950         let lo = self.prev_token.span;
1951         let scrutinee = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1952         if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
1953             if self.token == token::Semi {
1954                 e.span_suggestion_short(
1955                     match_span,
1956                     "try removing this `match`",
1957                     String::new(),
1958                     Applicability::MaybeIncorrect, // speculative
1959                 );
1960             }
1961             return Err(e);
1962         }
1963
1964         let mut arms: Vec<Arm> = Vec::new();
1965         while self.token != token::CloseDelim(token::Brace) {
1966             match self.parse_arm() {
1967                 Ok(arm) => arms.push(arm),
1968                 Err(mut e) => {
1969                     // Recover by skipping to the end of the block.
1970                     e.emit();
1971                     self.recover_stmt();
1972                     let span = lo.to(self.token.span);
1973                     if self.token == token::CloseDelim(token::Brace) {
1974                         self.bump();
1975                     }
1976                     return Ok(self.mk_expr(span, ExprKind::Match(scrutinee, arms), attrs));
1977                 }
1978             }
1979         }
1980         let hi = self.token.span;
1981         self.bump();
1982         Ok(self.mk_expr(lo.to(hi), ExprKind::Match(scrutinee, arms), attrs))
1983     }
1984
1985     /// Attempt to recover from match arm body with statements and no surrounding braces.
1986     fn parse_arm_body_missing_braces(
1987         &mut self,
1988         first_expr: &P<Expr>,
1989         arrow_span: Span,
1990     ) -> Option<P<Expr>> {
1991         if self.token.kind != token::Semi {
1992             return None;
1993         }
1994         let start_snapshot = self.clone();
1995         let semi_sp = self.token.span;
1996         self.bump(); // `;`
1997         let mut stmts =
1998             vec![self.mk_stmt(first_expr.span, ast::StmtKind::Expr(first_expr.clone()))];
1999         let err = |this: &mut Parser<'_>, stmts: Vec<ast::Stmt>| {
2000             let span = stmts[0].span.to(stmts[stmts.len() - 1].span);
2001             let mut err = this.struct_span_err(span, "`match` arm body without braces");
2002             let (these, s, are) =
2003                 if stmts.len() > 1 { ("these", "s", "are") } else { ("this", "", "is") };
2004             err.span_label(
2005                 span,
2006                 &format!(
2007                     "{these} statement{s} {are} not surrounded by a body",
2008                     these = these,
2009                     s = s,
2010                     are = are
2011                 ),
2012             );
2013             err.span_label(arrow_span, "while parsing the `match` arm starting here");
2014             if stmts.len() > 1 {
2015                 err.multipart_suggestion(
2016                     &format!("surround the statement{} with a body", s),
2017                     vec![
2018                         (span.shrink_to_lo(), "{ ".to_string()),
2019                         (span.shrink_to_hi(), " }".to_string()),
2020                     ],
2021                     Applicability::MachineApplicable,
2022                 );
2023             } else {
2024                 err.span_suggestion(
2025                     semi_sp,
2026                     "use a comma to end a `match` arm expression",
2027                     ",".to_string(),
2028                     Applicability::MachineApplicable,
2029                 );
2030             }
2031             err.emit();
2032             this.mk_expr_err(span)
2033         };
2034         // We might have either a `,` -> `;` typo, or a block without braces. We need
2035         // a more subtle parsing strategy.
2036         loop {
2037             if self.token.kind == token::CloseDelim(token::Brace) {
2038                 // We have reached the closing brace of the `match` expression.
2039                 return Some(err(self, stmts));
2040             }
2041             if self.token.kind == token::Comma {
2042                 *self = start_snapshot;
2043                 return None;
2044             }
2045             let pre_pat_snapshot = self.clone();
2046             match self.parse_pat_no_top_alt(None) {
2047                 Ok(_pat) => {
2048                     if self.token.kind == token::FatArrow {
2049                         // Reached arm end.
2050                         *self = pre_pat_snapshot;
2051                         return Some(err(self, stmts));
2052                     }
2053                 }
2054                 Err(mut err) => {
2055                     err.cancel();
2056                 }
2057             }
2058
2059             *self = pre_pat_snapshot;
2060             match self.parse_stmt_without_recovery(true, ForceCollect::No) {
2061                 // Consume statements for as long as possible.
2062                 Ok(Some(stmt)) => {
2063                     stmts.push(stmt);
2064                 }
2065                 Ok(None) => {
2066                     *self = start_snapshot;
2067                     break;
2068                 }
2069                 // We couldn't parse either yet another statement missing it's
2070                 // enclosing block nor the next arm's pattern or closing brace.
2071                 Err(mut stmt_err) => {
2072                     stmt_err.cancel();
2073                     *self = start_snapshot;
2074                     break;
2075                 }
2076             }
2077         }
2078         None
2079     }
2080
2081     pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
2082         let attrs = self.parse_outer_attributes()?;
2083         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2084             let lo = this.token.span;
2085             let pat = this.parse_pat_allow_top_alt(None, RecoverComma::Yes)?;
2086             let guard = if this.eat_keyword(kw::If) {
2087                 let if_span = this.prev_token.span;
2088                 let cond = this.parse_expr()?;
2089                 if let ExprKind::Let(..) = cond.kind {
2090                     // Remove the last feature gating of a `let` expression since it's stable.
2091                     this.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2092                     let span = if_span.to(cond.span);
2093                     this.sess.gated_spans.gate(sym::if_let_guard, span);
2094                 }
2095                 Some(cond)
2096             } else {
2097                 None
2098             };
2099             let arrow_span = this.token.span;
2100             this.expect(&token::FatArrow)?;
2101             let arm_start_span = this.token.span;
2102
2103             let expr = this.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| {
2104                 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2105                 err
2106             })?;
2107
2108             let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
2109                 && this.token != token::CloseDelim(token::Brace);
2110
2111             let hi = this.prev_token.span;
2112
2113             if require_comma {
2114                 let sm = this.sess.source_map();
2115                 if let Some(body) = this.parse_arm_body_missing_braces(&expr, arrow_span) {
2116                     let span = body.span;
2117                     return Ok((
2118                         ast::Arm {
2119                             attrs,
2120                             pat,
2121                             guard,
2122                             body,
2123                             span,
2124                             id: DUMMY_NODE_ID,
2125                             is_placeholder: false,
2126                         },
2127                         TrailingToken::None,
2128                     ));
2129                 }
2130                 this.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]).map_err(
2131                     |mut err| {
2132                         match (sm.span_to_lines(expr.span), sm.span_to_lines(arm_start_span)) {
2133                             (Ok(ref expr_lines), Ok(ref arm_start_lines))
2134                                 if arm_start_lines.lines[0].end_col
2135                                     == expr_lines.lines[0].end_col
2136                                     && expr_lines.lines.len() == 2
2137                                     && this.token == token::FatArrow =>
2138                             {
2139                                 // We check whether there's any trailing code in the parse span,
2140                                 // if there isn't, we very likely have the following:
2141                                 //
2142                                 // X |     &Y => "y"
2143                                 //   |        --    - missing comma
2144                                 //   |        |
2145                                 //   |        arrow_span
2146                                 // X |     &X => "x"
2147                                 //   |      - ^^ self.token.span
2148                                 //   |      |
2149                                 //   |      parsed until here as `"y" & X`
2150                                 err.span_suggestion_short(
2151                                     arm_start_span.shrink_to_hi(),
2152                                     "missing a comma here to end this `match` arm",
2153                                     ",".to_owned(),
2154                                     Applicability::MachineApplicable,
2155                                 );
2156                             }
2157                             _ => {
2158                                 err.span_label(
2159                                     arrow_span,
2160                                     "while parsing the `match` arm starting here",
2161                                 );
2162                             }
2163                         }
2164                         err
2165                     },
2166                 )?;
2167             } else {
2168                 this.eat(&token::Comma);
2169             }
2170
2171             Ok((
2172                 ast::Arm {
2173                     attrs,
2174                     pat,
2175                     guard,
2176                     body: expr,
2177                     span: lo.to(hi),
2178                     id: DUMMY_NODE_ID,
2179                     is_placeholder: false,
2180                 },
2181                 TrailingToken::None,
2182             ))
2183         })
2184     }
2185
2186     /// Parses a `try {...}` expression (`try` token already eaten).
2187     fn parse_try_block(&mut self, span_lo: Span, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2188         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2189         attrs.extend(iattrs);
2190         if self.eat_keyword(kw::Catch) {
2191             let mut error = self.struct_span_err(
2192                 self.prev_token.span,
2193                 "keyword `catch` cannot follow a `try` block",
2194             );
2195             error.help("try using `match` on the result of the `try` block instead");
2196             error.emit();
2197             Err(error)
2198         } else {
2199             let span = span_lo.to(body.span);
2200             self.sess.gated_spans.gate(sym::try_blocks, span);
2201             Ok(self.mk_expr(span, ExprKind::TryBlock(body), attrs))
2202         }
2203     }
2204
2205     fn is_do_catch_block(&self) -> bool {
2206         self.token.is_keyword(kw::Do)
2207             && self.is_keyword_ahead(1, &[kw::Catch])
2208             && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2209             && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
2210     }
2211
2212     fn is_try_block(&self) -> bool {
2213         self.token.is_keyword(kw::Try)
2214             && self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2215             && self.token.uninterpolated_span().rust_2018()
2216     }
2217
2218     /// Parses an `async move? {...}` expression.
2219     fn parse_async_block(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2220         let lo = self.token.span;
2221         self.expect_keyword(kw::Async)?;
2222         let capture_clause = self.parse_capture_clause()?;
2223         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2224         attrs.extend(iattrs);
2225         let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);
2226         Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
2227     }
2228
2229     fn is_async_block(&self) -> bool {
2230         self.token.is_keyword(kw::Async)
2231             && ((
2232                 // `async move {`
2233                 self.is_keyword_ahead(1, &[kw::Move])
2234                     && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2235             ) || (
2236                 // `async {`
2237                 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2238             ))
2239     }
2240
2241     fn is_certainly_not_a_block(&self) -> bool {
2242         self.look_ahead(1, |t| t.is_ident())
2243             && (
2244                 // `{ ident, ` cannot start a block.
2245                 self.look_ahead(2, |t| t == &token::Comma)
2246                     || self.look_ahead(2, |t| t == &token::Colon)
2247                         && (
2248                             // `{ ident: token, ` cannot start a block.
2249                             self.look_ahead(4, |t| t == &token::Comma) ||
2250                 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
2251                 self.look_ahead(3, |t| !t.can_begin_type())
2252                         )
2253             )
2254     }
2255
2256     fn maybe_parse_struct_expr(
2257         &mut self,
2258         qself: Option<&ast::QSelf>,
2259         path: &ast::Path,
2260         attrs: &AttrVec,
2261     ) -> Option<PResult<'a, P<Expr>>> {
2262         let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2263         if struct_allowed || self.is_certainly_not_a_block() {
2264             if let Err(err) = self.expect(&token::OpenDelim(token::Brace)) {
2265                 return Some(Err(err));
2266             }
2267             let expr = self.parse_struct_expr(qself.cloned(), path.clone(), attrs.clone(), true);
2268             if let (Ok(expr), false) = (&expr, struct_allowed) {
2269                 // This is a struct literal, but we don't can't accept them here.
2270                 self.error_struct_lit_not_allowed_here(path.span, expr.span);
2271             }
2272             return Some(expr);
2273         }
2274         None
2275     }
2276
2277     fn error_struct_lit_not_allowed_here(&self, lo: Span, sp: Span) {
2278         self.struct_span_err(sp, "struct literals are not allowed here")
2279             .multipart_suggestion(
2280                 "surround the struct literal with parentheses",
2281                 vec![(lo.shrink_to_lo(), "(".to_string()), (sp.shrink_to_hi(), ")".to_string())],
2282                 Applicability::MachineApplicable,
2283             )
2284             .emit();
2285     }
2286
2287     /// Precondition: already parsed the '{'.
2288     pub(super) fn parse_struct_expr(
2289         &mut self,
2290         qself: Option<ast::QSelf>,
2291         pth: ast::Path,
2292         attrs: AttrVec,
2293         recover: bool,
2294     ) -> PResult<'a, P<Expr>> {
2295         let mut fields = Vec::new();
2296         let mut base = ast::StructRest::None;
2297         let mut recover_async = false;
2298
2299         let mut async_block_err = |e: &mut DiagnosticBuilder<'_>, span: Span| {
2300             recover_async = true;
2301             e.span_label(span, "`async` blocks are only allowed in Rust 2018 or later");
2302             e.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
2303             e.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
2304         };
2305
2306         while self.token != token::CloseDelim(token::Brace) {
2307             if self.eat(&token::DotDot) {
2308                 let exp_span = self.prev_token.span;
2309                 // We permit `.. }` on the left-hand side of a destructuring assignment.
2310                 if self.check(&token::CloseDelim(token::Brace)) {
2311                     self.sess.gated_spans.gate(sym::destructuring_assignment, self.prev_token.span);
2312                     base = ast::StructRest::Rest(self.prev_token.span.shrink_to_hi());
2313                     break;
2314                 }
2315                 match self.parse_expr() {
2316                     Ok(e) => base = ast::StructRest::Base(e),
2317                     Err(mut e) if recover => {
2318                         e.emit();
2319                         self.recover_stmt();
2320                     }
2321                     Err(e) => return Err(e),
2322                 }
2323                 self.recover_struct_comma_after_dotdot(exp_span);
2324                 break;
2325             }
2326
2327             let recovery_field = self.find_struct_error_after_field_looking_code();
2328             let parsed_field = match self.parse_expr_field() {
2329                 Ok(f) => Some(f),
2330                 Err(mut e) => {
2331                     if pth == kw::Async {
2332                         async_block_err(&mut e, pth.span);
2333                     } else {
2334                         e.span_label(pth.span, "while parsing this struct");
2335                     }
2336                     e.emit();
2337
2338                     // If the next token is a comma, then try to parse
2339                     // what comes next as additional fields, rather than
2340                     // bailing out until next `}`.
2341                     if self.token != token::Comma {
2342                         self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2343                         if self.token != token::Comma {
2344                             break;
2345                         }
2346                     }
2347                     None
2348                 }
2349             };
2350
2351             match self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]) {
2352                 Ok(_) => {
2353                     if let Some(f) = parsed_field.or(recovery_field) {
2354                         // Only include the field if there's no parse error for the field name.
2355                         fields.push(f);
2356                     }
2357                 }
2358                 Err(mut e) => {
2359                     if pth == kw::Async {
2360                         async_block_err(&mut e, pth.span);
2361                     } else {
2362                         e.span_label(pth.span, "while parsing this struct");
2363                         if let Some(f) = recovery_field {
2364                             fields.push(f);
2365                             e.span_suggestion(
2366                                 self.prev_token.span.shrink_to_hi(),
2367                                 "try adding a comma",
2368                                 ",".into(),
2369                                 Applicability::MachineApplicable,
2370                             );
2371                         }
2372                     }
2373                     if !recover {
2374                         return Err(e);
2375                     }
2376                     e.emit();
2377                     self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2378                     self.eat(&token::Comma);
2379                 }
2380             }
2381         }
2382
2383         let span = pth.span.to(self.token.span);
2384         self.expect(&token::CloseDelim(token::Brace))?;
2385         let expr = if recover_async {
2386             ExprKind::Err
2387         } else {
2388             ExprKind::Struct(P(ast::StructExpr { qself, path: pth, fields, rest: base }))
2389         };
2390         Ok(self.mk_expr(span, expr, attrs))
2391     }
2392
2393     /// Use in case of error after field-looking code: `S { foo: () with a }`.
2394     fn find_struct_error_after_field_looking_code(&self) -> Option<ExprField> {
2395         match self.token.ident() {
2396             Some((ident, is_raw))
2397                 if (is_raw || !ident.is_reserved())
2398                     && self.look_ahead(1, |t| *t == token::Colon) =>
2399             {
2400                 Some(ast::ExprField {
2401                     ident,
2402                     span: self.token.span,
2403                     expr: self.mk_expr_err(self.token.span),
2404                     is_shorthand: false,
2405                     attrs: AttrVec::new(),
2406                     id: DUMMY_NODE_ID,
2407                     is_placeholder: false,
2408                 })
2409             }
2410             _ => None,
2411         }
2412     }
2413
2414     fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
2415         if self.token != token::Comma {
2416             return;
2417         }
2418         self.struct_span_err(
2419             span.to(self.prev_token.span),
2420             "cannot use a comma after the base struct",
2421         )
2422         .span_suggestion_short(
2423             self.token.span,
2424             "remove this comma",
2425             String::new(),
2426             Applicability::MachineApplicable,
2427         )
2428         .note("the base struct must always be the last field")
2429         .emit();
2430         self.recover_stmt();
2431     }
2432
2433     /// Parses `ident (COLON expr)?`.
2434     fn parse_expr_field(&mut self) -> PResult<'a, ExprField> {
2435         let attrs = self.parse_outer_attributes()?;
2436         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2437             let lo = this.token.span;
2438
2439             // Check if a colon exists one ahead. This means we're parsing a fieldname.
2440             let is_shorthand = !this.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
2441             let (ident, expr) = if is_shorthand {
2442                 // Mimic `x: x` for the `x` field shorthand.
2443                 let ident = this.parse_ident_common(false)?;
2444                 let path = ast::Path::from_ident(ident);
2445                 (ident, this.mk_expr(ident.span, ExprKind::Path(None, path), AttrVec::new()))
2446             } else {
2447                 let ident = this.parse_field_name()?;
2448                 this.error_on_eq_field_init(ident);
2449                 this.bump(); // `:`
2450                 (ident, this.parse_expr()?)
2451             };
2452
2453             Ok((
2454                 ast::ExprField {
2455                     ident,
2456                     span: lo.to(expr.span),
2457                     expr,
2458                     is_shorthand,
2459                     attrs: attrs.into(),
2460                     id: DUMMY_NODE_ID,
2461                     is_placeholder: false,
2462                 },
2463                 TrailingToken::MaybeComma,
2464             ))
2465         })
2466     }
2467
2468     /// Check for `=`. This means the source incorrectly attempts to
2469     /// initialize a field with an eq rather than a colon.
2470     fn error_on_eq_field_init(&self, field_name: Ident) {
2471         if self.token != token::Eq {
2472             return;
2473         }
2474
2475         self.struct_span_err(self.token.span, "expected `:`, found `=`")
2476             .span_suggestion(
2477                 field_name.span.shrink_to_hi().to(self.token.span),
2478                 "replace equals symbol with a colon",
2479                 ":".to_string(),
2480                 Applicability::MachineApplicable,
2481             )
2482             .emit();
2483     }
2484
2485     fn err_dotdotdot_syntax(&self, span: Span) {
2486         self.struct_span_err(span, "unexpected token: `...`")
2487             .span_suggestion(
2488                 span,
2489                 "use `..` for an exclusive range",
2490                 "..".to_owned(),
2491                 Applicability::MaybeIncorrect,
2492             )
2493             .span_suggestion(
2494                 span,
2495                 "or `..=` for an inclusive range",
2496                 "..=".to_owned(),
2497                 Applicability::MaybeIncorrect,
2498             )
2499             .emit();
2500     }
2501
2502     fn err_larrow_operator(&self, span: Span) {
2503         self.struct_span_err(span, "unexpected token: `<-`")
2504             .span_suggestion(
2505                 span,
2506                 "if you meant to write a comparison against a negative value, add a \
2507              space in between `<` and `-`",
2508                 "< -".to_string(),
2509                 Applicability::MaybeIncorrect,
2510             )
2511             .emit();
2512     }
2513
2514     fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2515         ExprKind::AssignOp(binop, lhs, rhs)
2516     }
2517
2518     fn mk_range(
2519         &self,
2520         start: Option<P<Expr>>,
2521         end: Option<P<Expr>>,
2522         limits: RangeLimits,
2523     ) -> ExprKind {
2524         if end.is_none() && limits == RangeLimits::Closed {
2525             self.error_inclusive_range_with_no_end(self.prev_token.span);
2526             ExprKind::Err
2527         } else {
2528             ExprKind::Range(start, end, limits)
2529         }
2530     }
2531
2532     fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
2533         ExprKind::Unary(unop, expr)
2534     }
2535
2536     fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2537         ExprKind::Binary(binop, lhs, rhs)
2538     }
2539
2540     fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
2541         ExprKind::Index(expr, idx)
2542     }
2543
2544     fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
2545         ExprKind::Call(f, args)
2546     }
2547
2548     fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> P<Expr> {
2549         let span = lo.to(self.prev_token.span);
2550         let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), AttrVec::new());
2551         self.recover_from_await_method_call();
2552         await_expr
2553     }
2554
2555     crate fn mk_expr(&self, span: Span, kind: ExprKind, attrs: AttrVec) -> P<Expr> {
2556         P(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None })
2557     }
2558
2559     pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
2560         self.mk_expr(span, ExprKind::Err, AttrVec::new())
2561     }
2562
2563     /// Create expression span ensuring the span of the parent node
2564     /// is larger than the span of lhs and rhs, including the attributes.
2565     fn mk_expr_sp(&self, lhs: &P<Expr>, lhs_span: Span, rhs_span: Span) -> Span {
2566         lhs.attrs
2567             .iter()
2568             .find(|a| a.style == AttrStyle::Outer)
2569             .map_or(lhs_span, |a| a.span)
2570             .to(rhs_span)
2571     }
2572
2573     fn collect_tokens_for_expr(
2574         &mut self,
2575         attrs: AttrWrapper,
2576         f: impl FnOnce(&mut Self, Vec<ast::Attribute>) -> PResult<'a, P<Expr>>,
2577     ) -> PResult<'a, P<Expr>> {
2578         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2579             let res = f(this, attrs)?;
2580             let trailing = if this.restrictions.contains(Restrictions::STMT_EXPR)
2581                 && this.token.kind == token::Semi
2582             {
2583                 TrailingToken::Semi
2584             } else {
2585                 // FIXME - pass this through from the place where we know
2586                 // we need a comma, rather than assuming that `#[attr] expr,`
2587                 // always captures a trailing comma
2588                 TrailingToken::MaybeComma
2589             };
2590             Ok((res, trailing))
2591         })
2592     }
2593 }