1 use super::pat::{RecoverComma, PARAM_EXPECTED};
2 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
3 use super::{AttrWrapper, BlockMode, ForceCollect, Parser, PathStyle, Restrictions, TokenType};
4 use super::{SemiColonMode, SeqSep, TokenExpectType, TrailingToken};
5 use crate::maybe_recover_from_interpolated_ty_qpath;
8 use rustc_ast::token::{self, Token, TokenKind};
9 use rustc_ast::tokenstream::Spacing;
10 use rustc_ast::util::classify;
11 use rustc_ast::util::literal::LitError;
12 use rustc_ast::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity};
13 use rustc_ast::{self as ast, AttrStyle, AttrVec, CaptureBy, ExprField, Lit, UnOp, DUMMY_NODE_ID};
14 use rustc_ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty, TyKind};
15 use rustc_ast::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits};
16 use rustc_ast_pretty::pprust;
17 use rustc_errors::{Applicability, DiagnosticBuilder, PResult};
18 use rustc_span::edition::LATEST_STABLE_EDITION;
19 use rustc_span::source_map::{self, Span, Spanned};
20 use rustc_span::symbol::{kw, sym, Ident, Symbol};
21 use rustc_span::{BytePos, Pos};
24 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
25 /// dropped into the token stream, which happens while parsing the result of
26 /// macro expansion). Placement of these is not as complex as I feared it would
27 /// be. The important thing is to make sure that lookahead doesn't balk at
28 /// `token::Interpolated` tokens.
29 macro_rules! maybe_whole_expr {
31 if let token::Interpolated(nt) = &$p.token.kind {
33 token::NtExpr(e) | token::NtLiteral(e) => {
38 token::NtPath(path) => {
39 let path = path.clone();
43 ExprKind::Path(None, path),
47 token::NtBlock(block) => {
48 let block = block.clone();
52 ExprKind::Block(block, None),
63 pub(super) enum LhsExpr {
65 AttributesParsed(AttrWrapper),
66 AlreadyParsed(P<Expr>),
69 impl From<Option<AttrWrapper>> for LhsExpr {
70 /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
71 /// and `None` into `LhsExpr::NotYetParsed`.
73 /// This conversion does not allocate.
74 fn from(o: Option<AttrWrapper>) -> Self {
75 if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed }
79 impl From<P<Expr>> for LhsExpr {
80 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
82 /// This conversion does not allocate.
83 fn from(expr: P<Expr>) -> Self {
84 LhsExpr::AlreadyParsed(expr)
89 /// Parses an expression.
91 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
92 self.parse_expr_res(Restrictions::empty(), None)
95 /// Parses an expression, forcing tokens to be collected
96 pub fn parse_expr_force_collect(&mut self) -> PResult<'a, P<Expr>> {
97 // If we have outer attributes, then the call to `collect_tokens_trailing_token`
98 // will be made for us.
99 if matches!(self.token.kind, TokenKind::Pound | TokenKind::DocComment(..)) {
102 // If we don't have outer attributes, then we need to ensure
103 // that collection happens by using `collect_tokens_no_attrs`.
104 // Expression don't support custom inner attributes, so `parse_expr`
105 // will never try to collect tokens if we don't have outer attributes.
106 self.collect_tokens_no_attrs(|this| this.parse_expr())
110 pub fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> {
111 self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
114 fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P<Expr>> {
115 match self.parse_expr() {
116 Ok(expr) => Ok(expr),
117 Err(mut err) => match self.token.ident() {
118 Some((Ident { name: kw::Underscore, .. }, false))
119 if self.look_ahead(1, |t| t == &token::Comma) =>
121 // Special-case handling of `foo(_, _, _)`
124 Ok(self.mk_expr(self.prev_token.span, ExprKind::Err, AttrVec::new()))
131 /// Parses a sequence of expressions delimited by parentheses.
132 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
133 self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r)
136 /// Parses an expression, subject to the given restrictions.
138 pub(super) fn parse_expr_res(
141 already_parsed_attrs: Option<AttrWrapper>,
142 ) -> PResult<'a, P<Expr>> {
143 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
146 /// Parses an associative expression.
148 /// This parses an expression accounting for associativity and precedence of the operators in
153 already_parsed_attrs: Option<AttrWrapper>,
154 ) -> PResult<'a, P<Expr>> {
155 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
158 /// Parses an associative expression with operators of at least `min_prec` precedence.
159 pub(super) fn parse_assoc_expr_with(
163 ) -> PResult<'a, P<Expr>> {
164 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
167 let attrs = match lhs {
168 LhsExpr::AttributesParsed(attrs) => Some(attrs),
171 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
172 return self.parse_prefix_range_expr(attrs);
174 self.parse_prefix_expr(attrs)?
177 let last_type_ascription_set = self.last_type_ascription.is_some();
179 if !self.should_continue_as_assoc_expr(&lhs) {
180 self.last_type_ascription = None;
184 self.expected_tokens.push(TokenType::Operator);
185 while let Some(op) = self.check_assoc_op() {
186 // Adjust the span for interpolated LHS to point to the `$lhs` token
187 // and not to what it refers to.
188 let lhs_span = match self.prev_token.kind {
189 TokenKind::Interpolated(..) => self.prev_token.span,
193 let cur_op_span = self.token.span;
194 let restrictions = if op.node.is_assign_like() {
195 self.restrictions & Restrictions::NO_STRUCT_LITERAL
199 let prec = op.node.precedence();
203 // Check for deprecated `...` syntax
204 if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq {
205 self.err_dotdotdot_syntax(self.token.span);
208 if self.token == token::LArrow {
209 self.err_larrow_operator(self.token.span);
213 if op.node.is_comparison() {
214 if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
219 if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual)
220 && self.token.kind == token::Eq
221 && self.prev_token.span.hi() == self.token.span.lo()
223 // Look for JS' `===` and `!==` and recover 😇
224 let sp = op.span.to(self.token.span);
225 let sugg = match op.node {
226 AssocOp::Equal => "==",
227 AssocOp::NotEqual => "!=",
230 self.struct_span_err(sp, &format!("invalid comparison operator `{}=`", sugg))
231 .span_suggestion_short(
233 &format!("`{s}=` is not a valid comparison operator, use `{s}`", s = sugg),
235 Applicability::MachineApplicable,
243 if op == AssocOp::As {
244 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
246 } else if op == AssocOp::Colon {
247 lhs = self.parse_assoc_op_ascribe(lhs, lhs_span)?;
249 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
250 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
251 // generalise it to the Fixity::None code.
252 lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?;
256 let fixity = op.fixity();
257 let prec_adjustment = match fixity {
260 // We currently have no non-associative operators that are not handled above by
261 // the special cases. The code is here only for future convenience.
264 let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
265 this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
268 let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span);
281 | AssocOp::ShiftRight
287 | AssocOp::GreaterEqual => {
288 let ast_op = op.to_ast_binop().unwrap();
289 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
290 self.mk_expr(span, binary, AttrVec::new())
293 self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span), AttrVec::new())
295 AssocOp::AssignOp(k) => {
297 token::Plus => BinOpKind::Add,
298 token::Minus => BinOpKind::Sub,
299 token::Star => BinOpKind::Mul,
300 token::Slash => BinOpKind::Div,
301 token::Percent => BinOpKind::Rem,
302 token::Caret => BinOpKind::BitXor,
303 token::And => BinOpKind::BitAnd,
304 token::Or => BinOpKind::BitOr,
305 token::Shl => BinOpKind::Shl,
306 token::Shr => BinOpKind::Shr,
308 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
309 self.mk_expr(span, aopexpr, AttrVec::new())
311 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
312 self.span_bug(span, "AssocOp should have been handled by special case")
316 if let Fixity::None = fixity {
320 if last_type_ascription_set {
321 self.last_type_ascription = None;
326 fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
327 match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) {
328 // Semi-statement forms are odd:
329 // See https://github.com/rust-lang/rust/issues/29071
330 (true, None) => false,
331 (false, _) => true, // Continue parsing the expression.
332 // An exhaustive check is done in the following block, but these are checked first
333 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
334 // want to keep their span info to improve diagnostics in these cases in a later stage.
335 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
336 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
337 (true, Some(AssocOp::Add)) // `{ 42 } + 42
338 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
339 // `if x { a } else { b } && if y { c } else { d }`
340 if !self.look_ahead(1, |t| t.is_used_keyword()) => {
341 // These cases are ambiguous and can't be identified in the parser alone.
342 let sp = self.sess.source_map().start_point(self.token.span);
343 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
346 (true, Some(AssocOp::LAnd)) => {
347 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`. Separated from the
348 // above due to #74233.
349 // These cases are ambiguous and can't be identified in the parser alone.
350 let sp = self.sess.source_map().start_point(self.token.span);
351 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
354 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => false,
356 self.error_found_expr_would_be_stmt(lhs);
362 /// We've found an expression that would be parsed as a statement,
363 /// but the next token implies this should be parsed as an expression.
364 /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
365 fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
366 let mut err = self.struct_span_err(
368 &format!("expected expression, found `{}`", pprust::token_to_string(&self.token),),
370 err.span_label(self.token.span, "expected expression");
371 self.sess.expr_parentheses_needed(&mut err, lhs.span, Some(pprust::expr_to_string(&lhs)));
375 /// Possibly translate the current token to an associative operator.
376 /// The method does not advance the current token.
378 /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
379 fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
380 let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
381 // When parsing const expressions, stop parsing when encountering `>`.
386 | AssocOp::GreaterEqual
387 | AssocOp::AssignOp(token::BinOpToken::Shr),
390 ) if self.restrictions.contains(Restrictions::CONST_EXPR) => {
393 (Some(op), _) => (op, self.token.span),
394 (None, Some((Ident { name: sym::and, span }, false))) => {
395 self.error_bad_logical_op("and", "&&", "conjunction");
396 (AssocOp::LAnd, span)
398 (None, Some((Ident { name: sym::or, span }, false))) => {
399 self.error_bad_logical_op("or", "||", "disjunction");
404 Some(source_map::respan(span, op))
407 /// Error on `and` and `or` suggesting `&&` and `||` respectively.
408 fn error_bad_logical_op(&self, bad: &str, good: &str, english: &str) {
409 self.struct_span_err(self.token.span, &format!("`{}` is not a logical operator", bad))
410 .span_suggestion_short(
412 &format!("use `{}` to perform logical {}", good, english),
414 Applicability::MachineApplicable,
416 .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators")
420 /// Checks if this expression is a successfully parsed statement.
421 fn expr_is_complete(&self, e: &Expr) -> bool {
422 self.restrictions.contains(Restrictions::STMT_EXPR)
423 && !classify::expr_requires_semi_to_be_stmt(e)
426 /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
427 /// The other two variants are handled in `parse_prefix_range_expr` below.
434 ) -> PResult<'a, P<Expr>> {
435 let rhs = if self.is_at_start_of_range_notation_rhs() {
436 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
440 let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
441 let span = self.mk_expr_sp(&lhs, lhs.span, rhs_span);
443 if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed };
444 Ok(self.mk_expr(span, self.mk_range(Some(lhs), rhs, limits), AttrVec::new()))
447 fn is_at_start_of_range_notation_rhs(&self) -> bool {
448 if self.token.can_begin_expr() {
449 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
450 if self.token == token::OpenDelim(token::Brace) {
451 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
459 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
460 fn parse_prefix_range_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
461 // Check for deprecated `...` syntax.
462 if self.token == token::DotDotDot {
463 self.err_dotdotdot_syntax(self.token.span);
467 [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
468 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
472 let limits = match self.token.kind {
473 token::DotDot => RangeLimits::HalfOpen,
474 _ => RangeLimits::Closed,
476 let op = AssocOp::from_token(&self.token);
477 // FIXME: `parse_prefix_range_expr` is called when the current
478 // token is `DotDot`, `DotDotDot`, or `DotDotEq`. If we haven't already
479 // parsed attributes, then trying to parse them here will always fail.
480 // We should figure out how we want attributes on range expressions to work.
481 let attrs = self.parse_or_use_outer_attributes(attrs)?;
482 self.collect_tokens_for_expr(attrs, |this, attrs| {
483 let lo = this.token.span;
485 let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() {
486 // RHS must be parsed with more associativity than the dots.
487 this.parse_assoc_expr_with(op.unwrap().precedence() + 1, LhsExpr::NotYetParsed)
488 .map(|x| (lo.to(x.span), Some(x)))?
492 Ok(this.mk_expr(span, this.mk_range(None, opt_end, limits), attrs.into()))
496 /// Parses a prefix-unary-operator expr.
497 fn parse_prefix_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
498 let attrs = self.parse_or_use_outer_attributes(attrs)?;
499 let lo = self.token.span;
501 macro_rules! make_it {
502 ($this:ident, $attrs:expr, |this, _| $body:expr) => {
503 $this.collect_tokens_for_expr($attrs, |$this, attrs| {
504 let (hi, ex) = $body?;
505 Ok($this.mk_expr(lo.to(hi), ex, attrs.into()))
512 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
513 match this.token.uninterpolate().kind {
514 token::Not => make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Not)), // `!expr`
515 token::Tilde => make_it!(this, attrs, |this, _| this.recover_tilde_expr(lo)), // `~expr`
516 token::BinOp(token::Minus) => {
517 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Neg))
519 token::BinOp(token::Star) => {
520 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Deref))
522 token::BinOp(token::And) | token::AndAnd => {
523 make_it!(this, attrs, |this, _| this.parse_borrow_expr(lo))
525 token::Ident(..) if this.token.is_keyword(kw::Box) => {
526 make_it!(this, attrs, |this, _| this.parse_box_expr(lo))
528 token::Ident(..) if this.is_mistaken_not_ident_negation() => {
529 make_it!(this, attrs, |this, _| this.recover_not_expr(lo))
531 _ => return this.parse_dot_or_call_expr(Some(attrs)),
535 fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P<Expr>)> {
537 let expr = self.parse_prefix_expr(None);
538 let (span, expr) = self.interpolated_or_expr_span(expr)?;
539 Ok((lo.to(span), expr))
542 fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
543 let (span, expr) = self.parse_prefix_expr_common(lo)?;
544 Ok((span, self.mk_unary(op, expr)))
547 // Recover on `!` suggesting for bitwise negation instead.
548 fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
549 self.struct_span_err(lo, "`~` cannot be used as a unary operator")
550 .span_suggestion_short(
552 "use `!` to perform bitwise not",
554 Applicability::MachineApplicable,
558 self.parse_unary_expr(lo, UnOp::Not)
561 /// Parse `box expr`.
562 fn parse_box_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
563 let (span, expr) = self.parse_prefix_expr_common(lo)?;
564 self.sess.gated_spans.gate(sym::box_syntax, span);
565 Ok((span, ExprKind::Box(expr)))
568 fn is_mistaken_not_ident_negation(&self) -> bool {
569 let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
570 // These tokens can start an expression after `!`, but
571 // can't continue an expression after an ident
572 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
573 token::Literal(..) | token::Pound => true,
574 _ => t.is_whole_expr(),
576 self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
579 /// Recover on `not expr` in favor of `!expr`.
580 fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
582 let not_token = self.look_ahead(1, |t| t.clone());
583 self.struct_span_err(
585 &format!("unexpected {} after identifier", super::token_descr(¬_token)),
587 .span_suggestion_short(
588 // Span the `not` plus trailing whitespace to avoid
589 // trailing whitespace after the `!` in our suggestion
590 self.sess.source_map().span_until_non_whitespace(lo.to(not_token.span)),
591 "use `!` to perform logical negation",
593 Applicability::MachineApplicable,
598 self.parse_unary_expr(lo, UnOp::Not)
601 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
602 fn interpolated_or_expr_span(
604 expr: PResult<'a, P<Expr>>,
605 ) -> PResult<'a, (Span, P<Expr>)> {
608 match self.prev_token.kind {
609 TokenKind::Interpolated(..) => self.prev_token.span,
617 fn parse_assoc_op_cast(
621 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind,
622 ) -> PResult<'a, P<Expr>> {
623 let mk_expr = |this: &mut Self, lhs: P<Expr>, rhs: P<Ty>| {
625 this.mk_expr_sp(&lhs, lhs_span, rhs.span),
631 // Save the state of the parser before parsing type normally, in case there is a
632 // LessThan comparison after this cast.
633 let parser_snapshot_before_type = self.clone();
634 let cast_expr = match self.parse_ty_no_plus() {
635 Ok(rhs) => mk_expr(self, lhs, rhs),
636 Err(mut type_err) => {
637 // Rewind to before attempting to parse the type with generics, to recover
638 // from situations like `x as usize < y` in which we first tried to parse
639 // `usize < y` as a type with generic arguments.
640 let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
642 // Check for typo of `'a: loop { break 'a }` with a missing `'`.
643 match (&lhs.kind, &self.token.kind) {
646 ExprKind::Path(None, ast::Path { segments, .. }),
647 TokenKind::Ident(kw::For | kw::Loop | kw::While, false),
648 ) if segments.len() == 1 => {
649 let snapshot = self.clone();
651 ident: Ident::from_str_and_span(
652 &format!("'{}", segments[0].ident),
653 segments[0].ident.span,
656 match self.parse_labeled_expr(label, AttrVec::new(), false) {
659 self.struct_span_err(label.ident.span, "malformed loop label")
662 "use the correct loop label format",
663 label.ident.to_string(),
664 Applicability::MachineApplicable,
678 match self.parse_path(PathStyle::Expr) {
680 let (op_noun, op_verb) = match self.token.kind {
681 token::Lt => ("comparison", "comparing"),
682 token::BinOp(token::Shl) => ("shift", "shifting"),
684 // We can end up here even without `<` being the next token, for
685 // example because `parse_ty_no_plus` returns `Err` on keywords,
686 // but `parse_path` returns `Ok` on them due to error recovery.
687 // Return original error and parser state.
688 *self = parser_snapshot_after_type;
689 return Err(type_err);
693 // Successfully parsed the type path leaving a `<` yet to parse.
696 // Report non-fatal diagnostics, keep `x as usize` as an expression
697 // in AST and continue parsing.
699 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
700 pprust::path_to_string(&path),
703 let span_after_type = parser_snapshot_after_type.token.span;
705 mk_expr(self, lhs, self.mk_ty(path.span, TyKind::Path(None, path)));
708 .span_to_snippet(expr.span)
709 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
711 self.struct_span_err(self.token.span, &msg)
713 self.look_ahead(1, |t| t.span).to(span_after_type),
714 "interpreted as generic arguments",
716 .span_label(self.token.span, format!("not interpreted as {}", op_noun))
719 &format!("try {} the cast value", op_verb),
720 format!("({})", expr_str),
721 Applicability::MachineApplicable,
727 Err(mut path_err) => {
728 // Couldn't parse as a path, return original error and parser state.
730 *self = parser_snapshot_after_type;
731 return Err(type_err);
737 self.parse_and_disallow_postfix_after_cast(cast_expr)
740 /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
741 /// then emits an error and returns the newly parsed tree.
742 /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
743 fn parse_and_disallow_postfix_after_cast(
746 ) -> PResult<'a, P<Expr>> {
747 // Save the memory location of expr before parsing any following postfix operators.
748 // This will be compared with the memory location of the output expression.
749 // If they different we can assume we parsed another expression because the existing expression is not reallocated.
750 let addr_before = &*cast_expr as *const _ as usize;
751 let span = cast_expr.span;
752 let with_postfix = self.parse_dot_or_call_expr_with_(cast_expr, span)?;
753 let changed = addr_before != &*with_postfix as *const _ as usize;
755 // Check if an illegal postfix operator has been added after the cast.
756 // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator.
757 if !matches!(with_postfix.kind, ExprKind::Cast(_, _) | ExprKind::Type(_, _)) || changed {
759 "casts cannot be followed by {}",
760 match with_postfix.kind {
761 ExprKind::Index(_, _) => "indexing",
762 ExprKind::Try(_) => "?",
763 ExprKind::Field(_, _) => "a field access",
764 ExprKind::MethodCall(_, _, _) => "a method call",
765 ExprKind::Call(_, _) => "a function call",
766 ExprKind::Await(_) => "`.await`",
767 ExprKind::Err => return Ok(with_postfix),
768 _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"),
771 let mut err = self.struct_span_err(span, &msg);
772 // If type ascription is "likely an error", the user will already be getting a useful
773 // help message, and doesn't need a second.
774 if self.last_type_ascription.map_or(false, |last_ascription| last_ascription.1) {
775 self.maybe_annotate_with_ascription(&mut err, false);
777 let suggestions = vec![
778 (span.shrink_to_lo(), "(".to_string()),
779 (span.shrink_to_hi(), ")".to_string()),
781 err.multipart_suggestion(
782 "try surrounding the expression in parentheses",
784 Applicability::MachineApplicable,
792 fn parse_assoc_op_ascribe(&mut self, lhs: P<Expr>, lhs_span: Span) -> PResult<'a, P<Expr>> {
793 let maybe_path = self.could_ascription_be_path(&lhs.kind);
794 self.last_type_ascription = Some((self.prev_token.span, maybe_path));
795 let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
796 self.sess.gated_spans.gate(sym::type_ascription, lhs.span);
800 /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
801 fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
803 let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
804 let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
805 let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo);
806 let expr = self.parse_prefix_expr(None);
807 let (hi, expr) = self.interpolated_or_expr_span(expr)?;
808 let span = lo.to(hi);
809 if let Some(lt) = lifetime {
810 self.error_remove_borrow_lifetime(span, lt.ident.span);
812 Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
815 fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
816 self.struct_span_err(span, "borrow expressions cannot be annotated with lifetimes")
817 .span_label(lt_span, "annotated with lifetime here")
820 "remove the lifetime annotation",
822 Applicability::MachineApplicable,
827 /// Parse `mut?` or `raw [ const | mut ]`.
828 fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) {
829 if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) {
830 // `raw [ const | mut ]`.
831 let found_raw = self.eat_keyword(kw::Raw);
833 let mutability = self.parse_const_or_mut().unwrap();
834 self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span));
835 (ast::BorrowKind::Raw, mutability)
838 (ast::BorrowKind::Ref, self.parse_mutability())
842 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
843 fn parse_dot_or_call_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
844 let attrs = self.parse_or_use_outer_attributes(attrs)?;
845 self.collect_tokens_for_expr(attrs, |this, attrs| {
846 let base = this.parse_bottom_expr();
847 let (span, base) = this.interpolated_or_expr_span(base)?;
848 this.parse_dot_or_call_expr_with(base, span, attrs)
852 pub(super) fn parse_dot_or_call_expr_with(
856 mut attrs: Vec<ast::Attribute>,
857 ) -> PResult<'a, P<Expr>> {
858 // Stitch the list of outer attributes onto the return value.
859 // A little bit ugly, but the best way given the current code
861 self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| {
862 expr.map(|mut expr| {
863 attrs.extend::<Vec<_>>(expr.attrs.into());
864 expr.attrs = attrs.into();
870 fn parse_dot_or_call_expr_with_(&mut self, mut e: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
872 if self.eat(&token::Question) {
874 e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e), AttrVec::new());
877 if self.eat(&token::Dot) {
879 e = self.parse_dot_suffix_expr(lo, e)?;
882 if self.expr_is_complete(&e) {
885 e = match self.token.kind {
886 token::OpenDelim(token::Paren) => self.parse_fn_call_expr(lo, e),
887 token::OpenDelim(token::Bracket) => self.parse_index_expr(lo, e)?,
893 fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
894 match self.token.uninterpolate().kind {
895 token::Ident(..) => self.parse_dot_suffix(base, lo),
896 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
897 Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix, None))
899 token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => {
900 Ok(self.parse_tuple_field_access_expr_float(lo, base, symbol, suffix))
903 self.error_unexpected_after_dot();
909 fn error_unexpected_after_dot(&self) {
910 // FIXME Could factor this out into non_fatal_unexpected or something.
911 let actual = pprust::token_to_string(&self.token);
912 self.struct_span_err(self.token.span, &format!("unexpected token: `{}`", actual)).emit();
915 // We need an identifier or integer, but the next token is a float.
916 // Break the float into components to extract the identifier or integer.
917 // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
918 // parts unless those parts are processed immediately. `TokenCursor` should either
919 // support pushing "future tokens" (would be also helpful to `break_and_eat`), or
920 // we should break everything including floats into more basic proc-macro style
921 // tokens in the lexer (probably preferable).
922 fn parse_tuple_field_access_expr_float(
927 suffix: Option<Symbol>,
930 enum FloatComponent {
934 use FloatComponent::*;
936 let float_str = float.as_str();
937 let mut components = Vec::new();
938 let mut ident_like = String::new();
939 for c in float_str.chars() {
940 if c == '_' || c.is_ascii_alphanumeric() {
942 } else if matches!(c, '.' | '+' | '-') {
943 if !ident_like.is_empty() {
944 components.push(IdentLike(mem::take(&mut ident_like)));
946 components.push(Punct(c));
948 panic!("unexpected character in a float token: {:?}", c)
951 if !ident_like.is_empty() {
952 components.push(IdentLike(ident_like));
955 // With proc macros the span can refer to anything, the source may be too short,
956 // or too long, or non-ASCII. It only makes sense to break our span into components
957 // if its underlying text is identical to our float literal.
958 let span = self.token.span;
959 let can_take_span_apart =
960 || self.span_to_snippet(span).as_deref() == Ok(float_str).as_deref();
965 self.parse_tuple_field_access_expr(lo, base, Symbol::intern(&i), suffix, None)
968 [IdentLike(i), Punct('.')] => {
969 let (ident_span, dot_span) = if can_take_span_apart() {
970 let (span, ident_len) = (span.data(), BytePos::from_usize(i.len()));
971 let ident_span = span.with_hi(span.lo + ident_len);
972 let dot_span = span.with_lo(span.lo + ident_len);
973 (ident_span, dot_span)
977 assert!(suffix.is_none());
978 let symbol = Symbol::intern(&i);
979 self.token = Token::new(token::Ident(symbol, false), ident_span);
980 let next_token = (Token::new(token::Dot, dot_span), self.token_spacing);
981 self.parse_tuple_field_access_expr(lo, base, symbol, None, Some(next_token))
984 [IdentLike(i1), Punct('.'), IdentLike(i2)] => {
985 let (ident1_span, dot_span, ident2_span) = if can_take_span_apart() {
986 let (span, ident1_len) = (span.data(), BytePos::from_usize(i1.len()));
987 let ident1_span = span.with_hi(span.lo + ident1_len);
989 .with_lo(span.lo + ident1_len)
990 .with_hi(span.lo + ident1_len + BytePos(1));
991 let ident2_span = self.token.span.with_lo(span.lo + ident1_len + BytePos(1));
992 (ident1_span, dot_span, ident2_span)
996 let symbol1 = Symbol::intern(&i1);
997 self.token = Token::new(token::Ident(symbol1, false), ident1_span);
998 // This needs to be `Spacing::Alone` to prevent regressions.
999 // See issue #76399 and PR #76285 for more details
1000 let next_token1 = (Token::new(token::Dot, dot_span), Spacing::Alone);
1002 self.parse_tuple_field_access_expr(lo, base, symbol1, None, Some(next_token1));
1003 let symbol2 = Symbol::intern(&i2);
1004 let next_token2 = Token::new(token::Ident(symbol2, false), ident2_span);
1005 self.bump_with((next_token2, self.token_spacing)); // `.`
1006 self.parse_tuple_field_access_expr(lo, base1, symbol2, suffix, None)
1008 // 1e+ | 1e- (recovered)
1009 [IdentLike(_), Punct('+' | '-')] |
1011 [IdentLike(_), Punct('+' | '-'), IdentLike(_)] |
1013 [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-'), IdentLike(_)] => {
1014 // See the FIXME about `TokenCursor` above.
1015 self.error_unexpected_after_dot();
1018 _ => panic!("unexpected components in a float token: {:?}", components),
1022 fn parse_tuple_field_access_expr(
1027 suffix: Option<Symbol>,
1028 next_token: Option<(Token, Spacing)>,
1031 Some(next_token) => self.bump_with(next_token),
1032 None => self.bump(),
1034 let span = self.prev_token.span;
1035 let field = ExprKind::Field(base, Ident::new(field, span));
1036 self.expect_no_suffix(span, "a tuple index", suffix);
1037 self.mk_expr(lo.to(span), field, AttrVec::new())
1040 /// Parse a function call expression, `expr(...)`.
1041 fn parse_fn_call_expr(&mut self, lo: Span, fun: P<Expr>) -> P<Expr> {
1042 let seq = self.parse_paren_expr_seq().map(|args| {
1043 self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args), AttrVec::new())
1045 self.recover_seq_parse_error(token::Paren, lo, seq)
1048 /// Parse an indexing expression `expr[...]`.
1049 fn parse_index_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
1051 let index = self.parse_expr()?;
1052 self.expect(&token::CloseDelim(token::Bracket))?;
1053 Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_index(base, index), AttrVec::new()))
1056 /// Assuming we have just parsed `.`, continue parsing into an expression.
1057 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
1058 if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) {
1059 return Ok(self.mk_await_expr(self_arg, lo));
1062 let fn_span_lo = self.token.span;
1063 let mut segment = self.parse_path_segment(PathStyle::Expr)?;
1064 self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(token::Paren)]);
1065 self.check_turbofish_missing_angle_brackets(&mut segment);
1067 if self.check(&token::OpenDelim(token::Paren)) {
1068 // Method call `expr.f()`
1069 let mut args = self.parse_paren_expr_seq()?;
1070 args.insert(0, self_arg);
1072 let fn_span = fn_span_lo.to(self.prev_token.span);
1073 let span = lo.to(self.prev_token.span);
1074 Ok(self.mk_expr(span, ExprKind::MethodCall(segment, args, fn_span), AttrVec::new()))
1076 // Field access `expr.f`
1077 if let Some(args) = segment.args {
1078 self.struct_span_err(
1080 "field expressions cannot have generic arguments",
1085 let span = lo.to(self.prev_token.span);
1086 Ok(self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), AttrVec::new()))
1090 /// At the bottom (top?) of the precedence hierarchy,
1091 /// Parses things like parenthesized exprs, macros, `return`, etc.
1093 /// N.B., this does not parse outer attributes, and is private because it only works
1094 /// correctly if called from `parse_dot_or_call_expr()`.
1095 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1096 maybe_recover_from_interpolated_ty_qpath!(self, true);
1097 maybe_whole_expr!(self);
1099 // Outer attributes are already parsed and will be
1100 // added to the return value after the fact.
1102 // Therefore, prevent sub-parser from parsing
1103 // attributes by giving them a empty "already-parsed" list.
1104 let attrs = AttrVec::new();
1106 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
1107 let lo = self.token.span;
1108 if let token::Literal(_) = self.token.kind {
1109 // This match arm is a special-case of the `_` match arm below and
1110 // could be removed without changing functionality, but it's faster
1111 // to have it here, especially for programs with large constants.
1112 self.parse_lit_expr(attrs)
1113 } else if self.check(&token::OpenDelim(token::Paren)) {
1114 self.parse_tuple_parens_expr(attrs)
1115 } else if self.check(&token::OpenDelim(token::Brace)) {
1116 self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs)
1117 } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) {
1118 self.parse_closure_expr(attrs)
1119 } else if self.check(&token::OpenDelim(token::Bracket)) {
1120 self.parse_array_or_repeat_expr(attrs)
1121 } else if self.eat_lt() {
1122 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
1123 Ok(self.mk_expr(lo.to(path.span), ExprKind::Path(Some(qself), path), attrs))
1124 } else if self.check_path() {
1125 self.parse_path_start_expr(attrs)
1126 } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
1127 self.parse_closure_expr(attrs)
1128 } else if self.eat_keyword(kw::If) {
1129 self.parse_if_expr(attrs)
1130 } else if self.check_keyword(kw::For) {
1131 if self.choose_generics_over_qpath(1) {
1132 // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery,
1133 // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns.
1134 // When `for <Foo as Bar>::Proj in $expr $block` is wanted,
1135 // you can disambiguate in favor of a pattern with `(...)`.
1136 self.recover_quantified_closure_expr(attrs)
1138 assert!(self.eat_keyword(kw::For));
1139 self.parse_for_expr(None, self.prev_token.span, attrs)
1141 } else if self.eat_keyword(kw::While) {
1142 self.parse_while_expr(None, self.prev_token.span, attrs)
1143 } else if let Some(label) = self.eat_label() {
1144 self.parse_labeled_expr(label, attrs, true)
1145 } else if self.eat_keyword(kw::Loop) {
1146 self.parse_loop_expr(None, self.prev_token.span, attrs)
1147 } else if self.eat_keyword(kw::Continue) {
1148 let kind = ExprKind::Continue(self.eat_label());
1149 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1150 } else if self.eat_keyword(kw::Match) {
1151 let match_sp = self.prev_token.span;
1152 self.parse_match_expr(attrs).map_err(|mut err| {
1153 err.span_label(match_sp, "while parsing this match expression");
1156 } else if self.eat_keyword(kw::Unsafe) {
1157 self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs)
1158 } else if self.check_inline_const(0) {
1159 self.parse_const_block(lo.to(self.token.span))
1160 } else if self.is_do_catch_block() {
1161 self.recover_do_catch(attrs)
1162 } else if self.is_try_block() {
1163 self.expect_keyword(kw::Try)?;
1164 self.parse_try_block(lo, attrs)
1165 } else if self.eat_keyword(kw::Return) {
1166 self.parse_return_expr(attrs)
1167 } else if self.eat_keyword(kw::Break) {
1168 self.parse_break_expr(attrs)
1169 } else if self.eat_keyword(kw::Yield) {
1170 self.parse_yield_expr(attrs)
1171 } else if self.eat_keyword(kw::Let) {
1172 self.parse_let_expr(attrs)
1173 } else if self.eat_keyword(kw::Underscore) {
1174 self.sess.gated_spans.gate(sym::destructuring_assignment, self.prev_token.span);
1175 Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore, attrs))
1176 } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1177 // Don't complain about bare semicolons after unclosed braces
1178 // recovery in order to keep the error count down. Fixing the
1179 // delimiters will possibly also fix the bare semicolon found in
1180 // expression context. For example, silence the following error:
1182 // error: expected expression, found `;`
1186 // | ^ expected expression
1188 Ok(self.mk_expr_err(self.token.span))
1189 } else if self.token.uninterpolated_span().rust_2018() {
1190 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1191 if self.check_keyword(kw::Async) {
1192 if self.is_async_block() {
1193 // Check for `async {` and `async move {`.
1194 self.parse_async_block(attrs)
1196 self.parse_closure_expr(attrs)
1198 } else if self.eat_keyword(kw::Await) {
1199 self.recover_incorrect_await_syntax(lo, self.prev_token.span, attrs)
1201 self.parse_lit_expr(attrs)
1204 self.parse_lit_expr(attrs)
1208 fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1209 let lo = self.token.span;
1210 match self.parse_opt_lit() {
1212 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs);
1213 self.maybe_recover_from_bad_qpath(expr, true)
1215 None => self.try_macro_suggestion(),
1219 fn parse_tuple_parens_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1220 let lo = self.token.span;
1221 self.expect(&token::OpenDelim(token::Paren))?;
1222 let (es, trailing_comma) = match self.parse_seq_to_end(
1223 &token::CloseDelim(token::Paren),
1224 SeqSep::trailing_allowed(token::Comma),
1225 |p| p.parse_expr_catch_underscore(),
1228 Err(err) => return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err))),
1230 let kind = if es.len() == 1 && !trailing_comma {
1231 // `(e)` is parenthesized `e`.
1232 ExprKind::Paren(es.into_iter().next().unwrap())
1234 // `(e,)` is a tuple with only one field, `e`.
1237 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1238 self.maybe_recover_from_bad_qpath(expr, true)
1241 fn parse_array_or_repeat_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1242 let lo = self.token.span;
1245 let close = &token::CloseDelim(token::Bracket);
1246 let kind = if self.eat(close) {
1248 ExprKind::Array(Vec::new())
1251 let first_expr = self.parse_expr()?;
1252 if self.eat(&token::Semi) {
1253 // Repeating array syntax: `[ 0; 512 ]`
1254 let count = self.parse_anon_const_expr()?;
1255 self.expect(close)?;
1256 ExprKind::Repeat(first_expr, count)
1257 } else if self.eat(&token::Comma) {
1258 // Vector with two or more elements.
1259 let sep = SeqSep::trailing_allowed(token::Comma);
1260 let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1261 let mut exprs = vec![first_expr];
1262 exprs.extend(remaining_exprs);
1263 ExprKind::Array(exprs)
1265 // Vector with one element
1266 self.expect(close)?;
1267 ExprKind::Array(vec![first_expr])
1270 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1271 self.maybe_recover_from_bad_qpath(expr, true)
1274 fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1275 let path = self.parse_path(PathStyle::Expr)?;
1278 // `!`, as an operator, is prefix, so we know this isn't that.
1279 let (hi, kind) = if self.eat(&token::Not) {
1280 // MACRO INVOCATION expression
1283 args: self.parse_mac_args()?,
1284 prior_type_ascription: self.last_type_ascription,
1286 (self.prev_token.span, ExprKind::MacCall(mac))
1287 } else if self.check(&token::OpenDelim(token::Brace)) {
1288 if let Some(expr) = self.maybe_parse_struct_expr(&path, &attrs) {
1291 (path.span, ExprKind::Path(None, path))
1294 (path.span, ExprKind::Path(None, path))
1297 let expr = self.mk_expr(lo.to(hi), kind, attrs);
1298 self.maybe_recover_from_bad_qpath(expr, true)
1301 /// Parse `'label: $expr`. The label is already parsed.
1302 fn parse_labeled_expr(
1306 consume_colon: bool,
1307 ) -> PResult<'a, P<Expr>> {
1308 let lo = label.ident.span;
1309 let label = Some(label);
1310 let ate_colon = self.eat(&token::Colon);
1311 let expr = if self.eat_keyword(kw::While) {
1312 self.parse_while_expr(label, lo, attrs)
1313 } else if self.eat_keyword(kw::For) {
1314 self.parse_for_expr(label, lo, attrs)
1315 } else if self.eat_keyword(kw::Loop) {
1316 self.parse_loop_expr(label, lo, attrs)
1317 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1318 self.parse_block_expr(label, lo, BlockCheckMode::Default, attrs)
1320 let msg = "expected `while`, `for`, `loop` or `{` after a label";
1321 self.struct_span_err(self.token.span, msg).span_label(self.token.span, msg).emit();
1322 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1326 if !ate_colon && consume_colon {
1327 self.error_labeled_expr_must_be_followed_by_colon(lo, expr.span);
1333 fn error_labeled_expr_must_be_followed_by_colon(&self, lo: Span, span: Span) {
1334 self.struct_span_err(span, "labeled expression must be followed by `:`")
1335 .span_label(lo, "the label")
1336 .span_suggestion_short(
1338 "add `:` after the label",
1340 Applicability::MachineApplicable,
1342 .note("labels are used before loops and blocks, allowing e.g., `break 'label` to them")
1346 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1347 fn recover_do_catch(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1348 let lo = self.token.span;
1350 self.bump(); // `do`
1351 self.bump(); // `catch`
1353 let span_dc = lo.to(self.prev_token.span);
1354 self.struct_span_err(span_dc, "found removed `do catch` syntax")
1357 "replace with the new syntax",
1359 Applicability::MachineApplicable,
1361 .note("following RFC #2388, the new non-placeholder syntax is `try`")
1364 self.parse_try_block(lo, attrs)
1367 /// Parse an expression if the token can begin one.
1368 fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1369 Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1372 /// Parse `"return" expr?`.
1373 fn parse_return_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1374 let lo = self.prev_token.span;
1375 let kind = ExprKind::Ret(self.parse_expr_opt()?);
1376 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1377 self.maybe_recover_from_bad_qpath(expr, true)
1380 /// Parse `"('label ":")? break expr?`.
1381 fn parse_break_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1382 let lo = self.prev_token.span;
1383 let label = self.eat_label();
1384 let kind = if self.token != token::OpenDelim(token::Brace)
1385 || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1387 self.parse_expr_opt()?
1391 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind), attrs);
1392 self.maybe_recover_from_bad_qpath(expr, true)
1395 /// Parse `"yield" expr?`.
1396 fn parse_yield_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1397 let lo = self.prev_token.span;
1398 let kind = ExprKind::Yield(self.parse_expr_opt()?);
1399 let span = lo.to(self.prev_token.span);
1400 self.sess.gated_spans.gate(sym::generators, span);
1401 let expr = self.mk_expr(span, kind, attrs);
1402 self.maybe_recover_from_bad_qpath(expr, true)
1405 /// Returns a string literal if the next token is a string literal.
1406 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1407 /// and returns `None` if the next token is not literal at all.
1408 pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
1409 match self.parse_opt_lit() {
1410 Some(lit) => match lit.kind {
1411 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1413 symbol: lit.token.symbol,
1414 suffix: lit.token.suffix,
1418 _ => Err(Some(lit)),
1424 pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> {
1425 self.parse_opt_lit().ok_or_else(|| {
1426 let msg = format!("unexpected token: {}", super::token_descr(&self.token));
1427 self.struct_span_err(self.token.span, &msg)
1431 /// Matches `lit = true | false | token_lit`.
1432 /// Returns `None` if the next token is not a literal.
1433 pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
1434 let mut recovered = None;
1435 if self.token == token::Dot {
1436 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1437 // dot would follow an optional literal, so we do this unconditionally.
1438 recovered = self.look_ahead(1, |next_token| {
1439 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1442 if self.token.span.hi() == next_token.span.lo() {
1443 let s = String::from("0.") + &symbol.as_str();
1444 let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1445 return Some(Token::new(kind, self.token.span.to(next_token.span)));
1450 if let Some(token) = &recovered {
1452 self.error_float_lits_must_have_int_part(&token);
1456 let token = recovered.as_ref().unwrap_or(&self.token);
1457 match Lit::from_token(token) {
1462 Err(LitError::NotLiteral) => None,
1464 let span = token.span;
1465 let lit = match token.kind {
1466 token::Literal(lit) => lit,
1467 _ => unreachable!(),
1470 self.report_lit_error(err, lit, span);
1471 // Pack possible quotes and prefixes from the original literal into
1472 // the error literal's symbol so they can be pretty-printed faithfully.
1473 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1474 let symbol = Symbol::intern(&suffixless_lit.to_string());
1475 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1476 Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!()))
1481 fn error_float_lits_must_have_int_part(&self, token: &Token) {
1482 self.struct_span_err(token.span, "float literals must have an integer part")
1485 "must have an integer part",
1486 pprust::token_to_string(token),
1487 Applicability::MachineApplicable,
1492 fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) {
1493 // Checks if `s` looks like i32 or u1234 etc.
1494 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1495 s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
1498 let token::Lit { kind, suffix, .. } = lit;
1500 // `NotLiteral` is not an error by itself, so we don't report
1501 // it and give the parser opportunity to try something else.
1502 LitError::NotLiteral => {}
1503 // `LexerError` *is* an error, but it was already reported
1504 // by lexer, so here we don't report it the second time.
1505 LitError::LexerError => {}
1506 LitError::InvalidSuffix => {
1507 self.expect_no_suffix(
1509 &format!("{} {} literal", kind.article(), kind.descr()),
1513 LitError::InvalidIntSuffix => {
1514 let suf = suffix.expect("suffix error with no suffix").as_str();
1515 if looks_like_width_suffix(&['i', 'u'], &suf) {
1516 // If it looks like a width, try to be helpful.
1517 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
1518 self.struct_span_err(span, &msg)
1519 .help("valid widths are 8, 16, 32, 64 and 128")
1522 let msg = format!("invalid suffix `{}` for number literal", suf);
1523 self.struct_span_err(span, &msg)
1524 .span_label(span, format!("invalid suffix `{}`", suf))
1525 .help("the suffix must be one of the numeric types (`u32`, `isize`, `f32`, etc.)")
1529 LitError::InvalidFloatSuffix => {
1530 let suf = suffix.expect("suffix error with no suffix").as_str();
1531 if looks_like_width_suffix(&['f'], &suf) {
1532 // If it looks like a width, try to be helpful.
1533 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
1534 self.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit();
1536 let msg = format!("invalid suffix `{}` for float literal", suf);
1537 self.struct_span_err(span, &msg)
1538 .span_label(span, format!("invalid suffix `{}`", suf))
1539 .help("valid suffixes are `f32` and `f64`")
1543 LitError::NonDecimalFloat(base) => {
1544 let descr = match base {
1545 16 => "hexadecimal",
1548 _ => unreachable!(),
1550 self.struct_span_err(span, &format!("{} float literal is not supported", descr))
1551 .span_label(span, "not supported")
1554 LitError::IntTooLarge => {
1555 self.struct_span_err(span, "integer literal is too large").emit();
1560 pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) {
1561 if let Some(suf) = suffix {
1562 let mut err = if kind == "a tuple index"
1563 && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf)
1565 // #59553: warn instead of reject out of hand to allow the fix to percolate
1566 // through the ecosystem when people fix their macros
1570 .struct_span_warn(sp, &format!("suffixes on {} are invalid", kind));
1572 "`{}` is *temporarily* accepted on tuple index fields as it was \
1573 incorrectly accepted on stable for a few releases",
1577 "on proc macros, you'll want to use `syn::Index::from` or \
1578 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1579 to tuple field access",
1582 "see issue #60210 <https://github.com/rust-lang/rust/issues/60210> \
1583 for more information",
1587 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1589 err.span_label(sp, format!("invalid suffix `{}`", suf));
1594 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1595 /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
1596 pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1597 maybe_whole_expr!(self);
1599 let lo = self.token.span;
1600 let minus_present = self.eat(&token::BinOp(token::Minus));
1601 let lit = self.parse_lit()?;
1602 let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new());
1606 lo.to(self.prev_token.span),
1607 self.mk_unary(UnOp::Neg, expr),
1615 /// Parses a block or unsafe block.
1616 pub(super) fn parse_block_expr(
1618 opt_label: Option<Label>,
1620 blk_mode: BlockCheckMode,
1622 ) -> PResult<'a, P<Expr>> {
1623 if let Some(label) = opt_label {
1624 self.sess.gated_spans.gate(sym::label_break_value, label.ident.span);
1627 if self.token.is_whole_block() {
1628 self.struct_span_err(self.token.span, "cannot use a `block` macro fragment here")
1629 .span_label(lo.to(self.token.span), "the `block` fragment is within this context")
1633 let (inner_attrs, blk) = self.parse_block_common(lo, blk_mode)?;
1634 attrs.extend(inner_attrs);
1635 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs))
1638 /// Recover on an explicitly quantified closure expression, e.g., `for<'a> |x: &'a u8| *x + 1`.
1639 fn recover_quantified_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1640 let lo = self.token.span;
1641 let _ = self.parse_late_bound_lifetime_defs()?;
1642 let span_for = lo.to(self.prev_token.span);
1643 let closure = self.parse_closure_expr(attrs)?;
1645 self.struct_span_err(span_for, "cannot introduce explicit parameters for a closure")
1646 .span_label(closure.span, "the parameters are attached to this closure")
1649 "remove the parameters",
1651 Applicability::MachineApplicable,
1655 Ok(self.mk_expr_err(lo.to(closure.span)))
1658 /// Parses a closure expression (e.g., `move |args| expr`).
1659 fn parse_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1660 let lo = self.token.span;
1663 if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
1665 let asyncness = if self.token.uninterpolated_span().rust_2018() {
1666 self.parse_asyncness()
1671 let capture_clause = self.parse_capture_clause()?;
1672 let decl = self.parse_fn_block_decl()?;
1673 let decl_hi = self.prev_token.span;
1674 let body = match decl.output {
1675 FnRetTy::Default(_) => {
1676 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
1677 self.parse_expr_res(restrictions, None)?
1680 // If an explicit return type is given, require a block to appear (RFC 968).
1681 let body_lo = self.token.span;
1682 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, AttrVec::new())?
1686 if let Async::Yes { span, .. } = asyncness {
1687 // Feature-gate `async ||` closures.
1688 self.sess.gated_spans.gate(sym::async_closure, span);
1693 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
1698 /// Parses an optional `move` prefix to a closure-like construct.
1699 fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> {
1700 if self.eat_keyword(kw::Move) {
1701 // Check for `move async` and recover
1702 if self.check_keyword(kw::Async) {
1703 let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
1704 Err(self.incorrect_move_async_order_found(move_async_span))
1706 Ok(CaptureBy::Value)
1713 /// Parses the `|arg, arg|` header of a closure.
1714 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
1715 let inputs = if self.eat(&token::OrOr) {
1718 self.expect(&token::BinOp(token::Or))?;
1720 .parse_seq_to_before_tokens(
1721 &[&token::BinOp(token::Or), &token::OrOr],
1722 SeqSep::trailing_allowed(token::Comma),
1723 TokenExpectType::NoExpect,
1724 |p| p.parse_fn_block_param(),
1731 self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes, RecoverReturnSign::Yes)?;
1733 Ok(P(FnDecl { inputs, output }))
1736 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1737 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
1738 let lo = self.token.span;
1739 let attrs = self.parse_outer_attributes()?;
1740 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1741 let pat = this.parse_pat_no_top_alt(PARAM_EXPECTED)?;
1742 let ty = if this.eat(&token::Colon) {
1745 this.mk_ty(this.prev_token.span, TyKind::Infer)
1750 attrs: attrs.into(),
1753 span: lo.to(this.token.span),
1755 is_placeholder: false,
1757 TrailingToken::MaybeComma,
1762 /// Parses an `if` expression (`if` token already eaten).
1763 fn parse_if_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1764 let lo = self.prev_token.span;
1765 let cond = self.parse_cond_expr()?;
1767 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1768 // verify that the last statement is either an implicit return (no `;`) or an explicit
1769 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1770 // the dead code lint.
1771 let thn = if self.eat_keyword(kw::Else) || !cond.returns() {
1772 self.error_missing_if_cond(lo, cond.span)
1774 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
1775 let not_block = self.token != token::OpenDelim(token::Brace);
1776 let block = self.parse_block().map_err(|mut err| {
1778 err.span_label(lo, "this `if` expression has a condition, but no block");
1779 if let ExprKind::Binary(_, _, ref right) = cond.kind {
1780 if let ExprKind::Block(_, _) = right.kind {
1781 err.help("maybe you forgot the right operand of the condition?");
1787 self.error_on_if_block_attrs(lo, false, block.span, &attrs);
1790 let els = if self.eat_keyword(kw::Else) { Some(self.parse_else_expr()?) } else { None };
1791 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els), attrs))
1794 fn error_missing_if_cond(&self, lo: Span, span: Span) -> P<ast::Block> {
1795 let sp = self.sess.source_map().next_point(lo);
1796 self.struct_span_err(sp, "missing condition for `if` expression")
1797 .span_label(sp, "expected if condition here")
1799 self.mk_block_err(span)
1802 /// Parses the condition of a `if` or `while` expression.
1803 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
1804 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1806 if let ExprKind::Let(..) = cond.kind {
1807 // Remove the last feature gating of a `let` expression since it's stable.
1808 self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
1814 /// Parses a `let $pat = $expr` pseudo-expression.
1815 /// The `let` token has already been eaten.
1816 fn parse_let_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1817 let lo = self.prev_token.span;
1818 let pat = self.parse_pat_allow_top_alt(None, RecoverComma::Yes)?;
1819 self.expect(&token::Eq)?;
1820 let expr = self.with_res(self.restrictions | Restrictions::NO_STRUCT_LITERAL, |this| {
1821 this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
1823 let span = lo.to(expr.span);
1824 self.sess.gated_spans.gate(sym::let_chains, span);
1825 Ok(self.mk_expr(span, ExprKind::Let(pat, expr), attrs))
1828 /// Parses an `else { ... }` expression (`else` token already eaten).
1829 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
1830 let ctx_span = self.prev_token.span; // `else`
1831 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
1832 let expr = if self.eat_keyword(kw::If) {
1833 self.parse_if_expr(AttrVec::new())?
1835 let blk = self.parse_block()?;
1836 self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new())
1838 self.error_on_if_block_attrs(ctx_span, true, expr.span, &attrs);
1842 fn error_on_if_block_attrs(
1847 attrs: &[ast::Attribute],
1849 let (span, last) = match attrs {
1851 [x0 @ xn] | [x0, .., xn] => (x0.span.to(xn.span), xn.span),
1853 let ctx = if is_ctx_else { "else" } else { "if" };
1854 self.struct_span_err(last, "outer attributes are not allowed on `if` and `else` branches")
1855 .span_label(branch_span, "the attributes are attached to this branch")
1856 .span_label(ctx_span, format!("the branch belongs to this `{}`", ctx))
1859 "remove the attributes",
1861 Applicability::MachineApplicable,
1866 /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
1869 opt_label: Option<Label>,
1872 ) -> PResult<'a, P<Expr>> {
1873 // Record whether we are about to parse `for (`.
1874 // This is used below for recovery in case of `for ( $stuff ) $block`
1875 // in which case we will suggest `for $stuff $block`.
1876 let begin_paren = match self.token.kind {
1877 token::OpenDelim(token::Paren) => Some(self.token.span),
1881 let pat = self.parse_pat_allow_top_alt(None, RecoverComma::Yes)?;
1882 if !self.eat_keyword(kw::In) {
1883 self.error_missing_in_for_loop();
1885 self.check_for_for_in_in_typo(self.prev_token.span);
1886 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1888 let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
1890 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
1891 attrs.extend(iattrs);
1893 let kind = ExprKind::ForLoop(pat, expr, loop_block, opt_label);
1894 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1897 fn error_missing_in_for_loop(&mut self) {
1898 let (span, msg, sugg) = if self.token.is_ident_named(sym::of) {
1899 // Possibly using JS syntax (#75311).
1900 let span = self.token.span;
1902 (span, "try using `in` here instead", "in")
1904 (self.prev_token.span.between(self.token.span), "try adding `in` here", " in ")
1906 self.struct_span_err(span, "missing `in` in `for` loop")
1907 .span_suggestion_short(
1911 // Has been misleading, at least in the past (closed Issue #48492).
1912 Applicability::MaybeIncorrect,
1917 /// Parses a `while` or `while let` expression (`while` token already eaten).
1918 fn parse_while_expr(
1920 opt_label: Option<Label>,
1923 ) -> PResult<'a, P<Expr>> {
1924 let cond = self.parse_cond_expr()?;
1925 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1926 attrs.extend(iattrs);
1927 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::While(cond, body, opt_label), attrs))
1930 /// Parses `loop { ... }` (`loop` token already eaten).
1933 opt_label: Option<Label>,
1936 ) -> PResult<'a, P<Expr>> {
1937 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1938 attrs.extend(iattrs);
1939 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::Loop(body, opt_label), attrs))
1942 fn eat_label(&mut self) -> Option<Label> {
1943 self.token.lifetime().map(|ident| {
1949 /// Parses a `match ... { ... }` expression (`match` token already eaten).
1950 fn parse_match_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1951 let match_span = self.prev_token.span;
1952 let lo = self.prev_token.span;
1953 let scrutinee = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1954 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
1955 if self.token == token::Semi {
1956 e.span_suggestion_short(
1958 "try removing this `match`",
1960 Applicability::MaybeIncorrect, // speculative
1966 let mut arms: Vec<Arm> = Vec::new();
1967 while self.token != token::CloseDelim(token::Brace) {
1968 match self.parse_arm() {
1969 Ok(arm) => arms.push(arm),
1971 // Recover by skipping to the end of the block.
1973 self.recover_stmt();
1974 let span = lo.to(self.token.span);
1975 if self.token == token::CloseDelim(token::Brace) {
1978 return Ok(self.mk_expr(span, ExprKind::Match(scrutinee, arms), attrs));
1982 let hi = self.token.span;
1984 Ok(self.mk_expr(lo.to(hi), ExprKind::Match(scrutinee, arms), attrs))
1987 /// Attempt to recover from match arm body with statements and no surrounding braces.
1988 fn parse_arm_body_missing_braces(
1990 first_expr: &P<Expr>,
1992 ) -> Option<P<Expr>> {
1993 if self.token.kind != token::Semi {
1996 let start_snapshot = self.clone();
1997 let semi_sp = self.token.span;
2000 vec![self.mk_stmt(first_expr.span, ast::StmtKind::Expr(first_expr.clone()))];
2001 let err = |this: &mut Parser<'_>, stmts: Vec<ast::Stmt>| {
2002 let span = stmts[0].span.to(stmts[stmts.len() - 1].span);
2003 let mut err = this.struct_span_err(span, "`match` arm body without braces");
2004 let (these, s, are) =
2005 if stmts.len() > 1 { ("these", "s", "are") } else { ("this", "", "is") };
2009 "{these} statement{s} {are} not surrounded by a body",
2015 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2016 if stmts.len() > 1 {
2017 err.multipart_suggestion(
2018 &format!("surround the statement{} with a body", s),
2020 (span.shrink_to_lo(), "{ ".to_string()),
2021 (span.shrink_to_hi(), " }".to_string()),
2023 Applicability::MachineApplicable,
2026 err.span_suggestion(
2028 "use a comma to end a `match` arm expression",
2030 Applicability::MachineApplicable,
2034 this.mk_expr_err(span)
2036 // We might have either a `,` -> `;` typo, or a block without braces. We need
2037 // a more subtle parsing strategy.
2039 if self.token.kind == token::CloseDelim(token::Brace) {
2040 // We have reached the closing brace of the `match` expression.
2041 return Some(err(self, stmts));
2043 if self.token.kind == token::Comma {
2044 *self = start_snapshot;
2047 let pre_pat_snapshot = self.clone();
2048 match self.parse_pat_no_top_alt(None) {
2050 if self.token.kind == token::FatArrow {
2052 *self = pre_pat_snapshot;
2053 return Some(err(self, stmts));
2061 *self = pre_pat_snapshot;
2062 match self.parse_stmt_without_recovery(true, ForceCollect::No) {
2063 // Consume statements for as long as possible.
2068 *self = start_snapshot;
2071 // We couldn't parse either yet another statement missing it's
2072 // enclosing block nor the next arm's pattern or closing brace.
2073 Err(mut stmt_err) => {
2075 *self = start_snapshot;
2083 pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
2084 let attrs = self.parse_outer_attributes()?;
2085 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2086 let lo = this.token.span;
2087 let pat = this.parse_pat_allow_top_alt(None, RecoverComma::Yes)?;
2088 let guard = if this.eat_keyword(kw::If) {
2089 let if_span = this.prev_token.span;
2090 let cond = this.parse_expr()?;
2091 if let ExprKind::Let(..) = cond.kind {
2092 // Remove the last feature gating of a `let` expression since it's stable.
2093 this.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2094 let span = if_span.to(cond.span);
2095 this.sess.gated_spans.gate(sym::if_let_guard, span);
2101 let arrow_span = this.token.span;
2102 this.expect(&token::FatArrow)?;
2103 let arm_start_span = this.token.span;
2105 let expr = this.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| {
2106 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2110 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
2111 && this.token != token::CloseDelim(token::Brace);
2113 let hi = this.prev_token.span;
2116 let sm = this.sess.source_map();
2117 if let Some(body) = this.parse_arm_body_missing_braces(&expr, arrow_span) {
2118 let span = body.span;
2127 is_placeholder: false,
2129 TrailingToken::None,
2132 this.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]).map_err(
2134 match (sm.span_to_lines(expr.span), sm.span_to_lines(arm_start_span)) {
2135 (Ok(ref expr_lines), Ok(ref arm_start_lines))
2136 if arm_start_lines.lines[0].end_col
2137 == expr_lines.lines[0].end_col
2138 && expr_lines.lines.len() == 2
2139 && this.token == token::FatArrow =>
2141 // We check whether there's any trailing code in the parse span,
2142 // if there isn't, we very likely have the following:
2145 // | -- - missing comma
2149 // | - ^^ self.token.span
2151 // | parsed until here as `"y" & X`
2152 err.span_suggestion_short(
2153 arm_start_span.shrink_to_hi(),
2154 "missing a comma here to end this `match` arm",
2156 Applicability::MachineApplicable,
2162 "while parsing the `match` arm starting here",
2170 this.eat(&token::Comma);
2181 is_placeholder: false,
2183 TrailingToken::None,
2188 /// Parses a `try {...}` expression (`try` token already eaten).
2189 fn parse_try_block(&mut self, span_lo: Span, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2190 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2191 attrs.extend(iattrs);
2192 if self.eat_keyword(kw::Catch) {
2193 let mut error = self.struct_span_err(
2194 self.prev_token.span,
2195 "keyword `catch` cannot follow a `try` block",
2197 error.help("try using `match` on the result of the `try` block instead");
2201 let span = span_lo.to(body.span);
2202 self.sess.gated_spans.gate(sym::try_blocks, span);
2203 Ok(self.mk_expr(span, ExprKind::TryBlock(body), attrs))
2207 fn is_do_catch_block(&self) -> bool {
2208 self.token.is_keyword(kw::Do)
2209 && self.is_keyword_ahead(1, &[kw::Catch])
2210 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2211 && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
2214 fn is_try_block(&self) -> bool {
2215 self.token.is_keyword(kw::Try)
2216 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2217 && self.token.uninterpolated_span().rust_2018()
2220 /// Parses an `async move? {...}` expression.
2221 fn parse_async_block(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2222 let lo = self.token.span;
2223 self.expect_keyword(kw::Async)?;
2224 let capture_clause = self.parse_capture_clause()?;
2225 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2226 attrs.extend(iattrs);
2227 let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);
2228 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
2231 fn is_async_block(&self) -> bool {
2232 self.token.is_keyword(kw::Async)
2235 self.is_keyword_ahead(1, &[kw::Move])
2236 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2239 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2243 fn is_certainly_not_a_block(&self) -> bool {
2244 self.look_ahead(1, |t| t.is_ident())
2246 // `{ ident, ` cannot start a block.
2247 self.look_ahead(2, |t| t == &token::Comma)
2248 || self.look_ahead(2, |t| t == &token::Colon)
2250 // `{ ident: token, ` cannot start a block.
2251 self.look_ahead(4, |t| t == &token::Comma) ||
2252 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
2253 self.look_ahead(3, |t| !t.can_begin_type())
2258 fn maybe_parse_struct_expr(
2262 ) -> Option<PResult<'a, P<Expr>>> {
2263 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2264 if struct_allowed || self.is_certainly_not_a_block() {
2265 if let Err(err) = self.expect(&token::OpenDelim(token::Brace)) {
2266 return Some(Err(err));
2268 let expr = self.parse_struct_expr(path.clone(), attrs.clone(), true);
2269 if let (Ok(expr), false) = (&expr, struct_allowed) {
2270 // This is a struct literal, but we don't can't accept them here.
2271 self.error_struct_lit_not_allowed_here(path.span, expr.span);
2278 fn error_struct_lit_not_allowed_here(&self, lo: Span, sp: Span) {
2279 self.struct_span_err(sp, "struct literals are not allowed here")
2280 .multipart_suggestion(
2281 "surround the struct literal with parentheses",
2282 vec![(lo.shrink_to_lo(), "(".to_string()), (sp.shrink_to_hi(), ")".to_string())],
2283 Applicability::MachineApplicable,
2288 /// Precondition: already parsed the '{'.
2289 pub(super) fn parse_struct_expr(
2294 ) -> PResult<'a, P<Expr>> {
2295 let mut fields = Vec::new();
2296 let mut base = ast::StructRest::None;
2297 let mut recover_async = false;
2299 let mut async_block_err = |e: &mut DiagnosticBuilder<'_>, span: Span| {
2300 recover_async = true;
2301 e.span_label(span, "`async` blocks are only allowed in Rust 2018 or later");
2302 e.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
2303 e.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
2306 while self.token != token::CloseDelim(token::Brace) {
2307 if self.eat(&token::DotDot) {
2308 let exp_span = self.prev_token.span;
2309 // We permit `.. }` on the left-hand side of a destructuring assignment.
2310 if self.check(&token::CloseDelim(token::Brace)) {
2311 self.sess.gated_spans.gate(sym::destructuring_assignment, self.prev_token.span);
2312 base = ast::StructRest::Rest(self.prev_token.span.shrink_to_hi());
2315 match self.parse_expr() {
2316 Ok(e) => base = ast::StructRest::Base(e),
2317 Err(mut e) if recover => {
2319 self.recover_stmt();
2321 Err(e) => return Err(e),
2323 self.recover_struct_comma_after_dotdot(exp_span);
2327 let recovery_field = self.find_struct_error_after_field_looking_code();
2328 let parsed_field = match self.parse_expr_field() {
2331 if pth == kw::Async {
2332 async_block_err(&mut e, pth.span);
2334 e.span_label(pth.span, "while parsing this struct");
2338 // If the next token is a comma, then try to parse
2339 // what comes next as additional fields, rather than
2340 // bailing out until next `}`.
2341 if self.token != token::Comma {
2342 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2343 if self.token != token::Comma {
2351 match self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]) {
2353 if let Some(f) = parsed_field.or(recovery_field) {
2354 // Only include the field if there's no parse error for the field name.
2359 if pth == kw::Async {
2360 async_block_err(&mut e, pth.span);
2362 e.span_label(pth.span, "while parsing this struct");
2363 if let Some(f) = recovery_field {
2366 self.prev_token.span.shrink_to_hi(),
2367 "try adding a comma",
2369 Applicability::MachineApplicable,
2377 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2378 self.eat(&token::Comma);
2383 let span = pth.span.to(self.token.span);
2384 self.expect(&token::CloseDelim(token::Brace))?;
2385 let expr = if recover_async {
2388 ExprKind::Struct(P(ast::StructExpr { path: pth, fields, rest: base }))
2390 Ok(self.mk_expr(span, expr, attrs))
2393 /// Use in case of error after field-looking code: `S { foo: () with a }`.
2394 fn find_struct_error_after_field_looking_code(&self) -> Option<ExprField> {
2395 match self.token.ident() {
2396 Some((ident, is_raw))
2397 if (is_raw || !ident.is_reserved())
2398 && self.look_ahead(1, |t| *t == token::Colon) =>
2400 Some(ast::ExprField {
2402 span: self.token.span,
2403 expr: self.mk_expr_err(self.token.span),
2404 is_shorthand: false,
2405 attrs: AttrVec::new(),
2407 is_placeholder: false,
2414 fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
2415 if self.token != token::Comma {
2418 self.struct_span_err(
2419 span.to(self.prev_token.span),
2420 "cannot use a comma after the base struct",
2422 .span_suggestion_short(
2424 "remove this comma",
2426 Applicability::MachineApplicable,
2428 .note("the base struct must always be the last field")
2430 self.recover_stmt();
2433 /// Parses `ident (COLON expr)?`.
2434 fn parse_expr_field(&mut self) -> PResult<'a, ExprField> {
2435 let attrs = self.parse_outer_attributes()?;
2436 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2437 let lo = this.token.span;
2439 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2440 let is_shorthand = !this.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
2441 let (ident, expr) = if is_shorthand {
2442 // Mimic `x: x` for the `x` field shorthand.
2443 let ident = this.parse_ident_common(false)?;
2444 let path = ast::Path::from_ident(ident);
2445 (ident, this.mk_expr(ident.span, ExprKind::Path(None, path), AttrVec::new()))
2447 let ident = this.parse_field_name()?;
2448 this.error_on_eq_field_init(ident);
2450 (ident, this.parse_expr()?)
2456 span: lo.to(expr.span),
2459 attrs: attrs.into(),
2461 is_placeholder: false,
2463 TrailingToken::MaybeComma,
2468 /// Check for `=`. This means the source incorrectly attempts to
2469 /// initialize a field with an eq rather than a colon.
2470 fn error_on_eq_field_init(&self, field_name: Ident) {
2471 if self.token != token::Eq {
2475 self.struct_span_err(self.token.span, "expected `:`, found `=`")
2477 field_name.span.shrink_to_hi().to(self.token.span),
2478 "replace equals symbol with a colon",
2480 Applicability::MachineApplicable,
2485 fn err_dotdotdot_syntax(&self, span: Span) {
2486 self.struct_span_err(span, "unexpected token: `...`")
2489 "use `..` for an exclusive range",
2491 Applicability::MaybeIncorrect,
2495 "or `..=` for an inclusive range",
2497 Applicability::MaybeIncorrect,
2502 fn err_larrow_operator(&self, span: Span) {
2503 self.struct_span_err(span, "unexpected token: `<-`")
2506 "if you meant to write a comparison against a negative value, add a \
2507 space in between `<` and `-`",
2509 Applicability::MaybeIncorrect,
2514 fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2515 ExprKind::AssignOp(binop, lhs, rhs)
2520 start: Option<P<Expr>>,
2521 end: Option<P<Expr>>,
2522 limits: RangeLimits,
2524 if end.is_none() && limits == RangeLimits::Closed {
2525 self.error_inclusive_range_with_no_end(self.prev_token.span);
2528 ExprKind::Range(start, end, limits)
2532 fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
2533 ExprKind::Unary(unop, expr)
2536 fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2537 ExprKind::Binary(binop, lhs, rhs)
2540 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
2541 ExprKind::Index(expr, idx)
2544 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
2545 ExprKind::Call(f, args)
2548 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> P<Expr> {
2549 let span = lo.to(self.prev_token.span);
2550 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), AttrVec::new());
2551 self.recover_from_await_method_call();
2555 crate fn mk_expr(&self, span: Span, kind: ExprKind, attrs: AttrVec) -> P<Expr> {
2556 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None })
2559 pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
2560 self.mk_expr(span, ExprKind::Err, AttrVec::new())
2563 /// Create expression span ensuring the span of the parent node
2564 /// is larger than the span of lhs and rhs, including the attributes.
2565 fn mk_expr_sp(&self, lhs: &P<Expr>, lhs_span: Span, rhs_span: Span) -> Span {
2568 .find(|a| a.style == AttrStyle::Outer)
2569 .map_or(lhs_span, |a| a.span)
2573 fn collect_tokens_for_expr(
2576 f: impl FnOnce(&mut Self, Vec<ast::Attribute>) -> PResult<'a, P<Expr>>,
2577 ) -> PResult<'a, P<Expr>> {
2578 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2579 let res = f(this, attrs)?;
2580 let trailing = if this.restrictions.contains(Restrictions::STMT_EXPR)
2581 && this.token.kind == token::Semi
2585 // FIXME - pass this through from the place where we know
2586 // we need a comma, rather than assuming that `#[attr] expr,`
2587 // always captures a trailing comma
2588 TrailingToken::MaybeComma