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