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