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