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