]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/expr.rs
Make "use latest edition" subdiagnostic translatable
[rust.git] / compiler / rustc_parse / src / parser / expr.rs
1 use super::diagnostics::SnapshotParser;
2 use super::pat::{CommaRecoveryMode, Expected, RecoverColon, RecoverComma};
3 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
4 use super::{
5     AttrWrapper, BlockMode, ClosureSpans, ForceCollect, Parser, PathStyle, Restrictions,
6     SemiColonMode, SeqSep, TokenExpectType, TokenType, TrailingToken,
7 };
8 use crate::errors::{
9     ArrayBracketsInsteadOfSpaces, ArrayBracketsInsteadOfSpacesSugg, AsyncBlockIn2015,
10     AsyncMoveOrderIncorrect, BracesForStructLiteral, CatchAfterTry, CommaAfterBaseStruct,
11     ComparisonInterpretedAsGeneric, ComparisonOrShiftInterpretedAsGenericSugg,
12     DoCatchSyntaxRemoved, DotDotDot, EqFieldInit, ExpectedElseBlock, ExpectedEqForLetExpr,
13     ExpectedExpressionFoundLet, FieldExpressionWithGeneric, FloatLiteralRequiresIntegerPart,
14     FoundExprWouldBeStmt, HelpUseLatestEdition, IfExpressionLetSomeSub,
15     IfExpressionMissingCondition, IfExpressionMissingThenBlock, IfExpressionMissingThenBlockSub,
16     InvalidBlockMacroSegment, InvalidComparisonOperator, InvalidComparisonOperatorSub,
17     InvalidInterpolatedExpression, InvalidLiteralSuffixOnTupleIndex, InvalidLogicalOperator,
18     InvalidLogicalOperatorSub, LabeledLoopInBreak, LeadingPlusNotSupported, LeftArrowOperator,
19     LifetimeInBorrowExpression, MacroInvocationWithQualifiedPath, MalformedLoopLabel,
20     MatchArmBodyWithoutBraces, MatchArmBodyWithoutBracesSugg, MissingCommaAfterMatchArm,
21     MissingDotDot, MissingInInForLoop, MissingInInForLoopSub, MissingSemicolonBeforeArray,
22     NoFieldsForFnCall, NotAsNegationOperator, NotAsNegationOperatorSub,
23     OuterAttributeNotAllowedOnIfElse, ParenthesesWithStructFields,
24     RequireColonAfterLabeledExpression, ShiftInterpretedAsGeneric, StructLiteralNotAllowedHere,
25     StructLiteralNotAllowedHereSugg, TildeAsUnaryOperator, UnexpectedIfWithIf,
26     UnexpectedTokenAfterLabel, UnexpectedTokenAfterLabelSugg, WrapExpressionInParentheses,
27 };
28 use crate::maybe_recover_from_interpolated_ty_qpath;
29 use core::mem;
30 use rustc_ast::ptr::P;
31 use rustc_ast::token::{self, Delimiter, Token, TokenKind};
32 use rustc_ast::tokenstream::Spacing;
33 use rustc_ast::util::case::Case;
34 use rustc_ast::util::classify;
35 use rustc_ast::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity};
36 use rustc_ast::visit::Visitor;
37 use rustc_ast::{self as ast, AttrStyle, AttrVec, CaptureBy, ExprField, UnOp, DUMMY_NODE_ID};
38 use rustc_ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty, TyKind};
39 use rustc_ast::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits};
40 use rustc_ast::{ClosureBinder, MetaItemLit, StmtKind};
41 use rustc_ast_pretty::pprust;
42 use rustc_errors::{
43     AddToDiagnostic, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, IntoDiagnostic,
44     PResult, StashKey,
45 };
46 use rustc_session::errors::{report_lit_error, ExprParenthesesNeeded};
47 use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP;
48 use rustc_session::lint::BuiltinLintDiagnostics;
49 use rustc_span::source_map::{self, Span, Spanned};
50 use rustc_span::symbol::{kw, sym, Ident, Symbol};
51 use rustc_span::{BytePos, Pos};
52
53 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
54 /// dropped into the token stream, which happens while parsing the result of
55 /// macro expansion). Placement of these is not as complex as I feared it would
56 /// be. The important thing is to make sure that lookahead doesn't balk at
57 /// `token::Interpolated` tokens.
58 macro_rules! maybe_whole_expr {
59     ($p:expr) => {
60         if let token::Interpolated(nt) = &$p.token.kind {
61             match &**nt {
62                 token::NtExpr(e) | token::NtLiteral(e) => {
63                     let e = e.clone();
64                     $p.bump();
65                     return Ok(e);
66                 }
67                 token::NtPath(path) => {
68                     let path = (**path).clone();
69                     $p.bump();
70                     return Ok($p.mk_expr($p.prev_token.span, ExprKind::Path(None, path)));
71                 }
72                 token::NtBlock(block) => {
73                     let block = block.clone();
74                     $p.bump();
75                     return Ok($p.mk_expr($p.prev_token.span, ExprKind::Block(block, None)));
76                 }
77                 _ => {}
78             };
79         }
80     };
81 }
82
83 #[derive(Debug)]
84 pub(super) enum LhsExpr {
85     NotYetParsed,
86     AttributesParsed(AttrWrapper),
87     AlreadyParsed { expr: P<Expr>, starts_statement: bool },
88 }
89
90 impl From<Option<AttrWrapper>> for LhsExpr {
91     /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
92     /// and `None` into `LhsExpr::NotYetParsed`.
93     ///
94     /// This conversion does not allocate.
95     fn from(o: Option<AttrWrapper>) -> Self {
96         if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed }
97     }
98 }
99
100 impl From<P<Expr>> for LhsExpr {
101     /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed { expr, starts_statement: false }`.
102     ///
103     /// This conversion does not allocate.
104     fn from(expr: P<Expr>) -> Self {
105         LhsExpr::AlreadyParsed { expr, starts_statement: false }
106     }
107 }
108
109 impl<'a> Parser<'a> {
110     /// Parses an expression.
111     #[inline]
112     pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
113         self.current_closure.take();
114
115         self.parse_expr_res(Restrictions::empty(), None)
116     }
117
118     /// Parses an expression, forcing tokens to be collected
119     pub fn parse_expr_force_collect(&mut self) -> PResult<'a, P<Expr>> {
120         self.collect_tokens_no_attrs(|this| this.parse_expr())
121     }
122
123     pub fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> {
124         self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
125     }
126
127     fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P<Expr>> {
128         match self.parse_expr() {
129             Ok(expr) => Ok(expr),
130             Err(mut err) => match self.token.ident() {
131                 Some((Ident { name: kw::Underscore, .. }, false))
132                     if self.may_recover() && self.look_ahead(1, |t| t == &token::Comma) =>
133                 {
134                     // Special-case handling of `foo(_, _, _)`
135                     err.emit();
136                     self.bump();
137                     Ok(self.mk_expr(self.prev_token.span, ExprKind::Err))
138                 }
139                 _ => Err(err),
140             },
141         }
142     }
143
144     /// Parses a sequence of expressions delimited by parentheses.
145     fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
146         self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r)
147     }
148
149     /// Parses an expression, subject to the given restrictions.
150     #[inline]
151     pub(super) fn parse_expr_res(
152         &mut self,
153         r: Restrictions,
154         already_parsed_attrs: Option<AttrWrapper>,
155     ) -> PResult<'a, P<Expr>> {
156         self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
157     }
158
159     /// Parses an associative expression.
160     ///
161     /// This parses an expression accounting for associativity and precedence of the operators in
162     /// the expression.
163     #[inline]
164     fn parse_assoc_expr(
165         &mut self,
166         already_parsed_attrs: Option<AttrWrapper>,
167     ) -> PResult<'a, P<Expr>> {
168         self.parse_assoc_expr_with(0, already_parsed_attrs.into())
169     }
170
171     /// Parses an associative expression with operators of at least `min_prec` precedence.
172     pub(super) fn parse_assoc_expr_with(
173         &mut self,
174         min_prec: usize,
175         lhs: LhsExpr,
176     ) -> PResult<'a, P<Expr>> {
177         let mut starts_stmt = false;
178         let mut lhs = if let LhsExpr::AlreadyParsed { expr, starts_statement } = lhs {
179             starts_stmt = starts_statement;
180             expr
181         } else {
182             let attrs = match lhs {
183                 LhsExpr::AttributesParsed(attrs) => Some(attrs),
184                 _ => None,
185             };
186             if self.token.is_range_separator() {
187                 return self.parse_prefix_range_expr(attrs);
188             } else {
189                 self.parse_prefix_expr(attrs)?
190             }
191         };
192         let last_type_ascription_set = self.last_type_ascription.is_some();
193
194         if !self.should_continue_as_assoc_expr(&lhs) {
195             self.last_type_ascription = None;
196             return Ok(lhs);
197         }
198
199         self.expected_tokens.push(TokenType::Operator);
200         while let Some(op) = self.check_assoc_op() {
201             // Adjust the span for interpolated LHS to point to the `$lhs` token
202             // and not to what it refers to.
203             let lhs_span = match self.prev_token.kind {
204                 TokenKind::Interpolated(..) => self.prev_token.span,
205                 _ => lhs.span,
206             };
207
208             let cur_op_span = self.token.span;
209             let restrictions = if op.node.is_assign_like() {
210                 self.restrictions & Restrictions::NO_STRUCT_LITERAL
211             } else {
212                 self.restrictions
213             };
214             let prec = op.node.precedence();
215             if prec < min_prec {
216                 break;
217             }
218             // Check for deprecated `...` syntax
219             if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq {
220                 self.err_dotdotdot_syntax(self.token.span);
221             }
222
223             if self.token == token::LArrow {
224                 self.err_larrow_operator(self.token.span);
225             }
226
227             self.bump();
228             if op.node.is_comparison() {
229                 if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
230                     return Ok(expr);
231                 }
232             }
233
234             // Look for JS' `===` and `!==` and recover
235             if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual)
236                 && self.token.kind == token::Eq
237                 && self.prev_token.span.hi() == self.token.span.lo()
238             {
239                 let sp = op.span.to(self.token.span);
240                 let sugg = match op.node {
241                     AssocOp::Equal => "==",
242                     AssocOp::NotEqual => "!=",
243                     _ => unreachable!(),
244                 }
245                 .into();
246                 let invalid = format!("{}=", &sugg);
247                 self.sess.emit_err(InvalidComparisonOperator {
248                     span: sp,
249                     invalid: invalid.clone(),
250                     sub: InvalidComparisonOperatorSub::Correctable {
251                         span: sp,
252                         invalid,
253                         correct: sugg,
254                     },
255                 });
256                 self.bump();
257             }
258
259             // Look for PHP's `<>` and recover
260             if op.node == AssocOp::Less
261                 && self.token.kind == token::Gt
262                 && self.prev_token.span.hi() == self.token.span.lo()
263             {
264                 let sp = op.span.to(self.token.span);
265                 self.sess.emit_err(InvalidComparisonOperator {
266                     span: sp,
267                     invalid: "<>".into(),
268                     sub: InvalidComparisonOperatorSub::Correctable {
269                         span: sp,
270                         invalid: "<>".into(),
271                         correct: "!=".into(),
272                     },
273                 });
274                 self.bump();
275             }
276
277             // Look for C++'s `<=>` and recover
278             if op.node == AssocOp::LessEqual
279                 && self.token.kind == token::Gt
280                 && self.prev_token.span.hi() == self.token.span.lo()
281             {
282                 let sp = op.span.to(self.token.span);
283                 self.sess.emit_err(InvalidComparisonOperator {
284                     span: sp,
285                     invalid: "<=>".into(),
286                     sub: InvalidComparisonOperatorSub::Spaceship(sp),
287                 });
288                 self.bump();
289             }
290
291             if self.prev_token == token::BinOp(token::Plus)
292                 && self.token == token::BinOp(token::Plus)
293                 && self.prev_token.span.between(self.token.span).is_empty()
294             {
295                 let op_span = self.prev_token.span.to(self.token.span);
296                 // Eat the second `+`
297                 self.bump();
298                 lhs = self.recover_from_postfix_increment(lhs, op_span, starts_stmt)?;
299                 continue;
300             }
301
302             let op = op.node;
303             // Special cases:
304             if op == AssocOp::As {
305                 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
306                 continue;
307             } else if op == AssocOp::Colon {
308                 lhs = self.parse_assoc_op_ascribe(lhs, lhs_span)?;
309                 continue;
310             } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
311                 // If we didn't have to handle `x..`/`x..=`, it would be pretty easy to
312                 // generalise it to the Fixity::None code.
313                 lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?;
314                 break;
315             }
316
317             let fixity = op.fixity();
318             let prec_adjustment = match fixity {
319                 Fixity::Right => 0,
320                 Fixity::Left => 1,
321                 // We currently have no non-associative operators that are not handled above by
322                 // the special cases. The code is here only for future convenience.
323                 Fixity::None => 1,
324             };
325             let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
326                 this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
327             })?;
328
329             let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span);
330             lhs = match op {
331                 AssocOp::Add
332                 | AssocOp::Subtract
333                 | AssocOp::Multiply
334                 | AssocOp::Divide
335                 | AssocOp::Modulus
336                 | AssocOp::LAnd
337                 | AssocOp::LOr
338                 | AssocOp::BitXor
339                 | AssocOp::BitAnd
340                 | AssocOp::BitOr
341                 | AssocOp::ShiftLeft
342                 | AssocOp::ShiftRight
343                 | AssocOp::Equal
344                 | AssocOp::Less
345                 | AssocOp::LessEqual
346                 | AssocOp::NotEqual
347                 | AssocOp::Greater
348                 | AssocOp::GreaterEqual => {
349                     let ast_op = op.to_ast_binop().unwrap();
350                     let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
351                     self.mk_expr(span, binary)
352                 }
353                 AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span)),
354                 AssocOp::AssignOp(k) => {
355                     let aop = match k {
356                         token::Plus => BinOpKind::Add,
357                         token::Minus => BinOpKind::Sub,
358                         token::Star => BinOpKind::Mul,
359                         token::Slash => BinOpKind::Div,
360                         token::Percent => BinOpKind::Rem,
361                         token::Caret => BinOpKind::BitXor,
362                         token::And => BinOpKind::BitAnd,
363                         token::Or => BinOpKind::BitOr,
364                         token::Shl => BinOpKind::Shl,
365                         token::Shr => BinOpKind::Shr,
366                     };
367                     let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
368                     self.mk_expr(span, aopexpr)
369                 }
370                 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
371                     self.span_bug(span, "AssocOp should have been handled by special case")
372                 }
373             };
374
375             if let Fixity::None = fixity {
376                 break;
377             }
378         }
379         if last_type_ascription_set {
380             self.last_type_ascription = None;
381         }
382         Ok(lhs)
383     }
384
385     fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
386         match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) {
387             // Semi-statement forms are odd:
388             // See https://github.com/rust-lang/rust/issues/29071
389             (true, None) => false,
390             (false, _) => true, // Continue parsing the expression.
391             // An exhaustive check is done in the following block, but these are checked first
392             // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
393             // want to keep their span info to improve diagnostics in these cases in a later stage.
394             (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
395             (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
396             (true, Some(AssocOp::Add)) | // `{ 42 } + 42` (unary plus)
397             (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
398             (true, Some(AssocOp::LOr)) | // `{ 42 } || 42` ("logical or" or closure)
399             (true, Some(AssocOp::BitOr)) // `{ 42 } | 42` or `{ 42 } |x| 42`
400             => {
401                 // These cases are ambiguous and can't be identified in the parser alone.
402                 //
403                 // Bitwise AND is left out because guessing intent is hard. We can make
404                 // suggestions based on the assumption that double-refs are rarely intentional,
405                 // and closures are distinct enough that they don't get mixed up with their
406                 // return value.
407                 let sp = self.sess.source_map().start_point(self.token.span);
408                 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
409                 false
410             }
411             (true, Some(op)) if !op.can_continue_expr_unambiguously() => false,
412             (true, Some(_)) => {
413                 self.error_found_expr_would_be_stmt(lhs);
414                 true
415             }
416         }
417     }
418
419     /// We've found an expression that would be parsed as a statement,
420     /// but the next token implies this should be parsed as an expression.
421     /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
422     fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
423         self.sess.emit_err(FoundExprWouldBeStmt {
424             span: self.token.span,
425             token: self.token.clone(),
426             suggestion: ExprParenthesesNeeded::surrounding(lhs.span),
427         });
428     }
429
430     /// Possibly translate the current token to an associative operator.
431     /// The method does not advance the current token.
432     ///
433     /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
434     fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
435         let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
436             // When parsing const expressions, stop parsing when encountering `>`.
437             (
438                 Some(
439                     AssocOp::ShiftRight
440                     | AssocOp::Greater
441                     | AssocOp::GreaterEqual
442                     | AssocOp::AssignOp(token::BinOpToken::Shr),
443                 ),
444                 _,
445             ) if self.restrictions.contains(Restrictions::CONST_EXPR) => {
446                 return None;
447             }
448             (Some(op), _) => (op, self.token.span),
449             (None, Some((Ident { name: sym::and, span }, false))) if self.may_recover() => {
450                 self.sess.emit_err(InvalidLogicalOperator {
451                     span: self.token.span,
452                     incorrect: "and".into(),
453                     sub: InvalidLogicalOperatorSub::Conjunction(self.token.span),
454                 });
455                 (AssocOp::LAnd, span)
456             }
457             (None, Some((Ident { name: sym::or, span }, false))) if self.may_recover() => {
458                 self.sess.emit_err(InvalidLogicalOperator {
459                     span: self.token.span,
460                     incorrect: "or".into(),
461                     sub: InvalidLogicalOperatorSub::Disjunction(self.token.span),
462                 });
463                 (AssocOp::LOr, span)
464             }
465             _ => return None,
466         };
467         Some(source_map::respan(span, op))
468     }
469
470     /// Checks if this expression is a successfully parsed statement.
471     fn expr_is_complete(&self, e: &Expr) -> bool {
472         self.restrictions.contains(Restrictions::STMT_EXPR)
473             && !classify::expr_requires_semi_to_be_stmt(e)
474     }
475
476     /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
477     /// The other two variants are handled in `parse_prefix_range_expr` below.
478     fn parse_range_expr(
479         &mut self,
480         prec: usize,
481         lhs: P<Expr>,
482         op: AssocOp,
483         cur_op_span: Span,
484     ) -> PResult<'a, P<Expr>> {
485         let rhs = if self.is_at_start_of_range_notation_rhs() {
486             Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
487         } else {
488             None
489         };
490         let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
491         let span = self.mk_expr_sp(&lhs, lhs.span, rhs_span);
492         let limits =
493             if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed };
494         let range = self.mk_range(Some(lhs), rhs, limits);
495         Ok(self.mk_expr(span, range))
496     }
497
498     fn is_at_start_of_range_notation_rhs(&self) -> bool {
499         if self.token.can_begin_expr() {
500             // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
501             if self.token == token::OpenDelim(Delimiter::Brace) {
502                 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
503             }
504             true
505         } else {
506             false
507         }
508     }
509
510     /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
511     fn parse_prefix_range_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
512         // Check for deprecated `...` syntax.
513         if self.token == token::DotDotDot {
514             self.err_dotdotdot_syntax(self.token.span);
515         }
516
517         debug_assert!(
518             self.token.is_range_separator(),
519             "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
520             self.token
521         );
522
523         let limits = match self.token.kind {
524             token::DotDot => RangeLimits::HalfOpen,
525             _ => RangeLimits::Closed,
526         };
527         let op = AssocOp::from_token(&self.token);
528         // FIXME: `parse_prefix_range_expr` is called when the current
529         // token is `DotDot`, `DotDotDot`, or `DotDotEq`. If we haven't already
530         // parsed attributes, then trying to parse them here will always fail.
531         // We should figure out how we want attributes on range expressions to work.
532         let attrs = self.parse_or_use_outer_attributes(attrs)?;
533         self.collect_tokens_for_expr(attrs, |this, attrs| {
534             let lo = this.token.span;
535             this.bump();
536             let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() {
537                 // RHS must be parsed with more associativity than the dots.
538                 this.parse_assoc_expr_with(op.unwrap().precedence() + 1, LhsExpr::NotYetParsed)
539                     .map(|x| (lo.to(x.span), Some(x)))?
540             } else {
541                 (lo, None)
542             };
543             let range = this.mk_range(None, opt_end, limits);
544             Ok(this.mk_expr_with_attrs(span, range, attrs))
545         })
546     }
547
548     /// Parses a prefix-unary-operator expr.
549     fn parse_prefix_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
550         let attrs = self.parse_or_use_outer_attributes(attrs)?;
551         let lo = self.token.span;
552
553         macro_rules! make_it {
554             ($this:ident, $attrs:expr, |this, _| $body:expr) => {
555                 $this.collect_tokens_for_expr($attrs, |$this, attrs| {
556                     let (hi, ex) = $body?;
557                     Ok($this.mk_expr_with_attrs(lo.to(hi), ex, attrs))
558                 })
559             };
560         }
561
562         let this = self;
563
564         // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
565         match this.token.uninterpolate().kind {
566             // `!expr`
567             token::Not => make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Not)),
568             // `~expr`
569             token::Tilde => make_it!(this, attrs, |this, _| this.recover_tilde_expr(lo)),
570             // `-expr`
571             token::BinOp(token::Minus) => {
572                 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Neg))
573             }
574             // `*expr`
575             token::BinOp(token::Star) => {
576                 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Deref))
577             }
578             // `&expr` and `&&expr`
579             token::BinOp(token::And) | token::AndAnd => {
580                 make_it!(this, attrs, |this, _| this.parse_borrow_expr(lo))
581             }
582             // `+lit`
583             token::BinOp(token::Plus) if this.look_ahead(1, |tok| tok.is_numeric_lit()) => {
584                 let mut err =
585                     LeadingPlusNotSupported { span: lo, remove_plus: None, add_parentheses: None };
586
587                 // a block on the LHS might have been intended to be an expression instead
588                 if let Some(sp) = this.sess.ambiguous_block_expr_parse.borrow().get(&lo) {
589                     err.add_parentheses = Some(ExprParenthesesNeeded::surrounding(*sp));
590                 } else {
591                     err.remove_plus = Some(lo);
592                 }
593                 this.sess.emit_err(err);
594
595                 this.bump();
596                 this.parse_prefix_expr(None)
597             }
598             // Recover from `++x`:
599             token::BinOp(token::Plus)
600                 if this.look_ahead(1, |t| *t == token::BinOp(token::Plus)) =>
601             {
602                 let starts_stmt = this.prev_token == token::Semi
603                     || this.prev_token == token::CloseDelim(Delimiter::Brace);
604                 let pre_span = this.token.span.to(this.look_ahead(1, |t| t.span));
605                 // Eat both `+`s.
606                 this.bump();
607                 this.bump();
608
609                 let operand_expr = this.parse_dot_or_call_expr(Default::default())?;
610                 this.recover_from_prefix_increment(operand_expr, pre_span, starts_stmt)
611             }
612             token::Ident(..) if this.token.is_keyword(kw::Box) => {
613                 make_it!(this, attrs, |this, _| this.parse_box_expr(lo))
614             }
615             token::Ident(..) if this.may_recover() && this.is_mistaken_not_ident_negation() => {
616                 make_it!(this, attrs, |this, _| this.recover_not_expr(lo))
617             }
618             _ => return this.parse_dot_or_call_expr(Some(attrs)),
619         }
620     }
621
622     fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P<Expr>)> {
623         self.bump();
624         let expr = self.parse_prefix_expr(None);
625         let (span, expr) = self.interpolated_or_expr_span(expr)?;
626         Ok((lo.to(span), expr))
627     }
628
629     fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
630         let (span, expr) = self.parse_prefix_expr_common(lo)?;
631         Ok((span, self.mk_unary(op, expr)))
632     }
633
634     /// Recover on `~expr` in favor of `!expr`.
635     fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
636         self.sess.emit_err(TildeAsUnaryOperator(lo));
637
638         self.parse_unary_expr(lo, UnOp::Not)
639     }
640
641     /// Parse `box expr`.
642     fn parse_box_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
643         let (span, expr) = self.parse_prefix_expr_common(lo)?;
644         self.sess.gated_spans.gate(sym::box_syntax, span);
645         Ok((span, ExprKind::Box(expr)))
646     }
647
648     fn is_mistaken_not_ident_negation(&self) -> bool {
649         let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
650             // These tokens can start an expression after `!`, but
651             // can't continue an expression after an ident
652             token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
653             token::Literal(..) | token::Pound => true,
654             _ => t.is_whole_expr(),
655         };
656         self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
657     }
658
659     /// Recover on `not expr` in favor of `!expr`.
660     fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
661         let negated_token = self.look_ahead(1, |t| t.clone());
662
663         let sub_diag = if negated_token.is_numeric_lit() {
664             NotAsNegationOperatorSub::SuggestNotBitwise
665         } else if negated_token.is_bool_lit() {
666             NotAsNegationOperatorSub::SuggestNotLogical
667         } else {
668             NotAsNegationOperatorSub::SuggestNotDefault
669         };
670
671         self.sess.emit_err(NotAsNegationOperator {
672             negated: negated_token.span,
673             negated_desc: super::token_descr(&negated_token),
674             // Span the `not` plus trailing whitespace to avoid
675             // trailing whitespace after the `!` in our suggestion
676             sub: sub_diag(
677                 self.sess.source_map().span_until_non_whitespace(lo.to(negated_token.span)),
678             ),
679         });
680
681         self.parse_unary_expr(lo, UnOp::Not)
682     }
683
684     /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
685     fn interpolated_or_expr_span(
686         &self,
687         expr: PResult<'a, P<Expr>>,
688     ) -> PResult<'a, (Span, P<Expr>)> {
689         expr.map(|e| {
690             (
691                 match self.prev_token.kind {
692                     TokenKind::Interpolated(..) => self.prev_token.span,
693                     _ => e.span,
694                 },
695                 e,
696             )
697         })
698     }
699
700     fn parse_assoc_op_cast(
701         &mut self,
702         lhs: P<Expr>,
703         lhs_span: Span,
704         expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind,
705     ) -> PResult<'a, P<Expr>> {
706         let mk_expr = |this: &mut Self, lhs: P<Expr>, rhs: P<Ty>| {
707             this.mk_expr(this.mk_expr_sp(&lhs, lhs_span, rhs.span), expr_kind(lhs, rhs))
708         };
709
710         // Save the state of the parser before parsing type normally, in case there is a
711         // LessThan comparison after this cast.
712         let parser_snapshot_before_type = self.clone();
713         let cast_expr = match self.parse_as_cast_ty() {
714             Ok(rhs) => mk_expr(self, lhs, rhs),
715             Err(type_err) => {
716                 if !self.may_recover() {
717                     return Err(type_err);
718                 }
719
720                 // Rewind to before attempting to parse the type with generics, to recover
721                 // from situations like `x as usize < y` in which we first tried to parse
722                 // `usize < y` as a type with generic arguments.
723                 let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
724
725                 // Check for typo of `'a: loop { break 'a }` with a missing `'`.
726                 match (&lhs.kind, &self.token.kind) {
727                     (
728                         // `foo: `
729                         ExprKind::Path(None, ast::Path { segments, .. }),
730                         TokenKind::Ident(kw::For | kw::Loop | kw::While, false),
731                     ) if segments.len() == 1 => {
732                         let snapshot = self.create_snapshot_for_diagnostic();
733                         let label = Label {
734                             ident: Ident::from_str_and_span(
735                                 &format!("'{}", segments[0].ident),
736                                 segments[0].ident.span,
737                             ),
738                         };
739                         match self.parse_labeled_expr(label, false) {
740                             Ok(expr) => {
741                                 type_err.cancel();
742                                 self.sess.emit_err(MalformedLoopLabel {
743                                     span: label.ident.span,
744                                     correct_label: label.ident,
745                                 });
746                                 return Ok(expr);
747                             }
748                             Err(err) => {
749                                 err.cancel();
750                                 self.restore_snapshot(snapshot);
751                             }
752                         }
753                     }
754                     _ => {}
755                 }
756
757                 match self.parse_path(PathStyle::Expr) {
758                     Ok(path) => {
759                         let span_after_type = parser_snapshot_after_type.token.span;
760                         let expr = mk_expr(
761                             self,
762                             lhs,
763                             self.mk_ty(path.span, TyKind::Path(None, path.clone())),
764                         );
765
766                         let args_span = self.look_ahead(1, |t| t.span).to(span_after_type);
767                         let suggestion = ComparisonOrShiftInterpretedAsGenericSugg {
768                             left: expr.span.shrink_to_lo(),
769                             right: expr.span.shrink_to_hi(),
770                         };
771
772                         match self.token.kind {
773                             token::Lt => self.sess.emit_err(ComparisonInterpretedAsGeneric {
774                                 comparison: self.token.span,
775                                 r#type: path,
776                                 args: args_span,
777                                 suggestion,
778                             }),
779                             token::BinOp(token::Shl) => {
780                                 self.sess.emit_err(ShiftInterpretedAsGeneric {
781                                     shift: self.token.span,
782                                     r#type: path,
783                                     args: args_span,
784                                     suggestion,
785                                 })
786                             }
787                             _ => {
788                                 // We can end up here even without `<` being the next token, for
789                                 // example because `parse_ty_no_plus` returns `Err` on keywords,
790                                 // but `parse_path` returns `Ok` on them due to error recovery.
791                                 // Return original error and parser state.
792                                 *self = parser_snapshot_after_type;
793                                 return Err(type_err);
794                             }
795                         };
796
797                         // Successfully parsed the type path leaving a `<` yet to parse.
798                         type_err.cancel();
799
800                         // Keep `x as usize` as an expression in AST and continue parsing.
801                         expr
802                     }
803                     Err(path_err) => {
804                         // Couldn't parse as a path, return original error and parser state.
805                         path_err.cancel();
806                         *self = parser_snapshot_after_type;
807                         return Err(type_err);
808                     }
809                 }
810             }
811         };
812
813         self.parse_and_disallow_postfix_after_cast(cast_expr)
814     }
815
816     /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
817     /// then emits an error and returns the newly parsed tree.
818     /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
819     fn parse_and_disallow_postfix_after_cast(
820         &mut self,
821         cast_expr: P<Expr>,
822     ) -> PResult<'a, P<Expr>> {
823         let span = cast_expr.span;
824         let (cast_kind, maybe_ascription_span) =
825             if let ExprKind::Type(ascripted_expr, _) = &cast_expr.kind {
826                 ("type ascription", Some(ascripted_expr.span.shrink_to_hi().with_hi(span.hi())))
827             } else {
828                 ("cast", None)
829             };
830
831         let with_postfix = self.parse_dot_or_call_expr_with_(cast_expr, span)?;
832
833         // Check if an illegal postfix operator has been added after the cast.
834         // If the resulting expression is not a cast, it is an illegal postfix operator.
835         if !matches!(with_postfix.kind, ExprKind::Cast(_, _) | ExprKind::Type(_, _)) {
836             let msg = format!(
837                 "{cast_kind} cannot be followed by {}",
838                 match with_postfix.kind {
839                     ExprKind::Index(_, _) => "indexing",
840                     ExprKind::Try(_) => "`?`",
841                     ExprKind::Field(_, _) => "a field access",
842                     ExprKind::MethodCall(_) => "a method call",
843                     ExprKind::Call(_, _) => "a function call",
844                     ExprKind::Await(_) => "`.await`",
845                     ExprKind::Err => return Ok(with_postfix),
846                     _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"),
847                 }
848             );
849             let mut err = self.struct_span_err(span, &msg);
850
851             let suggest_parens = |err: &mut Diagnostic| {
852                 let suggestions = vec![
853                     (span.shrink_to_lo(), "(".to_string()),
854                     (span.shrink_to_hi(), ")".to_string()),
855                 ];
856                 err.multipart_suggestion(
857                     "try surrounding the expression in parentheses",
858                     suggestions,
859                     Applicability::MachineApplicable,
860                 );
861             };
862
863             // If type ascription is "likely an error", the user will already be getting a useful
864             // help message, and doesn't need a second.
865             if self.last_type_ascription.map_or(false, |last_ascription| last_ascription.1) {
866                 self.maybe_annotate_with_ascription(&mut err, false);
867             } else if let Some(ascription_span) = maybe_ascription_span {
868                 let is_nightly = self.sess.unstable_features.is_nightly_build();
869                 if is_nightly {
870                     suggest_parens(&mut err);
871                 }
872                 err.span_suggestion(
873                     ascription_span,
874                     &format!(
875                         "{}remove the type ascription",
876                         if is_nightly { "alternatively, " } else { "" }
877                     ),
878                     "",
879                     if is_nightly {
880                         Applicability::MaybeIncorrect
881                     } else {
882                         Applicability::MachineApplicable
883                     },
884                 );
885             } else {
886                 suggest_parens(&mut err);
887             }
888             err.emit();
889         };
890         Ok(with_postfix)
891     }
892
893     fn parse_assoc_op_ascribe(&mut self, lhs: P<Expr>, lhs_span: Span) -> PResult<'a, P<Expr>> {
894         let maybe_path = self.could_ascription_be_path(&lhs.kind);
895         self.last_type_ascription = Some((self.prev_token.span, maybe_path));
896         let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
897         self.sess.gated_spans.gate(sym::type_ascription, lhs.span);
898         Ok(lhs)
899     }
900
901     /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
902     fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
903         self.expect_and()?;
904         let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
905         let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
906         let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo);
907         let expr = if self.token.is_range_separator() {
908             self.parse_prefix_range_expr(None)
909         } else {
910             self.parse_prefix_expr(None)
911         };
912         let (hi, expr) = self.interpolated_or_expr_span(expr)?;
913         let span = lo.to(hi);
914         if let Some(lt) = lifetime {
915             self.error_remove_borrow_lifetime(span, lt.ident.span);
916         }
917         Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
918     }
919
920     fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
921         self.sess.emit_err(LifetimeInBorrowExpression { span, lifetime_span: lt_span });
922     }
923
924     /// Parse `mut?` or `raw [ const | mut ]`.
925     fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) {
926         if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) {
927             // `raw [ const | mut ]`.
928             let found_raw = self.eat_keyword(kw::Raw);
929             assert!(found_raw);
930             let mutability = self.parse_const_or_mut().unwrap();
931             self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span));
932             (ast::BorrowKind::Raw, mutability)
933         } else {
934             // `mut?`
935             (ast::BorrowKind::Ref, self.parse_mutability())
936         }
937     }
938
939     /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
940     fn parse_dot_or_call_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
941         let attrs = self.parse_or_use_outer_attributes(attrs)?;
942         self.collect_tokens_for_expr(attrs, |this, attrs| {
943             let base = this.parse_bottom_expr();
944             let (span, base) = this.interpolated_or_expr_span(base)?;
945             this.parse_dot_or_call_expr_with(base, span, attrs)
946         })
947     }
948
949     pub(super) fn parse_dot_or_call_expr_with(
950         &mut self,
951         e0: P<Expr>,
952         lo: Span,
953         mut attrs: ast::AttrVec,
954     ) -> PResult<'a, P<Expr>> {
955         // Stitch the list of outer attributes onto the return value.
956         // A little bit ugly, but the best way given the current code
957         // structure
958         let res = self.parse_dot_or_call_expr_with_(e0, lo);
959         if attrs.is_empty() {
960             res
961         } else {
962             res.map(|expr| {
963                 expr.map(|mut expr| {
964                     attrs.extend(expr.attrs);
965                     expr.attrs = attrs;
966                     expr
967                 })
968             })
969         }
970     }
971
972     fn parse_dot_or_call_expr_with_(&mut self, mut e: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
973         loop {
974             let has_question = if self.prev_token.kind == TokenKind::Ident(kw::Return, false) {
975                 // we are using noexpect here because we don't expect a `?` directly after a `return`
976                 // which could be suggested otherwise
977                 self.eat_noexpect(&token::Question)
978             } else {
979                 self.eat(&token::Question)
980             };
981             if has_question {
982                 // `expr?`
983                 e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e));
984                 continue;
985             }
986             let has_dot = if self.prev_token.kind == TokenKind::Ident(kw::Return, false) {
987                 // we are using noexpect here because we don't expect a `.` directly after a `return`
988                 // which could be suggested otherwise
989                 self.eat_noexpect(&token::Dot)
990             } else {
991                 self.eat(&token::Dot)
992             };
993             if has_dot {
994                 // expr.f
995                 e = self.parse_dot_suffix_expr(lo, e)?;
996                 continue;
997             }
998             if self.expr_is_complete(&e) {
999                 return Ok(e);
1000             }
1001             e = match self.token.kind {
1002                 token::OpenDelim(Delimiter::Parenthesis) => self.parse_fn_call_expr(lo, e),
1003                 token::OpenDelim(Delimiter::Bracket) => self.parse_index_expr(lo, e)?,
1004                 _ => return Ok(e),
1005             }
1006         }
1007     }
1008
1009     fn look_ahead_type_ascription_as_field(&mut self) -> bool {
1010         self.look_ahead(1, |t| t.is_ident())
1011             && self.look_ahead(2, |t| t == &token::Colon)
1012             && self.look_ahead(3, |t| t.can_begin_expr())
1013     }
1014
1015     fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
1016         match self.token.uninterpolate().kind {
1017             token::Ident(..) => self.parse_dot_suffix(base, lo),
1018             token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
1019                 Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix, None))
1020             }
1021             token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => {
1022                 Ok(self.parse_tuple_field_access_expr_float(lo, base, symbol, suffix))
1023             }
1024             _ => {
1025                 self.error_unexpected_after_dot();
1026                 Ok(base)
1027             }
1028         }
1029     }
1030
1031     fn error_unexpected_after_dot(&self) {
1032         // FIXME Could factor this out into non_fatal_unexpected or something.
1033         let actual = pprust::token_to_string(&self.token);
1034         self.struct_span_err(self.token.span, &format!("unexpected token: `{actual}`")).emit();
1035     }
1036
1037     // We need an identifier or integer, but the next token is a float.
1038     // Break the float into components to extract the identifier or integer.
1039     // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
1040     // parts unless those parts are processed immediately. `TokenCursor` should either
1041     // support pushing "future tokens" (would be also helpful to `break_and_eat`), or
1042     // we should break everything including floats into more basic proc-macro style
1043     // tokens in the lexer (probably preferable).
1044     fn parse_tuple_field_access_expr_float(
1045         &mut self,
1046         lo: Span,
1047         base: P<Expr>,
1048         float: Symbol,
1049         suffix: Option<Symbol>,
1050     ) -> P<Expr> {
1051         #[derive(Debug)]
1052         enum FloatComponent {
1053             IdentLike(String),
1054             Punct(char),
1055         }
1056         use FloatComponent::*;
1057
1058         let float_str = float.as_str();
1059         let mut components = Vec::new();
1060         let mut ident_like = String::new();
1061         for c in float_str.chars() {
1062             if c == '_' || c.is_ascii_alphanumeric() {
1063                 ident_like.push(c);
1064             } else if matches!(c, '.' | '+' | '-') {
1065                 if !ident_like.is_empty() {
1066                     components.push(IdentLike(mem::take(&mut ident_like)));
1067                 }
1068                 components.push(Punct(c));
1069             } else {
1070                 panic!("unexpected character in a float token: {:?}", c)
1071             }
1072         }
1073         if !ident_like.is_empty() {
1074             components.push(IdentLike(ident_like));
1075         }
1076
1077         // With proc macros the span can refer to anything, the source may be too short,
1078         // or too long, or non-ASCII. It only makes sense to break our span into components
1079         // if its underlying text is identical to our float literal.
1080         let span = self.token.span;
1081         let can_take_span_apart =
1082             || self.span_to_snippet(span).as_deref() == Ok(float_str).as_deref();
1083
1084         match &*components {
1085             // 1e2
1086             [IdentLike(i)] => {
1087                 self.parse_tuple_field_access_expr(lo, base, Symbol::intern(&i), suffix, None)
1088             }
1089             // 1.
1090             [IdentLike(i), Punct('.')] => {
1091                 let (ident_span, dot_span) = if can_take_span_apart() {
1092                     let (span, ident_len) = (span.data(), BytePos::from_usize(i.len()));
1093                     let ident_span = span.with_hi(span.lo + ident_len);
1094                     let dot_span = span.with_lo(span.lo + ident_len);
1095                     (ident_span, dot_span)
1096                 } else {
1097                     (span, span)
1098                 };
1099                 assert!(suffix.is_none());
1100                 let symbol = Symbol::intern(&i);
1101                 self.token = Token::new(token::Ident(symbol, false), ident_span);
1102                 let next_token = (Token::new(token::Dot, dot_span), self.token_spacing);
1103                 self.parse_tuple_field_access_expr(lo, base, symbol, None, Some(next_token))
1104             }
1105             // 1.2 | 1.2e3
1106             [IdentLike(i1), Punct('.'), IdentLike(i2)] => {
1107                 let (ident1_span, dot_span, ident2_span) = if can_take_span_apart() {
1108                     let (span, ident1_len) = (span.data(), BytePos::from_usize(i1.len()));
1109                     let ident1_span = span.with_hi(span.lo + ident1_len);
1110                     let dot_span = span
1111                         .with_lo(span.lo + ident1_len)
1112                         .with_hi(span.lo + ident1_len + BytePos(1));
1113                     let ident2_span = self.token.span.with_lo(span.lo + ident1_len + BytePos(1));
1114                     (ident1_span, dot_span, ident2_span)
1115                 } else {
1116                     (span, span, span)
1117                 };
1118                 let symbol1 = Symbol::intern(&i1);
1119                 self.token = Token::new(token::Ident(symbol1, false), ident1_span);
1120                 // This needs to be `Spacing::Alone` to prevent regressions.
1121                 // See issue #76399 and PR #76285 for more details
1122                 let next_token1 = (Token::new(token::Dot, dot_span), Spacing::Alone);
1123                 let base1 =
1124                     self.parse_tuple_field_access_expr(lo, base, symbol1, None, Some(next_token1));
1125                 let symbol2 = Symbol::intern(&i2);
1126                 let next_token2 = Token::new(token::Ident(symbol2, false), ident2_span);
1127                 self.bump_with((next_token2, self.token_spacing)); // `.`
1128                 self.parse_tuple_field_access_expr(lo, base1, symbol2, suffix, None)
1129             }
1130             // 1e+ | 1e- (recovered)
1131             [IdentLike(_), Punct('+' | '-')] |
1132             // 1e+2 | 1e-2
1133             [IdentLike(_), Punct('+' | '-'), IdentLike(_)] |
1134             // 1.2e+ | 1.2e-
1135             [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-')] |
1136             // 1.2e+3 | 1.2e-3
1137             [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-'), IdentLike(_)] => {
1138                 // See the FIXME about `TokenCursor` above.
1139                 self.error_unexpected_after_dot();
1140                 base
1141             }
1142             _ => panic!("unexpected components in a float token: {:?}", components),
1143         }
1144     }
1145
1146     fn parse_tuple_field_access_expr(
1147         &mut self,
1148         lo: Span,
1149         base: P<Expr>,
1150         field: Symbol,
1151         suffix: Option<Symbol>,
1152         next_token: Option<(Token, Spacing)>,
1153     ) -> P<Expr> {
1154         match next_token {
1155             Some(next_token) => self.bump_with(next_token),
1156             None => self.bump(),
1157         }
1158         let span = self.prev_token.span;
1159         let field = ExprKind::Field(base, Ident::new(field, span));
1160         if let Some(suffix) = suffix {
1161             self.expect_no_tuple_index_suffix(span, suffix);
1162         }
1163         self.mk_expr(lo.to(span), field)
1164     }
1165
1166     /// Parse a function call expression, `expr(...)`.
1167     fn parse_fn_call_expr(&mut self, lo: Span, fun: P<Expr>) -> P<Expr> {
1168         let snapshot = if self.token.kind == token::OpenDelim(Delimiter::Parenthesis)
1169             && self.look_ahead_type_ascription_as_field()
1170         {
1171             Some((self.create_snapshot_for_diagnostic(), fun.kind.clone()))
1172         } else {
1173             None
1174         };
1175         let open_paren = self.token.span;
1176
1177         let mut seq = self
1178             .parse_paren_expr_seq()
1179             .map(|args| self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args)));
1180         if let Some(expr) =
1181             self.maybe_recover_struct_lit_bad_delims(lo, open_paren, &mut seq, snapshot)
1182         {
1183             return expr;
1184         }
1185         self.recover_seq_parse_error(Delimiter::Parenthesis, lo, seq)
1186     }
1187
1188     /// If we encounter a parser state that looks like the user has written a `struct` literal with
1189     /// parentheses instead of braces, recover the parser state and provide suggestions.
1190     #[instrument(skip(self, seq, snapshot), level = "trace")]
1191     fn maybe_recover_struct_lit_bad_delims(
1192         &mut self,
1193         lo: Span,
1194         open_paren: Span,
1195         seq: &mut PResult<'a, P<Expr>>,
1196         snapshot: Option<(SnapshotParser<'a>, ExprKind)>,
1197     ) -> Option<P<Expr>> {
1198         if !self.may_recover() {
1199             return None;
1200         }
1201
1202         match (seq.as_mut(), snapshot) {
1203             (Err(err), Some((mut snapshot, ExprKind::Path(None, path)))) => {
1204                 snapshot.bump(); // `(`
1205                 match snapshot.parse_struct_fields(path.clone(), false, Delimiter::Parenthesis) {
1206                     Ok((fields, ..))
1207                         if snapshot.eat(&token::CloseDelim(Delimiter::Parenthesis)) =>
1208                     {
1209                         // We are certain we have `Enum::Foo(a: 3, b: 4)`, suggest
1210                         // `Enum::Foo { a: 3, b: 4 }` or `Enum::Foo(3, 4)`.
1211                         self.restore_snapshot(snapshot);
1212                         let close_paren = self.prev_token.span;
1213                         let span = lo.to(self.prev_token.span);
1214                         if !fields.is_empty() {
1215                             let mut replacement_err = ParenthesesWithStructFields {
1216                                 span,
1217                                 r#type: path,
1218                                 braces_for_struct: BracesForStructLiteral {
1219                                     first: open_paren,
1220                                     second: close_paren,
1221                                 },
1222                                 no_fields_for_fn: NoFieldsForFnCall {
1223                                     fields: fields
1224                                         .into_iter()
1225                                         .map(|field| field.span.until(field.expr.span))
1226                                         .collect(),
1227                                 },
1228                             }
1229                             .into_diagnostic(&self.sess.span_diagnostic);
1230                             replacement_err.emit();
1231
1232                             let old_err = mem::replace(err, replacement_err);
1233                             old_err.cancel();
1234                         } else {
1235                             err.emit();
1236                         }
1237                         return Some(self.mk_expr_err(span));
1238                     }
1239                     Ok(_) => {}
1240                     Err(mut err) => {
1241                         err.emit();
1242                     }
1243                 }
1244             }
1245             _ => {}
1246         }
1247         None
1248     }
1249
1250     /// Parse an indexing expression `expr[...]`.
1251     fn parse_index_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
1252         let prev_span = self.prev_token.span;
1253         let open_delim_span = self.token.span;
1254         self.bump(); // `[`
1255         let index = self.parse_expr()?;
1256         self.suggest_missing_semicolon_before_array(prev_span, open_delim_span)?;
1257         self.expect(&token::CloseDelim(Delimiter::Bracket))?;
1258         Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_index(base, index)))
1259     }
1260
1261     /// Assuming we have just parsed `.`, continue parsing into an expression.
1262     fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
1263         if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) {
1264             return Ok(self.mk_await_expr(self_arg, lo));
1265         }
1266
1267         let fn_span_lo = self.token.span;
1268         let mut seg = self.parse_path_segment(PathStyle::Expr, None)?;
1269         self.check_trailing_angle_brackets(&seg, &[&token::OpenDelim(Delimiter::Parenthesis)]);
1270         self.check_turbofish_missing_angle_brackets(&mut seg);
1271
1272         if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1273             // Method call `expr.f()`
1274             let args = self.parse_paren_expr_seq()?;
1275             let fn_span = fn_span_lo.to(self.prev_token.span);
1276             let span = lo.to(self.prev_token.span);
1277             Ok(self.mk_expr(
1278                 span,
1279                 ExprKind::MethodCall(Box::new(ast::MethodCall {
1280                     seg,
1281                     receiver: self_arg,
1282                     args,
1283                     span: fn_span,
1284                 })),
1285             ))
1286         } else {
1287             // Field access `expr.f`
1288             if let Some(args) = seg.args {
1289                 self.sess.emit_err(FieldExpressionWithGeneric(args.span()));
1290             }
1291
1292             let span = lo.to(self.prev_token.span);
1293             Ok(self.mk_expr(span, ExprKind::Field(self_arg, seg.ident)))
1294         }
1295     }
1296
1297     /// At the bottom (top?) of the precedence hierarchy,
1298     /// Parses things like parenthesized exprs, macros, `return`, etc.
1299     ///
1300     /// N.B., this does not parse outer attributes, and is private because it only works
1301     /// correctly if called from `parse_dot_or_call_expr()`.
1302     fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1303         maybe_recover_from_interpolated_ty_qpath!(self, true);
1304         maybe_whole_expr!(self);
1305
1306         // Outer attributes are already parsed and will be
1307         // added to the return value after the fact.
1308
1309         // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
1310         let lo = self.token.span;
1311         if let token::Literal(_) = self.token.kind {
1312             // This match arm is a special-case of the `_` match arm below and
1313             // could be removed without changing functionality, but it's faster
1314             // to have it here, especially for programs with large constants.
1315             self.parse_lit_expr()
1316         } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1317             self.parse_tuple_parens_expr()
1318         } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
1319             self.parse_block_expr(None, lo, BlockCheckMode::Default)
1320         } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) {
1321             self.parse_closure_expr().map_err(|mut err| {
1322                 // If the input is something like `if a { 1 } else { 2 } | if a { 3 } else { 4 }`
1323                 // then suggest parens around the lhs.
1324                 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&lo) {
1325                     err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
1326                 }
1327                 err
1328             })
1329         } else if self.check(&token::OpenDelim(Delimiter::Bracket)) {
1330             self.parse_array_or_repeat_expr(Delimiter::Bracket)
1331         } else if self.check_path() {
1332             self.parse_path_start_expr()
1333         } else if self.check_keyword(kw::Move)
1334             || self.check_keyword(kw::Static)
1335             || self.check_const_closure()
1336         {
1337             self.parse_closure_expr()
1338         } else if self.eat_keyword(kw::If) {
1339             self.parse_if_expr()
1340         } else if self.check_keyword(kw::For) {
1341             if self.choose_generics_over_qpath(1) {
1342                 self.parse_closure_expr()
1343             } else {
1344                 assert!(self.eat_keyword(kw::For));
1345                 self.parse_for_expr(None, self.prev_token.span)
1346             }
1347         } else if self.eat_keyword(kw::While) {
1348             self.parse_while_expr(None, self.prev_token.span)
1349         } else if let Some(label) = self.eat_label() {
1350             self.parse_labeled_expr(label, true)
1351         } else if self.eat_keyword(kw::Loop) {
1352             let sp = self.prev_token.span;
1353             self.parse_loop_expr(None, self.prev_token.span).map_err(|mut err| {
1354                 err.span_label(sp, "while parsing this `loop` expression");
1355                 err
1356             })
1357         } else if self.eat_keyword(kw::Match) {
1358             let match_sp = self.prev_token.span;
1359             self.parse_match_expr().map_err(|mut err| {
1360                 err.span_label(match_sp, "while parsing this `match` expression");
1361                 err
1362             })
1363         } else if self.eat_keyword(kw::Unsafe) {
1364             let sp = self.prev_token.span;
1365             self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided)).map_err(
1366                 |mut err| {
1367                     err.span_label(sp, "while parsing this `unsafe` expression");
1368                     err
1369                 },
1370             )
1371         } else if self.check_inline_const(0) {
1372             self.parse_const_block(lo.to(self.token.span), false)
1373         } else if self.may_recover() && self.is_do_catch_block() {
1374             self.recover_do_catch()
1375         } else if self.is_try_block() {
1376             self.expect_keyword(kw::Try)?;
1377             self.parse_try_block(lo)
1378         } else if self.eat_keyword(kw::Return) {
1379             self.parse_return_expr()
1380         } else if self.eat_keyword(kw::Continue) {
1381             self.parse_continue_expr(lo)
1382         } else if self.eat_keyword(kw::Break) {
1383             self.parse_break_expr()
1384         } else if self.eat_keyword(kw::Yield) {
1385             self.parse_yield_expr()
1386         } else if self.is_do_yeet() {
1387             self.parse_yeet_expr()
1388         } else if self.check_keyword(kw::Let) {
1389             self.parse_let_expr()
1390         } else if self.eat_keyword(kw::Underscore) {
1391             Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore))
1392         } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1393             // Don't complain about bare semicolons after unclosed braces
1394             // recovery in order to keep the error count down. Fixing the
1395             // delimiters will possibly also fix the bare semicolon found in
1396             // expression context. For example, silence the following error:
1397             //
1398             //     error: expected expression, found `;`
1399             //      --> file.rs:2:13
1400             //       |
1401             //     2 |     foo(bar(;
1402             //       |             ^ expected expression
1403             self.bump();
1404             Ok(self.mk_expr_err(self.token.span))
1405         } else if self.token.uninterpolated_span().rust_2018() {
1406             // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1407             if self.check_keyword(kw::Async) {
1408                 if self.is_async_block() {
1409                     // Check for `async {` and `async move {`.
1410                     self.parse_async_block()
1411                 } else {
1412                     self.parse_closure_expr()
1413                 }
1414             } else if self.eat_keyword(kw::Await) {
1415                 self.recover_incorrect_await_syntax(lo, self.prev_token.span)
1416             } else {
1417                 self.parse_lit_expr()
1418             }
1419         } else {
1420             self.parse_lit_expr()
1421         }
1422     }
1423
1424     fn parse_lit_expr(&mut self) -> PResult<'a, P<Expr>> {
1425         let lo = self.token.span;
1426         match self.parse_opt_token_lit() {
1427             Some((token_lit, _)) => {
1428                 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(token_lit));
1429                 self.maybe_recover_from_bad_qpath(expr)
1430             }
1431             None => self.try_macro_suggestion(),
1432         }
1433     }
1434
1435     fn parse_tuple_parens_expr(&mut self) -> PResult<'a, P<Expr>> {
1436         let lo = self.token.span;
1437         self.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
1438         let (es, trailing_comma) = match self.parse_seq_to_end(
1439             &token::CloseDelim(Delimiter::Parenthesis),
1440             SeqSep::trailing_allowed(token::Comma),
1441             |p| p.parse_expr_catch_underscore(),
1442         ) {
1443             Ok(x) => x,
1444             Err(err) => {
1445                 return Ok(self.recover_seq_parse_error(Delimiter::Parenthesis, lo, Err(err)));
1446             }
1447         };
1448         let kind = if es.len() == 1 && !trailing_comma {
1449             // `(e)` is parenthesized `e`.
1450             ExprKind::Paren(es.into_iter().next().unwrap())
1451         } else {
1452             // `(e,)` is a tuple with only one field, `e`.
1453             ExprKind::Tup(es)
1454         };
1455         let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1456         self.maybe_recover_from_bad_qpath(expr)
1457     }
1458
1459     fn parse_array_or_repeat_expr(&mut self, close_delim: Delimiter) -> PResult<'a, P<Expr>> {
1460         let lo = self.token.span;
1461         self.bump(); // `[` or other open delim
1462
1463         let close = &token::CloseDelim(close_delim);
1464         let kind = if self.eat(close) {
1465             // Empty vector
1466             ExprKind::Array(Vec::new())
1467         } else {
1468             // Non-empty vector
1469             let first_expr = self.parse_expr()?;
1470             if self.eat(&token::Semi) {
1471                 // Repeating array syntax: `[ 0; 512 ]`
1472                 let count = self.parse_anon_const_expr()?;
1473                 self.expect(close)?;
1474                 ExprKind::Repeat(first_expr, count)
1475             } else if self.eat(&token::Comma) {
1476                 // Vector with two or more elements.
1477                 let sep = SeqSep::trailing_allowed(token::Comma);
1478                 let (mut exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1479                 exprs.insert(0, first_expr);
1480                 ExprKind::Array(exprs)
1481             } else {
1482                 // Vector with one element
1483                 self.expect(close)?;
1484                 ExprKind::Array(vec![first_expr])
1485             }
1486         };
1487         let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1488         self.maybe_recover_from_bad_qpath(expr)
1489     }
1490
1491     fn parse_path_start_expr(&mut self) -> PResult<'a, P<Expr>> {
1492         let (qself, path) = if self.eat_lt() {
1493             let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
1494             (Some(qself), path)
1495         } else {
1496             (None, self.parse_path(PathStyle::Expr)?)
1497         };
1498
1499         // `!`, as an operator, is prefix, so we know this isn't that.
1500         let (span, kind) = if self.eat(&token::Not) {
1501             // MACRO INVOCATION expression
1502             if qself.is_some() {
1503                 self.sess.emit_err(MacroInvocationWithQualifiedPath(path.span));
1504             }
1505             let lo = path.span;
1506             let mac = P(MacCall {
1507                 path,
1508                 args: self.parse_delim_args()?,
1509                 prior_type_ascription: self.last_type_ascription,
1510             });
1511             (lo.to(self.prev_token.span), ExprKind::MacCall(mac))
1512         } else if self.check(&token::OpenDelim(Delimiter::Brace))
1513             && let Some(expr) = self.maybe_parse_struct_expr(&qself, &path)
1514         {
1515             if qself.is_some() {
1516                 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
1517             }
1518             return expr;
1519         } else {
1520             (path.span, ExprKind::Path(qself, path))
1521         };
1522
1523         let expr = self.mk_expr(span, kind);
1524         self.maybe_recover_from_bad_qpath(expr)
1525     }
1526
1527     /// Parse `'label: $expr`. The label is already parsed.
1528     fn parse_labeled_expr(
1529         &mut self,
1530         label_: Label,
1531         mut consume_colon: bool,
1532     ) -> PResult<'a, P<Expr>> {
1533         let lo = label_.ident.span;
1534         let label = Some(label_);
1535         let ate_colon = self.eat(&token::Colon);
1536         let expr = if self.eat_keyword(kw::While) {
1537             self.parse_while_expr(label, lo)
1538         } else if self.eat_keyword(kw::For) {
1539             self.parse_for_expr(label, lo)
1540         } else if self.eat_keyword(kw::Loop) {
1541             self.parse_loop_expr(label, lo)
1542         } else if self.check_noexpect(&token::OpenDelim(Delimiter::Brace))
1543             || self.token.is_whole_block()
1544         {
1545             self.parse_block_expr(label, lo, BlockCheckMode::Default)
1546         } else if !ate_colon
1547             && self.may_recover()
1548             && (matches!(self.token.kind, token::CloseDelim(_) | token::Comma)
1549                 || self.token.is_op())
1550         {
1551             let (lit, _) =
1552                 self.recover_unclosed_char(label_.ident, Parser::mk_token_lit_char, |self_| {
1553                     self_.sess.create_err(UnexpectedTokenAfterLabel {
1554                         span: self_.token.span,
1555                         remove_label: None,
1556                         enclose_in_block: None,
1557                     })
1558                 });
1559             consume_colon = false;
1560             Ok(self.mk_expr(lo, ExprKind::Lit(lit)))
1561         } else if !ate_colon
1562             && (self.check_noexpect(&TokenKind::Comma) || self.check_noexpect(&TokenKind::Gt))
1563         {
1564             // We're probably inside of a `Path<'a>` that needs a turbofish
1565             self.sess.emit_err(UnexpectedTokenAfterLabel {
1566                 span: self.token.span,
1567                 remove_label: None,
1568                 enclose_in_block: None,
1569             });
1570             consume_colon = false;
1571             Ok(self.mk_expr_err(lo))
1572         } else {
1573             let mut err = UnexpectedTokenAfterLabel {
1574                 span: self.token.span,
1575                 remove_label: None,
1576                 enclose_in_block: None,
1577             };
1578
1579             // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1580             let expr = self.parse_expr().map(|expr| {
1581                 let span = expr.span;
1582
1583                 let found_labeled_breaks = {
1584                     struct FindLabeledBreaksVisitor(bool);
1585
1586                     impl<'ast> Visitor<'ast> for FindLabeledBreaksVisitor {
1587                         fn visit_expr_post(&mut self, ex: &'ast Expr) {
1588                             if let ExprKind::Break(Some(_label), _) = ex.kind {
1589                                 self.0 = true;
1590                             }
1591                         }
1592                     }
1593
1594                     let mut vis = FindLabeledBreaksVisitor(false);
1595                     vis.visit_expr(&expr);
1596                     vis.0
1597                 };
1598
1599                 // Suggestion involves adding a labeled block.
1600                 //
1601                 // If there are no breaks that may use this label, suggest removing the label and
1602                 // recover to the unmodified expression.
1603                 if !found_labeled_breaks {
1604                     err.remove_label = Some(lo.until(span));
1605
1606                     return expr;
1607                 }
1608
1609                 err.enclose_in_block = Some(UnexpectedTokenAfterLabelSugg {
1610                     left: span.shrink_to_lo(),
1611                     right: span.shrink_to_hi(),
1612                 });
1613
1614                 // Replace `'label: non_block_expr` with `'label: {non_block_expr}` in order to suppress future errors about `break 'label`.
1615                 let stmt = self.mk_stmt(span, StmtKind::Expr(expr));
1616                 let blk = self.mk_block(vec![stmt], BlockCheckMode::Default, span);
1617                 self.mk_expr(span, ExprKind::Block(blk, label))
1618             });
1619
1620             self.sess.emit_err(err);
1621             expr
1622         }?;
1623
1624         if !ate_colon && consume_colon {
1625             self.sess.emit_err(RequireColonAfterLabeledExpression {
1626                 span: expr.span,
1627                 label: lo,
1628                 label_end: lo.shrink_to_hi(),
1629             });
1630         }
1631
1632         Ok(expr)
1633     }
1634
1635     /// Emit an error when a char is parsed as a lifetime because of a missing quote.
1636     pub(super) fn recover_unclosed_char<L>(
1637         &self,
1638         lifetime: Ident,
1639         mk_lit_char: impl FnOnce(Symbol, Span) -> L,
1640         err: impl FnOnce(&Self) -> DiagnosticBuilder<'a, ErrorGuaranteed>,
1641     ) -> L {
1642         if let Some(mut diag) =
1643             self.sess.span_diagnostic.steal_diagnostic(lifetime.span, StashKey::LifetimeIsChar)
1644         {
1645             diag.span_suggestion_verbose(
1646                 lifetime.span.shrink_to_hi(),
1647                 "add `'` to close the char literal",
1648                 "'",
1649                 Applicability::MaybeIncorrect,
1650             )
1651             .emit();
1652         } else {
1653             err(self)
1654                 .span_suggestion_verbose(
1655                     lifetime.span.shrink_to_hi(),
1656                     "add `'` to close the char literal",
1657                     "'",
1658                     Applicability::MaybeIncorrect,
1659                 )
1660                 .emit();
1661         }
1662         let name = lifetime.without_first_quote().name;
1663         mk_lit_char(name, lifetime.span)
1664     }
1665
1666     /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1667     fn recover_do_catch(&mut self) -> PResult<'a, P<Expr>> {
1668         let lo = self.token.span;
1669
1670         self.bump(); // `do`
1671         self.bump(); // `catch`
1672
1673         let span = lo.to(self.prev_token.span);
1674         self.sess.emit_err(DoCatchSyntaxRemoved { span });
1675
1676         self.parse_try_block(lo)
1677     }
1678
1679     /// Parse an expression if the token can begin one.
1680     fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1681         Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1682     }
1683
1684     /// Parse `"return" expr?`.
1685     fn parse_return_expr(&mut self) -> PResult<'a, P<Expr>> {
1686         let lo = self.prev_token.span;
1687         let kind = ExprKind::Ret(self.parse_expr_opt()?);
1688         let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1689         self.maybe_recover_from_bad_qpath(expr)
1690     }
1691
1692     /// Parse `"do" "yeet" expr?`.
1693     fn parse_yeet_expr(&mut self) -> PResult<'a, P<Expr>> {
1694         let lo = self.token.span;
1695
1696         self.bump(); // `do`
1697         self.bump(); // `yeet`
1698
1699         let kind = ExprKind::Yeet(self.parse_expr_opt()?);
1700
1701         let span = lo.to(self.prev_token.span);
1702         self.sess.gated_spans.gate(sym::yeet_expr, span);
1703         let expr = self.mk_expr(span, kind);
1704         self.maybe_recover_from_bad_qpath(expr)
1705     }
1706
1707     /// Parse `"break" (('label (:? expr)?) | expr?)` with `"break"` token already eaten.
1708     /// If the label is followed immediately by a `:` token, the label and `:` are
1709     /// parsed as part of the expression (i.e. a labeled loop). The language team has
1710     /// decided in #87026 to require parentheses as a visual aid to avoid confusion if
1711     /// the break expression of an unlabeled break is a labeled loop (as in
1712     /// `break 'lbl: loop {}`); a labeled break with an unlabeled loop as its value
1713     /// expression only gets a warning for compatibility reasons; and a labeled break
1714     /// with a labeled loop does not even get a warning because there is no ambiguity.
1715     fn parse_break_expr(&mut self) -> PResult<'a, P<Expr>> {
1716         let lo = self.prev_token.span;
1717         let mut label = self.eat_label();
1718         let kind = if self.token == token::Colon && let Some(label) = label.take() {
1719             // The value expression can be a labeled loop, see issue #86948, e.g.:
1720             // `loop { break 'label: loop { break 'label 42; }; }`
1721             let lexpr = self.parse_labeled_expr(label, true)?;
1722             self.sess.emit_err(LabeledLoopInBreak {
1723                 span: lexpr.span,
1724                 sub: WrapExpressionInParentheses {
1725                     left: lexpr.span.shrink_to_lo(),
1726                     right: lexpr.span.shrink_to_hi(),
1727                 },
1728             });
1729             Some(lexpr)
1730         } else if self.token != token::OpenDelim(Delimiter::Brace)
1731             || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1732         {
1733             let mut expr = self.parse_expr_opt()?;
1734             if let Some(expr) = &mut expr {
1735                 if label.is_some()
1736                     && matches!(
1737                         expr.kind,
1738                         ExprKind::While(_, _, None)
1739                             | ExprKind::ForLoop(_, _, _, None)
1740                             | ExprKind::Loop(_, None, _)
1741                             | ExprKind::Block(_, None)
1742                     )
1743                 {
1744                     self.sess.buffer_lint_with_diagnostic(
1745                         BREAK_WITH_LABEL_AND_LOOP,
1746                         lo.to(expr.span),
1747                         ast::CRATE_NODE_ID,
1748                         "this labeled break expression is easy to confuse with an unlabeled break with a labeled value expression",
1749                         BuiltinLintDiagnostics::BreakWithLabelAndLoop(expr.span),
1750                     );
1751                 }
1752
1753                 // Recover `break label aaaaa`
1754                 if self.may_recover()
1755                     && let ExprKind::Path(None, p) = &expr.kind
1756                     && let [segment] = &*p.segments
1757                     && let &ast::PathSegment { ident, args: None, .. } = segment
1758                     && let Some(next) = self.parse_expr_opt()?
1759                 {
1760                     label = Some(self.recover_ident_into_label(ident));
1761                     *expr = next;
1762                 }
1763             }
1764
1765             expr
1766         } else {
1767             None
1768         };
1769         let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind));
1770         self.maybe_recover_from_bad_qpath(expr)
1771     }
1772
1773     /// Parse `"continue" label?`.
1774     fn parse_continue_expr(&mut self, lo: Span) -> PResult<'a, P<Expr>> {
1775         let mut label = self.eat_label();
1776
1777         // Recover `continue label` -> `continue 'label`
1778         if self.may_recover()
1779             && label.is_none()
1780             && let Some((ident, _)) = self.token.ident()
1781         {
1782             self.bump();
1783             label = Some(self.recover_ident_into_label(ident));
1784         }
1785
1786         let kind = ExprKind::Continue(label);
1787         Ok(self.mk_expr(lo.to(self.prev_token.span), kind))
1788     }
1789
1790     /// Parse `"yield" expr?`.
1791     fn parse_yield_expr(&mut self) -> PResult<'a, P<Expr>> {
1792         let lo = self.prev_token.span;
1793         let kind = ExprKind::Yield(self.parse_expr_opt()?);
1794         let span = lo.to(self.prev_token.span);
1795         self.sess.gated_spans.gate(sym::generators, span);
1796         let expr = self.mk_expr(span, kind);
1797         self.maybe_recover_from_bad_qpath(expr)
1798     }
1799
1800     /// Returns a string literal if the next token is a string literal.
1801     /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1802     /// and returns `None` if the next token is not literal at all.
1803     pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<MetaItemLit>> {
1804         match self.parse_opt_meta_item_lit() {
1805             Some(lit) => match lit.kind {
1806                 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1807                     style,
1808                     symbol: lit.symbol,
1809                     suffix: lit.suffix,
1810                     span: lit.span,
1811                     symbol_unescaped,
1812                 }),
1813                 _ => Err(Some(lit)),
1814             },
1815             None => Err(None),
1816         }
1817     }
1818
1819     pub(crate) fn mk_token_lit_char(name: Symbol, span: Span) -> (token::Lit, Span) {
1820         (token::Lit { symbol: name, suffix: None, kind: token::Char }, span)
1821     }
1822
1823     fn mk_meta_item_lit_char(name: Symbol, span: Span) -> MetaItemLit {
1824         ast::MetaItemLit {
1825             symbol: name,
1826             suffix: None,
1827             kind: ast::LitKind::Char(name.as_str().chars().next().unwrap_or('_')),
1828             span,
1829         }
1830     }
1831
1832     fn handle_missing_lit<L>(
1833         &mut self,
1834         mk_lit_char: impl FnOnce(Symbol, Span) -> L,
1835     ) -> PResult<'a, L> {
1836         if let token::Interpolated(inner) = &self.token.kind {
1837             let expr = match inner.as_ref() {
1838                 token::NtExpr(expr) => Some(expr),
1839                 token::NtLiteral(expr) => Some(expr),
1840                 _ => None,
1841             };
1842             if let Some(expr) = expr {
1843                 if matches!(expr.kind, ExprKind::Err) {
1844                     let mut err = InvalidInterpolatedExpression { span: self.token.span }
1845                         .into_diagnostic(&self.sess.span_diagnostic);
1846                     err.downgrade_to_delayed_bug();
1847                     return Err(err);
1848                 }
1849             }
1850         }
1851         let token = self.token.clone();
1852         let err = |self_: &Self| {
1853             let msg = format!("unexpected token: {}", super::token_descr(&token));
1854             self_.struct_span_err(token.span, &msg)
1855         };
1856         // On an error path, eagerly consider a lifetime to be an unclosed character lit
1857         if self.token.is_lifetime() {
1858             let lt = self.expect_lifetime();
1859             Ok(self.recover_unclosed_char(lt.ident, mk_lit_char, err))
1860         } else {
1861             Err(err(self))
1862         }
1863     }
1864
1865     pub(super) fn parse_token_lit(&mut self) -> PResult<'a, (token::Lit, Span)> {
1866         self.parse_opt_token_lit()
1867             .ok_or(())
1868             .or_else(|()| self.handle_missing_lit(Parser::mk_token_lit_char))
1869     }
1870
1871     pub(super) fn parse_meta_item_lit(&mut self) -> PResult<'a, MetaItemLit> {
1872         self.parse_opt_meta_item_lit()
1873             .ok_or(())
1874             .or_else(|()| self.handle_missing_lit(Parser::mk_meta_item_lit_char))
1875     }
1876
1877     fn recover_after_dot(&mut self) -> Option<Token> {
1878         let mut recovered = None;
1879         if self.token == token::Dot {
1880             // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1881             // dot would follow an optional literal, so we do this unconditionally.
1882             recovered = self.look_ahead(1, |next_token| {
1883                 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1884                     next_token.kind
1885                 {
1886                     // If this integer looks like a float, then recover as such.
1887                     //
1888                     // We will never encounter the exponent part of a floating
1889                     // point literal here, since there's no use of the exponent
1890                     // syntax that also constitutes a valid integer, so we need
1891                     // not check for that.
1892                     if suffix.map_or(true, |s| s == sym::f32 || s == sym::f64)
1893                         && symbol.as_str().chars().all(|c| c.is_numeric() || c == '_')
1894                         && self.token.span.hi() == next_token.span.lo()
1895                     {
1896                         let s = String::from("0.") + symbol.as_str();
1897                         let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1898                         return Some(Token::new(kind, self.token.span.to(next_token.span)));
1899                     }
1900                 }
1901                 None
1902             });
1903             if let Some(token) = &recovered {
1904                 self.bump();
1905                 self.sess.emit_err(FloatLiteralRequiresIntegerPart {
1906                     span: token.span,
1907                     correct: pprust::token_to_string(token).into_owned(),
1908                 });
1909             }
1910         }
1911
1912         recovered
1913     }
1914
1915     /// Matches `lit = true | false | token_lit`.
1916     /// Returns `None` if the next token is not a literal.
1917     pub(super) fn parse_opt_token_lit(&mut self) -> Option<(token::Lit, Span)> {
1918         let recovered = self.recover_after_dot();
1919         let token = recovered.as_ref().unwrap_or(&self.token);
1920         let span = token.span;
1921         token::Lit::from_token(token).map(|token_lit| {
1922             self.bump();
1923             (token_lit, span)
1924         })
1925     }
1926
1927     /// Matches `lit = true | false | token_lit`.
1928     /// Returns `None` if the next token is not a literal.
1929     pub(super) fn parse_opt_meta_item_lit(&mut self) -> Option<MetaItemLit> {
1930         let recovered = self.recover_after_dot();
1931         let token = recovered.as_ref().unwrap_or(&self.token);
1932         match token::Lit::from_token(token) {
1933             Some(token_lit) => {
1934                 match MetaItemLit::from_token_lit(token_lit, token.span) {
1935                     Ok(lit) => {
1936                         self.bump();
1937                         Some(lit)
1938                     }
1939                     Err(err) => {
1940                         let span = token.span;
1941                         let token::Literal(lit) = token.kind else {
1942                             unreachable!();
1943                         };
1944                         self.bump();
1945                         report_lit_error(&self.sess, err, lit, span);
1946                         // Pack possible quotes and prefixes from the original literal into
1947                         // the error literal's symbol so they can be pretty-printed faithfully.
1948                         let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1949                         let symbol = Symbol::intern(&suffixless_lit.to_string());
1950                         let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1951                         Some(
1952                             MetaItemLit::from_token_lit(lit, span)
1953                                 .unwrap_or_else(|_| unreachable!()),
1954                         )
1955                     }
1956                 }
1957             }
1958             None => None,
1959         }
1960     }
1961
1962     pub(super) fn expect_no_tuple_index_suffix(&self, span: Span, suffix: Symbol) {
1963         if [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suffix) {
1964             // #59553: warn instead of reject out of hand to allow the fix to percolate
1965             // through the ecosystem when people fix their macros
1966             self.sess.emit_warning(InvalidLiteralSuffixOnTupleIndex {
1967                 span,
1968                 suffix,
1969                 exception: Some(()),
1970             });
1971         } else {
1972             self.sess.emit_err(InvalidLiteralSuffixOnTupleIndex { span, suffix, exception: None });
1973         }
1974     }
1975
1976     /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1977     /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
1978     pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1979         maybe_whole_expr!(self);
1980
1981         let lo = self.token.span;
1982         let minus_present = self.eat(&token::BinOp(token::Minus));
1983         let (token_lit, span) = self.parse_token_lit()?;
1984         let expr = self.mk_expr(span, ExprKind::Lit(token_lit));
1985
1986         if minus_present {
1987             Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_unary(UnOp::Neg, expr)))
1988         } else {
1989             Ok(expr)
1990         }
1991     }
1992
1993     fn is_array_like_block(&mut self) -> bool {
1994         self.look_ahead(1, |t| matches!(t.kind, TokenKind::Ident(..) | TokenKind::Literal(_)))
1995             && self.look_ahead(2, |t| t == &token::Comma)
1996             && self.look_ahead(3, |t| t.can_begin_expr())
1997     }
1998
1999     /// Emits a suggestion if it looks like the user meant an array but
2000     /// accidentally used braces, causing the code to be interpreted as a block
2001     /// expression.
2002     fn maybe_suggest_brackets_instead_of_braces(&mut self, lo: Span) -> Option<P<Expr>> {
2003         let mut snapshot = self.create_snapshot_for_diagnostic();
2004         match snapshot.parse_array_or_repeat_expr(Delimiter::Brace) {
2005             Ok(arr) => {
2006                 self.sess.emit_err(ArrayBracketsInsteadOfSpaces {
2007                     span: arr.span,
2008                     sub: ArrayBracketsInsteadOfSpacesSugg {
2009                         left: lo,
2010                         right: snapshot.prev_token.span,
2011                     },
2012                 });
2013
2014                 self.restore_snapshot(snapshot);
2015                 Some(self.mk_expr_err(arr.span))
2016             }
2017             Err(e) => {
2018                 e.cancel();
2019                 None
2020             }
2021         }
2022     }
2023
2024     fn suggest_missing_semicolon_before_array(
2025         &self,
2026         prev_span: Span,
2027         open_delim_span: Span,
2028     ) -> PResult<'a, ()> {
2029         if !self.may_recover() {
2030             return Ok(());
2031         }
2032
2033         if self.token.kind == token::Comma {
2034             if !self.sess.source_map().is_multiline(prev_span.until(self.token.span)) {
2035                 return Ok(());
2036             }
2037             let mut snapshot = self.create_snapshot_for_diagnostic();
2038             snapshot.bump();
2039             match snapshot.parse_seq_to_before_end(
2040                 &token::CloseDelim(Delimiter::Bracket),
2041                 SeqSep::trailing_allowed(token::Comma),
2042                 |p| p.parse_expr(),
2043             ) {
2044                 Ok(_)
2045                     // When the close delim is `)`, `token.kind` is expected to be `token::CloseDelim(Delimiter::Parenthesis)`,
2046                     // but the actual `token.kind` is `token::CloseDelim(Delimiter::Bracket)`.
2047                     // This is because the `token.kind` of the close delim is treated as the same as
2048                     // that of the open delim in `TokenTreesReader::parse_token_tree`, even if the delimiters of them are different.
2049                     // Therefore, `token.kind` should not be compared here.
2050                     if snapshot
2051                         .span_to_snippet(snapshot.token.span)
2052                         .map_or(false, |snippet| snippet == "]") =>
2053                 {
2054                     return Err(MissingSemicolonBeforeArray {
2055                         open_delim: open_delim_span,
2056                         semicolon: prev_span.shrink_to_hi(),
2057                     }.into_diagnostic(&self.sess.span_diagnostic));
2058                 }
2059                 Ok(_) => (),
2060                 Err(err) => err.cancel(),
2061             }
2062         }
2063         Ok(())
2064     }
2065
2066     /// Parses a block or unsafe block.
2067     pub(super) fn parse_block_expr(
2068         &mut self,
2069         opt_label: Option<Label>,
2070         lo: Span,
2071         blk_mode: BlockCheckMode,
2072     ) -> PResult<'a, P<Expr>> {
2073         if self.may_recover() && self.is_array_like_block() {
2074             if let Some(arr) = self.maybe_suggest_brackets_instead_of_braces(lo) {
2075                 return Ok(arr);
2076             }
2077         }
2078
2079         if self.token.is_whole_block() {
2080             self.sess.emit_err(InvalidBlockMacroSegment {
2081                 span: self.token.span,
2082                 context: lo.to(self.token.span),
2083             });
2084         }
2085
2086         let (attrs, blk) = self.parse_block_common(lo, blk_mode, true)?;
2087         Ok(self.mk_expr_with_attrs(blk.span, ExprKind::Block(blk, opt_label), attrs))
2088     }
2089
2090     /// Parse a block which takes no attributes and has no label
2091     fn parse_simple_block(&mut self) -> PResult<'a, P<Expr>> {
2092         let blk = self.parse_block()?;
2093         Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None)))
2094     }
2095
2096     /// Parses a closure expression (e.g., `move |args| expr`).
2097     fn parse_closure_expr(&mut self) -> PResult<'a, P<Expr>> {
2098         let lo = self.token.span;
2099
2100         let binder = if self.check_keyword(kw::For) {
2101             let lo = self.token.span;
2102             let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
2103             let span = lo.to(self.prev_token.span);
2104
2105             self.sess.gated_spans.gate(sym::closure_lifetime_binder, span);
2106
2107             ClosureBinder::For { span, generic_params: P::from_vec(lifetime_defs) }
2108         } else {
2109             ClosureBinder::NotPresent
2110         };
2111
2112         let constness = self.parse_constness(Case::Sensitive);
2113
2114         let movability =
2115             if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
2116
2117         let asyncness = if self.token.uninterpolated_span().rust_2018() {
2118             self.parse_asyncness(Case::Sensitive)
2119         } else {
2120             Async::No
2121         };
2122
2123         let capture_clause = self.parse_capture_clause()?;
2124         let (fn_decl, fn_arg_span) = self.parse_fn_block_decl()?;
2125         let decl_hi = self.prev_token.span;
2126         let mut body = match fn_decl.output {
2127             FnRetTy::Default(_) => {
2128                 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
2129                 self.parse_expr_res(restrictions, None)?
2130             }
2131             _ => {
2132                 // If an explicit return type is given, require a block to appear (RFC 968).
2133                 let body_lo = self.token.span;
2134                 self.parse_block_expr(None, body_lo, BlockCheckMode::Default)?
2135             }
2136         };
2137
2138         if let Async::Yes { span, .. } = asyncness {
2139             // Feature-gate `async ||` closures.
2140             self.sess.gated_spans.gate(sym::async_closure, span);
2141         }
2142
2143         if self.token.kind == TokenKind::Semi
2144             && matches!(self.token_cursor.frame.delim_sp, Some((Delimiter::Parenthesis, _)))
2145             && self.may_recover()
2146         {
2147             // It is likely that the closure body is a block but where the
2148             // braces have been removed. We will recover and eat the next
2149             // statements later in the parsing process.
2150             body = self.mk_expr_err(body.span);
2151         }
2152
2153         let body_span = body.span;
2154
2155         let closure = self.mk_expr(
2156             lo.to(body.span),
2157             ExprKind::Closure(Box::new(ast::Closure {
2158                 binder,
2159                 capture_clause,
2160                 constness,
2161                 asyncness,
2162                 movability,
2163                 fn_decl,
2164                 body,
2165                 fn_decl_span: lo.to(decl_hi),
2166                 fn_arg_span,
2167             })),
2168         );
2169
2170         // Disable recovery for closure body
2171         let spans =
2172             ClosureSpans { whole_closure: closure.span, closing_pipe: decl_hi, body: body_span };
2173         self.current_closure = Some(spans);
2174
2175         Ok(closure)
2176     }
2177
2178     /// Parses an optional `move` prefix to a closure-like construct.
2179     fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> {
2180         if self.eat_keyword(kw::Move) {
2181             // Check for `move async` and recover
2182             if self.check_keyword(kw::Async) {
2183                 let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
2184                 Err(AsyncMoveOrderIncorrect { span: move_async_span }
2185                     .into_diagnostic(&self.sess.span_diagnostic))
2186             } else {
2187                 Ok(CaptureBy::Value)
2188             }
2189         } else {
2190             Ok(CaptureBy::Ref)
2191         }
2192     }
2193
2194     /// Parses the `|arg, arg|` header of a closure.
2195     fn parse_fn_block_decl(&mut self) -> PResult<'a, (P<FnDecl>, Span)> {
2196         let arg_start = self.token.span.lo();
2197
2198         let inputs = if self.eat(&token::OrOr) {
2199             Vec::new()
2200         } else {
2201             self.expect(&token::BinOp(token::Or))?;
2202             let args = self
2203                 .parse_seq_to_before_tokens(
2204                     &[&token::BinOp(token::Or), &token::OrOr],
2205                     SeqSep::trailing_allowed(token::Comma),
2206                     TokenExpectType::NoExpect,
2207                     |p| p.parse_fn_block_param(),
2208                 )?
2209                 .0;
2210             self.expect_or()?;
2211             args
2212         };
2213         let arg_span = self.prev_token.span.with_lo(arg_start);
2214         let output =
2215             self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes, RecoverReturnSign::Yes)?;
2216
2217         Ok((P(FnDecl { inputs, output }), arg_span))
2218     }
2219
2220     /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
2221     fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
2222         let lo = self.token.span;
2223         let attrs = self.parse_outer_attributes()?;
2224         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2225             let pat = this.parse_pat_no_top_alt(Some(Expected::ParameterName))?;
2226             let ty = if this.eat(&token::Colon) {
2227                 this.parse_ty()?
2228             } else {
2229                 this.mk_ty(this.prev_token.span, TyKind::Infer)
2230             };
2231
2232             Ok((
2233                 Param {
2234                     attrs,
2235                     ty,
2236                     pat,
2237                     span: lo.to(this.prev_token.span),
2238                     id: DUMMY_NODE_ID,
2239                     is_placeholder: false,
2240                 },
2241                 TrailingToken::MaybeComma,
2242             ))
2243         })
2244     }
2245
2246     /// Parses an `if` expression (`if` token already eaten).
2247     fn parse_if_expr(&mut self) -> PResult<'a, P<Expr>> {
2248         let lo = self.prev_token.span;
2249         let cond = self.parse_cond_expr()?;
2250         self.parse_if_after_cond(lo, cond)
2251     }
2252
2253     fn parse_if_after_cond(&mut self, lo: Span, mut cond: P<Expr>) -> PResult<'a, P<Expr>> {
2254         let cond_span = cond.span;
2255         // Tries to interpret `cond` as either a missing expression if it's a block,
2256         // or as an unfinished expression if it's a binop and the RHS is a block.
2257         // We could probably add more recoveries here too...
2258         let mut recover_block_from_condition = |this: &mut Self| {
2259             let block = match &mut cond.kind {
2260                 ExprKind::Binary(Spanned { span: binop_span, .. }, _, right)
2261                     if let ExprKind::Block(_, None) = right.kind => {
2262                         self.sess.emit_err(IfExpressionMissingThenBlock {
2263                             if_span: lo,
2264                             missing_then_block_sub:
2265                                 IfExpressionMissingThenBlockSub::UnfinishedCondition(cond_span.shrink_to_lo().to(*binop_span)),
2266                                 let_else_sub: None,
2267
2268                         });
2269                         std::mem::replace(right, this.mk_expr_err(binop_span.shrink_to_hi()))
2270                     },
2271                 ExprKind::Block(_, None) => {
2272                     self.sess.emit_err(IfExpressionMissingCondition {
2273                         if_span: lo.shrink_to_hi(),
2274                         block_span: self.sess.source_map().start_point(cond_span),
2275                     });
2276                     std::mem::replace(&mut cond, this.mk_expr_err(cond_span.shrink_to_hi()))
2277                 }
2278                 _ => {
2279                     return None;
2280                 }
2281             };
2282             if let ExprKind::Block(block, _) = &block.kind {
2283                 Some(block.clone())
2284             } else {
2285                 unreachable!()
2286             }
2287         };
2288         // Parse then block
2289         let thn = if self.token.is_keyword(kw::Else) {
2290             if let Some(block) = recover_block_from_condition(self) {
2291                 block
2292             } else {
2293                 let let_else_sub = matches!(cond.kind, ExprKind::Let(..))
2294                     .then(|| IfExpressionLetSomeSub { if_span: lo.until(cond_span) });
2295
2296                 self.sess.emit_err(IfExpressionMissingThenBlock {
2297                     if_span: lo,
2298                     missing_then_block_sub: IfExpressionMissingThenBlockSub::AddThenBlock(
2299                         cond_span.shrink_to_hi(),
2300                     ),
2301                     let_else_sub,
2302                 });
2303                 self.mk_block_err(cond_span.shrink_to_hi())
2304             }
2305         } else {
2306             let attrs = self.parse_outer_attributes()?; // For recovery.
2307             let block = if self.check(&token::OpenDelim(Delimiter::Brace)) {
2308                 self.parse_block()?
2309             } else {
2310                 if let Some(block) = recover_block_from_condition(self) {
2311                     block
2312                 } else {
2313                     self.error_on_extra_if(&cond)?;
2314                     // Parse block, which will always fail, but we can add a nice note to the error
2315                     self.parse_block().map_err(|mut err| {
2316                         err.span_note(
2317                             cond_span,
2318                             "the `if` expression is missing a block after this condition",
2319                         );
2320                         err
2321                     })?
2322                 }
2323             };
2324             self.error_on_if_block_attrs(lo, false, block.span, attrs);
2325             block
2326         };
2327         let els = if self.eat_keyword(kw::Else) { Some(self.parse_else_expr()?) } else { None };
2328         Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els)))
2329     }
2330
2331     /// Parses the condition of a `if` or `while` expression.
2332     fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
2333         let cond =
2334             self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL | Restrictions::ALLOW_LET, None)?;
2335
2336         if let ExprKind::Let(..) = cond.kind {
2337             // Remove the last feature gating of a `let` expression since it's stable.
2338             self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2339         }
2340
2341         Ok(cond)
2342     }
2343
2344     /// Parses a `let $pat = $expr` pseudo-expression.
2345     fn parse_let_expr(&mut self) -> PResult<'a, P<Expr>> {
2346         // This is a *approximate* heuristic that detects if `let` chains are
2347         // being parsed in the right position. It's approximate because it
2348         // doesn't deny all invalid `let` expressions, just completely wrong usages.
2349         let not_in_chain = !matches!(
2350             self.prev_token.kind,
2351             TokenKind::AndAnd | TokenKind::Ident(kw::If, _) | TokenKind::Ident(kw::While, _)
2352         );
2353         if !self.restrictions.contains(Restrictions::ALLOW_LET) || not_in_chain {
2354             self.sess.emit_err(ExpectedExpressionFoundLet { span: self.token.span });
2355         }
2356
2357         self.bump(); // Eat `let` token
2358         let lo = self.prev_token.span;
2359         let pat = self.parse_pat_allow_top_alt(
2360             None,
2361             RecoverComma::Yes,
2362             RecoverColon::Yes,
2363             CommaRecoveryMode::LikelyTuple,
2364         )?;
2365         if self.token == token::EqEq {
2366             self.sess.emit_err(ExpectedEqForLetExpr {
2367                 span: self.token.span,
2368                 sugg_span: self.token.span,
2369             });
2370             self.bump();
2371         } else {
2372             self.expect(&token::Eq)?;
2373         }
2374         let expr = self.with_res(self.restrictions | Restrictions::NO_STRUCT_LITERAL, |this| {
2375             this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
2376         })?;
2377         let span = lo.to(expr.span);
2378         self.sess.gated_spans.gate(sym::let_chains, span);
2379         Ok(self.mk_expr(span, ExprKind::Let(pat, expr, span)))
2380     }
2381
2382     /// Parses an `else { ... }` expression (`else` token already eaten).
2383     fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
2384         let else_span = self.prev_token.span; // `else`
2385         let attrs = self.parse_outer_attributes()?; // For recovery.
2386         let expr = if self.eat_keyword(kw::If) {
2387             self.parse_if_expr()?
2388         } else if self.check(&TokenKind::OpenDelim(Delimiter::Brace)) {
2389             self.parse_simple_block()?
2390         } else {
2391             let snapshot = self.create_snapshot_for_diagnostic();
2392             let first_tok = super::token_descr(&self.token);
2393             let first_tok_span = self.token.span;
2394             match self.parse_expr() {
2395                 Ok(cond)
2396                 // If it's not a free-standing expression, and is followed by a block,
2397                 // then it's very likely the condition to an `else if`.
2398                     if self.check(&TokenKind::OpenDelim(Delimiter::Brace))
2399                         && classify::expr_requires_semi_to_be_stmt(&cond) =>
2400                 {
2401                     self.sess.emit_err(ExpectedElseBlock {
2402                         first_tok_span,
2403                         first_tok,
2404                         else_span,
2405                         condition_start: cond.span.shrink_to_lo(),
2406                     });
2407                     self.parse_if_after_cond(cond.span.shrink_to_lo(), cond)?
2408                 }
2409                 Err(e) => {
2410                     e.cancel();
2411                     self.restore_snapshot(snapshot);
2412                     self.parse_simple_block()?
2413                 },
2414                 Ok(_) => {
2415                     self.restore_snapshot(snapshot);
2416                     self.parse_simple_block()?
2417                 },
2418             }
2419         };
2420         self.error_on_if_block_attrs(else_span, true, expr.span, attrs);
2421         Ok(expr)
2422     }
2423
2424     fn error_on_if_block_attrs(
2425         &self,
2426         ctx_span: Span,
2427         is_ctx_else: bool,
2428         branch_span: Span,
2429         attrs: AttrWrapper,
2430     ) {
2431         if attrs.is_empty() {
2432             return;
2433         }
2434
2435         let attrs: &[ast::Attribute] = &attrs.take_for_recovery(self.sess);
2436         let (attributes, last) = match attrs {
2437             [] => return,
2438             [x0 @ xn] | [x0, .., xn] => (x0.span.to(xn.span), xn.span),
2439         };
2440         let ctx = if is_ctx_else { "else" } else { "if" };
2441         self.sess.emit_err(OuterAttributeNotAllowedOnIfElse {
2442             last,
2443             branch_span,
2444             ctx_span,
2445             ctx: ctx.to_string(),
2446             attributes,
2447         });
2448     }
2449
2450     fn error_on_extra_if(&mut self, cond: &P<Expr>) -> PResult<'a, ()> {
2451         if let ExprKind::Binary(Spanned { span: binop_span, node: binop}, _, right) = &cond.kind &&
2452             let BinOpKind::And = binop &&
2453             let ExprKind::If(cond, ..) = &right.kind {
2454                     Err(self.sess.create_err(UnexpectedIfWithIf(binop_span.shrink_to_hi().to(cond.span.shrink_to_lo()))))
2455             } else {
2456                 Ok(())
2457             }
2458     }
2459
2460     /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
2461     fn parse_for_expr(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, P<Expr>> {
2462         // Record whether we are about to parse `for (`.
2463         // This is used below for recovery in case of `for ( $stuff ) $block`
2464         // in which case we will suggest `for $stuff $block`.
2465         let begin_paren = match self.token.kind {
2466             token::OpenDelim(Delimiter::Parenthesis) => Some(self.token.span),
2467             _ => None,
2468         };
2469
2470         let pat = self.parse_pat_allow_top_alt(
2471             None,
2472             RecoverComma::Yes,
2473             RecoverColon::Yes,
2474             CommaRecoveryMode::LikelyTuple,
2475         )?;
2476         if !self.eat_keyword(kw::In) {
2477             self.error_missing_in_for_loop();
2478         }
2479         self.check_for_for_in_in_typo(self.prev_token.span);
2480         let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
2481
2482         let pat = self.recover_parens_around_for_head(pat, begin_paren);
2483
2484         let (attrs, loop_block) = self.parse_inner_attrs_and_block()?;
2485
2486         let kind = ExprKind::ForLoop(pat, expr, loop_block, opt_label);
2487         Ok(self.mk_expr_with_attrs(lo.to(self.prev_token.span), kind, attrs))
2488     }
2489
2490     fn error_missing_in_for_loop(&mut self) {
2491         let (span, sub): (_, fn(_) -> _) = if self.token.is_ident_named(sym::of) {
2492             // Possibly using JS syntax (#75311).
2493             let span = self.token.span;
2494             self.bump();
2495             (span, MissingInInForLoopSub::InNotOf)
2496         } else {
2497             (self.prev_token.span.between(self.token.span), MissingInInForLoopSub::AddIn)
2498         };
2499
2500         self.sess.emit_err(MissingInInForLoop { span, sub: sub(span) });
2501     }
2502
2503     /// Parses a `while` or `while let` expression (`while` token already eaten).
2504     fn parse_while_expr(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, P<Expr>> {
2505         let cond = self.parse_cond_expr().map_err(|mut err| {
2506             err.span_label(lo, "while parsing the condition of this `while` expression");
2507             err
2508         })?;
2509         let (attrs, body) = self.parse_inner_attrs_and_block().map_err(|mut err| {
2510             err.span_label(lo, "while parsing the body of this `while` expression");
2511             err.span_label(cond.span, "this `while` condition successfully parsed");
2512             err
2513         })?;
2514         Ok(self.mk_expr_with_attrs(
2515             lo.to(self.prev_token.span),
2516             ExprKind::While(cond, body, opt_label),
2517             attrs,
2518         ))
2519     }
2520
2521     /// Parses `loop { ... }` (`loop` token already eaten).
2522     fn parse_loop_expr(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, P<Expr>> {
2523         let loop_span = self.prev_token.span;
2524         let (attrs, body) = self.parse_inner_attrs_and_block()?;
2525         Ok(self.mk_expr_with_attrs(
2526             lo.to(self.prev_token.span),
2527             ExprKind::Loop(body, opt_label, loop_span),
2528             attrs,
2529         ))
2530     }
2531
2532     pub(crate) fn eat_label(&mut self) -> Option<Label> {
2533         self.token.lifetime().map(|ident| {
2534             self.bump();
2535             Label { ident }
2536         })
2537     }
2538
2539     /// Parses a `match ... { ... }` expression (`match` token already eaten).
2540     fn parse_match_expr(&mut self) -> PResult<'a, P<Expr>> {
2541         let match_span = self.prev_token.span;
2542         let lo = self.prev_token.span;
2543         let scrutinee = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
2544         if let Err(mut e) = self.expect(&token::OpenDelim(Delimiter::Brace)) {
2545             if self.token == token::Semi {
2546                 e.span_suggestion_short(
2547                     match_span,
2548                     "try removing this `match`",
2549                     "",
2550                     Applicability::MaybeIncorrect, // speculative
2551                 );
2552             }
2553             if self.maybe_recover_unexpected_block_label() {
2554                 e.cancel();
2555                 self.bump();
2556             } else {
2557                 return Err(e);
2558             }
2559         }
2560         let attrs = self.parse_inner_attributes()?;
2561
2562         let mut arms: Vec<Arm> = Vec::new();
2563         while self.token != token::CloseDelim(Delimiter::Brace) {
2564             match self.parse_arm() {
2565                 Ok(arm) => arms.push(arm),
2566                 Err(mut e) => {
2567                     // Recover by skipping to the end of the block.
2568                     e.emit();
2569                     self.recover_stmt();
2570                     let span = lo.to(self.token.span);
2571                     if self.token == token::CloseDelim(Delimiter::Brace) {
2572                         self.bump();
2573                     }
2574                     return Ok(self.mk_expr_with_attrs(
2575                         span,
2576                         ExprKind::Match(scrutinee, arms),
2577                         attrs,
2578                     ));
2579                 }
2580             }
2581         }
2582         let hi = self.token.span;
2583         self.bump();
2584         Ok(self.mk_expr_with_attrs(lo.to(hi), ExprKind::Match(scrutinee, arms), attrs))
2585     }
2586
2587     /// Attempt to recover from match arm body with statements and no surrounding braces.
2588     fn parse_arm_body_missing_braces(
2589         &mut self,
2590         first_expr: &P<Expr>,
2591         arrow_span: Span,
2592     ) -> Option<P<Expr>> {
2593         if self.token.kind != token::Semi {
2594             return None;
2595         }
2596         let start_snapshot = self.create_snapshot_for_diagnostic();
2597         let semi_sp = self.token.span;
2598         self.bump(); // `;`
2599         let mut stmts =
2600             vec![self.mk_stmt(first_expr.span, ast::StmtKind::Expr(first_expr.clone()))];
2601         let err = |this: &Parser<'_>, stmts: Vec<ast::Stmt>| {
2602             let span = stmts[0].span.to(stmts[stmts.len() - 1].span);
2603
2604             this.sess.emit_err(MatchArmBodyWithoutBraces {
2605                 statements: span,
2606                 arrow: arrow_span,
2607                 num_statements: stmts.len(),
2608                 sub: if stmts.len() > 1 {
2609                     MatchArmBodyWithoutBracesSugg::AddBraces {
2610                         left: span.shrink_to_lo(),
2611                         right: span.shrink_to_hi(),
2612                     }
2613                 } else {
2614                     MatchArmBodyWithoutBracesSugg::UseComma { semicolon: semi_sp }
2615                 },
2616             });
2617             this.mk_expr_err(span)
2618         };
2619         // We might have either a `,` -> `;` typo, or a block without braces. We need
2620         // a more subtle parsing strategy.
2621         loop {
2622             if self.token.kind == token::CloseDelim(Delimiter::Brace) {
2623                 // We have reached the closing brace of the `match` expression.
2624                 return Some(err(self, stmts));
2625             }
2626             if self.token.kind == token::Comma {
2627                 self.restore_snapshot(start_snapshot);
2628                 return None;
2629             }
2630             let pre_pat_snapshot = self.create_snapshot_for_diagnostic();
2631             match self.parse_pat_no_top_alt(None) {
2632                 Ok(_pat) => {
2633                     if self.token.kind == token::FatArrow {
2634                         // Reached arm end.
2635                         self.restore_snapshot(pre_pat_snapshot);
2636                         return Some(err(self, stmts));
2637                     }
2638                 }
2639                 Err(err) => {
2640                     err.cancel();
2641                 }
2642             }
2643
2644             self.restore_snapshot(pre_pat_snapshot);
2645             match self.parse_stmt_without_recovery(true, ForceCollect::No) {
2646                 // Consume statements for as long as possible.
2647                 Ok(Some(stmt)) => {
2648                     stmts.push(stmt);
2649                 }
2650                 Ok(None) => {
2651                     self.restore_snapshot(start_snapshot);
2652                     break;
2653                 }
2654                 // We couldn't parse either yet another statement missing it's
2655                 // enclosing block nor the next arm's pattern or closing brace.
2656                 Err(stmt_err) => {
2657                     stmt_err.cancel();
2658                     self.restore_snapshot(start_snapshot);
2659                     break;
2660                 }
2661             }
2662         }
2663         None
2664     }
2665
2666     pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
2667         // Used to check the `let_chains` and `if_let_guard` features mostly by scanning
2668         // `&&` tokens.
2669         fn check_let_expr(expr: &Expr) -> (bool, bool) {
2670             match &expr.kind {
2671                 ExprKind::Binary(BinOp { node: BinOpKind::And, .. }, lhs, rhs) => {
2672                     let lhs_rslt = check_let_expr(lhs);
2673                     let rhs_rslt = check_let_expr(rhs);
2674                     (lhs_rslt.0 || rhs_rslt.0, false)
2675                 }
2676                 ExprKind::Let(..) => (true, true),
2677                 _ => (false, true),
2678             }
2679         }
2680         let attrs = self.parse_outer_attributes()?;
2681         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2682             let lo = this.token.span;
2683             let pat = this.parse_pat_allow_top_alt(
2684                 None,
2685                 RecoverComma::Yes,
2686                 RecoverColon::Yes,
2687                 CommaRecoveryMode::EitherTupleOrPipe,
2688             )?;
2689             let guard = if this.eat_keyword(kw::If) {
2690                 let if_span = this.prev_token.span;
2691                 let cond = this.parse_expr_res(Restrictions::ALLOW_LET, None)?;
2692                 let (has_let_expr, does_not_have_bin_op) = check_let_expr(&cond);
2693                 if has_let_expr {
2694                     if does_not_have_bin_op {
2695                         // Remove the last feature gating of a `let` expression since it's stable.
2696                         this.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2697                     }
2698                     let span = if_span.to(cond.span);
2699                     this.sess.gated_spans.gate(sym::if_let_guard, span);
2700                 }
2701                 Some(cond)
2702             } else {
2703                 None
2704             };
2705             let arrow_span = this.token.span;
2706             if let Err(mut err) = this.expect(&token::FatArrow) {
2707                 // We might have a `=>` -> `=` or `->` typo (issue #89396).
2708                 if TokenKind::FatArrow
2709                     .similar_tokens()
2710                     .map_or(false, |similar_tokens| similar_tokens.contains(&this.token.kind))
2711                 {
2712                     err.span_suggestion(
2713                         this.token.span,
2714                         "try using a fat arrow here",
2715                         "=>",
2716                         Applicability::MaybeIncorrect,
2717                     );
2718                     err.emit();
2719                     this.bump();
2720                 } else {
2721                     return Err(err);
2722                 }
2723             }
2724             let arm_start_span = this.token.span;
2725
2726             let expr = this.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| {
2727                 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2728                 err
2729             })?;
2730
2731             let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
2732                 && this.token != token::CloseDelim(Delimiter::Brace);
2733
2734             let hi = this.prev_token.span;
2735
2736             if require_comma {
2737                 let sm = this.sess.source_map();
2738                 if let Some(body) = this.parse_arm_body_missing_braces(&expr, arrow_span) {
2739                     let span = body.span;
2740                     return Ok((
2741                         ast::Arm {
2742                             attrs,
2743                             pat,
2744                             guard,
2745                             body,
2746                             span,
2747                             id: DUMMY_NODE_ID,
2748                             is_placeholder: false,
2749                         },
2750                         TrailingToken::None,
2751                     ));
2752                 }
2753                 this.expect_one_of(&[token::Comma], &[token::CloseDelim(Delimiter::Brace)])
2754                     .or_else(|mut err| {
2755                         if this.token == token::FatArrow {
2756                             if let Ok(expr_lines) = sm.span_to_lines(expr.span)
2757                             && let Ok(arm_start_lines) = sm.span_to_lines(arm_start_span)
2758                             && arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
2759                             && expr_lines.lines.len() == 2
2760                             {
2761                                 // We check whether there's any trailing code in the parse span,
2762                                 // if there isn't, we very likely have the following:
2763                                 //
2764                                 // X |     &Y => "y"
2765                                 //   |        --    - missing comma
2766                                 //   |        |
2767                                 //   |        arrow_span
2768                                 // X |     &X => "x"
2769                                 //   |      - ^^ self.token.span
2770                                 //   |      |
2771                                 //   |      parsed until here as `"y" & X`
2772                                 err.span_suggestion_short(
2773                                     arm_start_span.shrink_to_hi(),
2774                                     "missing a comma here to end this `match` arm",
2775                                     ",",
2776                                     Applicability::MachineApplicable,
2777                                 );
2778                                 return Err(err);
2779                             }
2780                         } else {
2781                             // FIXME(compiler-errors): We could also recover `; PAT =>` here
2782
2783                             // Try to parse a following `PAT =>`, if successful
2784                             // then we should recover.
2785                             let mut snapshot = this.create_snapshot_for_diagnostic();
2786                             let pattern_follows = snapshot
2787                                 .parse_pat_allow_top_alt(
2788                                     None,
2789                                     RecoverComma::Yes,
2790                                     RecoverColon::Yes,
2791                                     CommaRecoveryMode::EitherTupleOrPipe,
2792                                 )
2793                                 .map_err(|err| err.cancel())
2794                                 .is_ok();
2795                             if pattern_follows && snapshot.check(&TokenKind::FatArrow) {
2796                                 err.cancel();
2797                                 this.sess.emit_err(MissingCommaAfterMatchArm {
2798                                     span: hi.shrink_to_hi(),
2799                                 });
2800                                 return Ok(true);
2801                             }
2802                         }
2803                         err.span_label(arrow_span, "while parsing the `match` arm starting here");
2804                         Err(err)
2805                     })?;
2806             } else {
2807                 this.eat(&token::Comma);
2808             }
2809
2810             Ok((
2811                 ast::Arm {
2812                     attrs,
2813                     pat,
2814                     guard,
2815                     body: expr,
2816                     span: lo.to(hi),
2817                     id: DUMMY_NODE_ID,
2818                     is_placeholder: false,
2819                 },
2820                 TrailingToken::None,
2821             ))
2822         })
2823     }
2824
2825     /// Parses a `try {...}` expression (`try` token already eaten).
2826     fn parse_try_block(&mut self, span_lo: Span) -> PResult<'a, P<Expr>> {
2827         let (attrs, body) = self.parse_inner_attrs_and_block()?;
2828         if self.eat_keyword(kw::Catch) {
2829             Err(CatchAfterTry { span: self.prev_token.span }
2830                 .into_diagnostic(&self.sess.span_diagnostic))
2831         } else {
2832             let span = span_lo.to(body.span);
2833             self.sess.gated_spans.gate(sym::try_blocks, span);
2834             Ok(self.mk_expr_with_attrs(span, ExprKind::TryBlock(body), attrs))
2835         }
2836     }
2837
2838     fn is_do_catch_block(&self) -> bool {
2839         self.token.is_keyword(kw::Do)
2840             && self.is_keyword_ahead(1, &[kw::Catch])
2841             && self.look_ahead(2, |t| *t == token::OpenDelim(Delimiter::Brace))
2842             && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
2843     }
2844
2845     fn is_do_yeet(&self) -> bool {
2846         self.token.is_keyword(kw::Do) && self.is_keyword_ahead(1, &[kw::Yeet])
2847     }
2848
2849     fn is_try_block(&self) -> bool {
2850         self.token.is_keyword(kw::Try)
2851             && self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Brace))
2852             && self.token.uninterpolated_span().rust_2018()
2853     }
2854
2855     /// Parses an `async move? {...}` expression.
2856     fn parse_async_block(&mut self) -> PResult<'a, P<Expr>> {
2857         let lo = self.token.span;
2858         self.expect_keyword(kw::Async)?;
2859         let capture_clause = self.parse_capture_clause()?;
2860         let (attrs, body) = self.parse_inner_attrs_and_block()?;
2861         let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);
2862         Ok(self.mk_expr_with_attrs(lo.to(self.prev_token.span), kind, attrs))
2863     }
2864
2865     fn is_async_block(&self) -> bool {
2866         self.token.is_keyword(kw::Async)
2867             && ((
2868                 // `async move {`
2869                 self.is_keyword_ahead(1, &[kw::Move])
2870                     && self.look_ahead(2, |t| *t == token::OpenDelim(Delimiter::Brace))
2871             ) || (
2872                 // `async {`
2873                 self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Brace))
2874             ))
2875     }
2876
2877     fn is_certainly_not_a_block(&self) -> bool {
2878         self.look_ahead(1, |t| t.is_ident())
2879             && (
2880                 // `{ ident, ` cannot start a block.
2881                 self.look_ahead(2, |t| t == &token::Comma)
2882                     || self.look_ahead(2, |t| t == &token::Colon)
2883                         && (
2884                             // `{ ident: token, ` cannot start a block.
2885                             self.look_ahead(4, |t| t == &token::Comma) ||
2886                 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
2887                 self.look_ahead(3, |t| !t.can_begin_type())
2888                         )
2889             )
2890     }
2891
2892     fn maybe_parse_struct_expr(
2893         &mut self,
2894         qself: &Option<P<ast::QSelf>>,
2895         path: &ast::Path,
2896     ) -> Option<PResult<'a, P<Expr>>> {
2897         let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2898         if struct_allowed || self.is_certainly_not_a_block() {
2899             if let Err(err) = self.expect(&token::OpenDelim(Delimiter::Brace)) {
2900                 return Some(Err(err));
2901             }
2902             let expr = self.parse_struct_expr(qself.clone(), path.clone(), true);
2903             if let (Ok(expr), false) = (&expr, struct_allowed) {
2904                 // This is a struct literal, but we don't can't accept them here.
2905                 self.sess.emit_err(StructLiteralNotAllowedHere {
2906                     span: expr.span,
2907                     sub: StructLiteralNotAllowedHereSugg {
2908                         left: path.span.shrink_to_lo(),
2909                         right: expr.span.shrink_to_hi(),
2910                     },
2911                 });
2912             }
2913             return Some(expr);
2914         }
2915         None
2916     }
2917
2918     pub(super) fn parse_struct_fields(
2919         &mut self,
2920         pth: ast::Path,
2921         recover: bool,
2922         close_delim: Delimiter,
2923     ) -> PResult<'a, (Vec<ExprField>, ast::StructRest, bool)> {
2924         let mut fields = Vec::new();
2925         let mut base = ast::StructRest::None;
2926         let mut recover_async = false;
2927
2928         let mut async_block_err = |e: &mut Diagnostic, span: Span| {
2929             recover_async = true;
2930             AsyncBlockIn2015 { span }.add_to_diagnostic(e);
2931             HelpUseLatestEdition::new().add_to_diagnostic(e);
2932         };
2933
2934         while self.token != token::CloseDelim(close_delim) {
2935             if self.eat(&token::DotDot) || self.recover_struct_field_dots(close_delim) {
2936                 let exp_span = self.prev_token.span;
2937                 // We permit `.. }` on the left-hand side of a destructuring assignment.
2938                 if self.check(&token::CloseDelim(close_delim)) {
2939                     base = ast::StructRest::Rest(self.prev_token.span.shrink_to_hi());
2940                     break;
2941                 }
2942                 match self.parse_expr() {
2943                     Ok(e) => base = ast::StructRest::Base(e),
2944                     Err(mut e) if recover => {
2945                         e.emit();
2946                         self.recover_stmt();
2947                     }
2948                     Err(e) => return Err(e),
2949                 }
2950                 self.recover_struct_comma_after_dotdot(exp_span);
2951                 break;
2952             }
2953
2954             let recovery_field = self.find_struct_error_after_field_looking_code();
2955             let parsed_field = match self.parse_expr_field() {
2956                 Ok(f) => Some(f),
2957                 Err(mut e) => {
2958                     if pth == kw::Async {
2959                         async_block_err(&mut e, pth.span);
2960                     } else {
2961                         e.span_label(pth.span, "while parsing this struct");
2962                     }
2963                     e.emit();
2964
2965                     // If the next token is a comma, then try to parse
2966                     // what comes next as additional fields, rather than
2967                     // bailing out until next `}`.
2968                     if self.token != token::Comma {
2969                         self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2970                         if self.token != token::Comma {
2971                             break;
2972                         }
2973                     }
2974                     None
2975                 }
2976             };
2977
2978             let is_shorthand = parsed_field.as_ref().map_or(false, |f| f.is_shorthand);
2979             // A shorthand field can be turned into a full field with `:`.
2980             // We should point this out.
2981             self.check_or_expected(!is_shorthand, TokenType::Token(token::Colon));
2982
2983             match self.expect_one_of(&[token::Comma], &[token::CloseDelim(close_delim)]) {
2984                 Ok(_) => {
2985                     if let Some(f) = parsed_field.or(recovery_field) {
2986                         // Only include the field if there's no parse error for the field name.
2987                         fields.push(f);
2988                     }
2989                 }
2990                 Err(mut e) => {
2991                     if pth == kw::Async {
2992                         async_block_err(&mut e, pth.span);
2993                     } else {
2994                         e.span_label(pth.span, "while parsing this struct");
2995                         if let Some(f) = recovery_field {
2996                             fields.push(f);
2997                             e.span_suggestion(
2998                                 self.prev_token.span.shrink_to_hi(),
2999                                 "try adding a comma",
3000                                 ",",
3001                                 Applicability::MachineApplicable,
3002                             );
3003                         } else if is_shorthand
3004                             && (AssocOp::from_token(&self.token).is_some()
3005                                 || matches!(&self.token.kind, token::OpenDelim(_))
3006                                 || self.token.kind == token::Dot)
3007                         {
3008                             // Looks like they tried to write a shorthand, complex expression.
3009                             let ident = parsed_field.expect("is_shorthand implies Some").ident;
3010                             e.span_suggestion(
3011                                 ident.span.shrink_to_lo(),
3012                                 "try naming a field",
3013                                 &format!("{ident}: "),
3014                                 Applicability::HasPlaceholders,
3015                             );
3016                         }
3017                     }
3018                     if !recover {
3019                         return Err(e);
3020                     }
3021                     e.emit();
3022                     self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
3023                     self.eat(&token::Comma);
3024                 }
3025             }
3026         }
3027         Ok((fields, base, recover_async))
3028     }
3029
3030     /// Precondition: already parsed the '{'.
3031     pub(super) fn parse_struct_expr(
3032         &mut self,
3033         qself: Option<P<ast::QSelf>>,
3034         pth: ast::Path,
3035         recover: bool,
3036     ) -> PResult<'a, P<Expr>> {
3037         let lo = pth.span;
3038         let (fields, base, recover_async) =
3039             self.parse_struct_fields(pth.clone(), recover, Delimiter::Brace)?;
3040         let span = lo.to(self.token.span);
3041         self.expect(&token::CloseDelim(Delimiter::Brace))?;
3042         let expr = if recover_async {
3043             ExprKind::Err
3044         } else {
3045             ExprKind::Struct(P(ast::StructExpr { qself, path: pth, fields, rest: base }))
3046         };
3047         Ok(self.mk_expr(span, expr))
3048     }
3049
3050     /// Use in case of error after field-looking code: `S { foo: () with a }`.
3051     fn find_struct_error_after_field_looking_code(&self) -> Option<ExprField> {
3052         match self.token.ident() {
3053             Some((ident, is_raw))
3054                 if (is_raw || !ident.is_reserved())
3055                     && self.look_ahead(1, |t| *t == token::Colon) =>
3056             {
3057                 Some(ast::ExprField {
3058                     ident,
3059                     span: self.token.span,
3060                     expr: self.mk_expr_err(self.token.span),
3061                     is_shorthand: false,
3062                     attrs: AttrVec::new(),
3063                     id: DUMMY_NODE_ID,
3064                     is_placeholder: false,
3065                 })
3066             }
3067             _ => None,
3068         }
3069     }
3070
3071     fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
3072         if self.token != token::Comma {
3073             return;
3074         }
3075         self.sess.emit_err(CommaAfterBaseStruct {
3076             span: span.to(self.prev_token.span),
3077             comma: self.token.span,
3078         });
3079         self.recover_stmt();
3080     }
3081
3082     fn recover_struct_field_dots(&mut self, close_delim: Delimiter) -> bool {
3083         if !self.look_ahead(1, |t| *t == token::CloseDelim(close_delim))
3084             && self.eat(&token::DotDotDot)
3085         {
3086             // recover from typo of `...`, suggest `..`
3087             let span = self.prev_token.span;
3088             self.sess.emit_err(MissingDotDot { token_span: span, sugg_span: span });
3089             return true;
3090         }
3091         false
3092     }
3093
3094     /// Converts an ident into 'label and emits an "expected a label, found an identifier" error.
3095     fn recover_ident_into_label(&mut self, ident: Ident) -> Label {
3096         // Convert `label` -> `'label`,
3097         // so that nameres doesn't complain about non-existing label
3098         let label = format!("'{}", ident.name);
3099         let ident = Ident { name: Symbol::intern(&label), span: ident.span };
3100
3101         self.struct_span_err(ident.span, "expected a label, found an identifier")
3102             .span_suggestion(
3103                 ident.span,
3104                 "labels start with a tick",
3105                 label,
3106                 Applicability::MachineApplicable,
3107             )
3108             .emit();
3109
3110         Label { ident }
3111     }
3112
3113     /// Parses `ident (COLON expr)?`.
3114     fn parse_expr_field(&mut self) -> PResult<'a, ExprField> {
3115         let attrs = self.parse_outer_attributes()?;
3116         self.recover_diff_marker();
3117         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
3118             let lo = this.token.span;
3119
3120             // Check if a colon exists one ahead. This means we're parsing a fieldname.
3121             let is_shorthand = !this.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
3122             let (ident, expr) = if is_shorthand {
3123                 // Mimic `x: x` for the `x` field shorthand.
3124                 let ident = this.parse_ident_common(false)?;
3125                 let path = ast::Path::from_ident(ident);
3126                 (ident, this.mk_expr(ident.span, ExprKind::Path(None, path)))
3127             } else {
3128                 let ident = this.parse_field_name()?;
3129                 this.error_on_eq_field_init(ident);
3130                 this.bump(); // `:`
3131                 (ident, this.parse_expr()?)
3132             };
3133
3134             Ok((
3135                 ast::ExprField {
3136                     ident,
3137                     span: lo.to(expr.span),
3138                     expr,
3139                     is_shorthand,
3140                     attrs,
3141                     id: DUMMY_NODE_ID,
3142                     is_placeholder: false,
3143                 },
3144                 TrailingToken::MaybeComma,
3145             ))
3146         })
3147     }
3148
3149     /// Check for `=`. This means the source incorrectly attempts to
3150     /// initialize a field with an eq rather than a colon.
3151     fn error_on_eq_field_init(&self, field_name: Ident) {
3152         if self.token != token::Eq {
3153             return;
3154         }
3155
3156         self.sess.emit_err(EqFieldInit {
3157             span: self.token.span,
3158             eq: field_name.span.shrink_to_hi().to(self.token.span),
3159         });
3160     }
3161
3162     fn err_dotdotdot_syntax(&self, span: Span) {
3163         self.sess.emit_err(DotDotDot { span });
3164     }
3165
3166     fn err_larrow_operator(&self, span: Span) {
3167         self.sess.emit_err(LeftArrowOperator { span });
3168     }
3169
3170     fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
3171         ExprKind::AssignOp(binop, lhs, rhs)
3172     }
3173
3174     fn mk_range(
3175         &mut self,
3176         start: Option<P<Expr>>,
3177         end: Option<P<Expr>>,
3178         limits: RangeLimits,
3179     ) -> ExprKind {
3180         if end.is_none() && limits == RangeLimits::Closed {
3181             self.inclusive_range_with_incorrect_end();
3182             ExprKind::Err
3183         } else {
3184             ExprKind::Range(start, end, limits)
3185         }
3186     }
3187
3188     fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
3189         ExprKind::Unary(unop, expr)
3190     }
3191
3192     fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
3193         ExprKind::Binary(binop, lhs, rhs)
3194     }
3195
3196     fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
3197         ExprKind::Index(expr, idx)
3198     }
3199
3200     fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
3201         ExprKind::Call(f, args)
3202     }
3203
3204     fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> P<Expr> {
3205         let span = lo.to(self.prev_token.span);
3206         let await_expr = self.mk_expr(span, ExprKind::Await(self_arg));
3207         self.recover_from_await_method_call();
3208         await_expr
3209     }
3210
3211     pub(crate) fn mk_expr_with_attrs(&self, span: Span, kind: ExprKind, attrs: AttrVec) -> P<Expr> {
3212         P(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None })
3213     }
3214
3215     pub(crate) fn mk_expr(&self, span: Span, kind: ExprKind) -> P<Expr> {
3216         P(Expr { kind, span, attrs: AttrVec::new(), id: DUMMY_NODE_ID, tokens: None })
3217     }
3218
3219     pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
3220         self.mk_expr(span, ExprKind::Err)
3221     }
3222
3223     /// Create expression span ensuring the span of the parent node
3224     /// is larger than the span of lhs and rhs, including the attributes.
3225     fn mk_expr_sp(&self, lhs: &P<Expr>, lhs_span: Span, rhs_span: Span) -> Span {
3226         lhs.attrs
3227             .iter()
3228             .find(|a| a.style == AttrStyle::Outer)
3229             .map_or(lhs_span, |a| a.span)
3230             .to(rhs_span)
3231     }
3232
3233     fn collect_tokens_for_expr(
3234         &mut self,
3235         attrs: AttrWrapper,
3236         f: impl FnOnce(&mut Self, ast::AttrVec) -> PResult<'a, P<Expr>>,
3237     ) -> PResult<'a, P<Expr>> {
3238         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
3239             let res = f(this, attrs)?;
3240             let trailing = if this.restrictions.contains(Restrictions::STMT_EXPR)
3241                 && this.token.kind == token::Semi
3242             {
3243                 TrailingToken::Semi
3244             } else if this.token.kind == token::Gt {
3245                 TrailingToken::Gt
3246             } else {
3247                 // FIXME - pass this through from the place where we know
3248                 // we need a comma, rather than assuming that `#[attr] expr,`
3249                 // always captures a trailing comma
3250                 TrailingToken::MaybeComma
3251             };
3252             Ok((res, trailing))
3253         })
3254     }
3255 }