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 self.collect_tokens_no_attrs(|this| this.parse_expr())
100 pub fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> {
101 self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
104 fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P<Expr>> {
105 match self.parse_expr() {
106 Ok(expr) => Ok(expr),
107 Err(mut err) => match self.token.ident() {
108 Some((Ident { name: kw::Underscore, .. }, false))
109 if self.look_ahead(1, |t| t == &token::Comma) =>
111 // Special-case handling of `foo(_, _, _)`
114 Ok(self.mk_expr(self.prev_token.span, ExprKind::Err, AttrVec::new()))
121 /// Parses a sequence of expressions delimited by parentheses.
122 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
123 self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r)
126 /// Parses an expression, subject to the given restrictions.
128 pub(super) fn parse_expr_res(
131 already_parsed_attrs: Option<AttrWrapper>,
132 ) -> PResult<'a, P<Expr>> {
133 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
136 /// Parses an associative expression.
138 /// This parses an expression accounting for associativity and precedence of the operators in
143 already_parsed_attrs: Option<AttrWrapper>,
144 ) -> PResult<'a, P<Expr>> {
145 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
148 /// Parses an associative expression with operators of at least `min_prec` precedence.
149 pub(super) fn parse_assoc_expr_with(
153 ) -> PResult<'a, P<Expr>> {
154 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
157 let attrs = match lhs {
158 LhsExpr::AttributesParsed(attrs) => Some(attrs),
161 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
162 return self.parse_prefix_range_expr(attrs);
164 self.parse_prefix_expr(attrs)?
167 let last_type_ascription_set = self.last_type_ascription.is_some();
169 if !self.should_continue_as_assoc_expr(&lhs) {
170 self.last_type_ascription = None;
174 self.expected_tokens.push(TokenType::Operator);
175 while let Some(op) = self.check_assoc_op() {
176 // Adjust the span for interpolated LHS to point to the `$lhs` token
177 // and not to what it refers to.
178 let lhs_span = match self.prev_token.kind {
179 TokenKind::Interpolated(..) => self.prev_token.span,
183 let cur_op_span = self.token.span;
184 let restrictions = if op.node.is_assign_like() {
185 self.restrictions & Restrictions::NO_STRUCT_LITERAL
189 let prec = op.node.precedence();
193 // Check for deprecated `...` syntax
194 if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq {
195 self.err_dotdotdot_syntax(self.token.span);
198 if self.token == token::LArrow {
199 self.err_larrow_operator(self.token.span);
203 if op.node.is_comparison() {
204 if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
209 if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual)
210 && self.token.kind == token::Eq
211 && self.prev_token.span.hi() == self.token.span.lo()
213 // Look for JS' `===` and `!==` and recover 😇
214 let sp = op.span.to(self.token.span);
215 let sugg = match op.node {
216 AssocOp::Equal => "==",
217 AssocOp::NotEqual => "!=",
220 self.struct_span_err(sp, &format!("invalid comparison operator `{}=`", sugg))
221 .span_suggestion_short(
223 &format!("`{s}=` is not a valid comparison operator, use `{s}`", s = sugg),
225 Applicability::MachineApplicable,
233 if op == AssocOp::As {
234 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
236 } else if op == AssocOp::Colon {
237 lhs = self.parse_assoc_op_ascribe(lhs, lhs_span)?;
239 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
240 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
241 // generalise it to the Fixity::None code.
242 lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?;
246 let fixity = op.fixity();
247 let prec_adjustment = match fixity {
250 // We currently have no non-associative operators that are not handled above by
251 // the special cases. The code is here only for future convenience.
254 let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
255 this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
258 let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span);
271 | AssocOp::ShiftRight
277 | AssocOp::GreaterEqual => {
278 let ast_op = op.to_ast_binop().unwrap();
279 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
280 self.mk_expr(span, binary, AttrVec::new())
283 self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span), AttrVec::new())
285 AssocOp::AssignOp(k) => {
287 token::Plus => BinOpKind::Add,
288 token::Minus => BinOpKind::Sub,
289 token::Star => BinOpKind::Mul,
290 token::Slash => BinOpKind::Div,
291 token::Percent => BinOpKind::Rem,
292 token::Caret => BinOpKind::BitXor,
293 token::And => BinOpKind::BitAnd,
294 token::Or => BinOpKind::BitOr,
295 token::Shl => BinOpKind::Shl,
296 token::Shr => BinOpKind::Shr,
298 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
299 self.mk_expr(span, aopexpr, AttrVec::new())
301 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
302 self.span_bug(span, "AssocOp should have been handled by special case")
306 if let Fixity::None = fixity {
310 if last_type_ascription_set {
311 self.last_type_ascription = None;
316 fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
317 match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) {
318 // Semi-statement forms are odd:
319 // See https://github.com/rust-lang/rust/issues/29071
320 (true, None) => false,
321 (false, _) => true, // Continue parsing the expression.
322 // An exhaustive check is done in the following block, but these are checked first
323 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
324 // want to keep their span info to improve diagnostics in these cases in a later stage.
325 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
326 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
327 (true, Some(AssocOp::Add)) // `{ 42 } + 42
328 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
329 // `if x { a } else { b } && if y { c } else { d }`
330 if !self.look_ahead(1, |t| t.is_used_keyword()) => {
331 // These cases are ambiguous and can't be identified in the parser alone.
332 let sp = self.sess.source_map().start_point(self.token.span);
333 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
336 (true, Some(AssocOp::LAnd)) => {
337 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`. Separated from the
338 // above due to #74233.
339 // These cases are ambiguous and can't be identified in the parser alone.
340 let sp = self.sess.source_map().start_point(self.token.span);
341 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
344 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => false,
346 self.error_found_expr_would_be_stmt(lhs);
352 /// We've found an expression that would be parsed as a statement,
353 /// but the next token implies this should be parsed as an expression.
354 /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
355 fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
356 let mut err = self.struct_span_err(
358 &format!("expected expression, found `{}`", pprust::token_to_string(&self.token),),
360 err.span_label(self.token.span, "expected expression");
361 self.sess.expr_parentheses_needed(&mut err, lhs.span, Some(pprust::expr_to_string(&lhs)));
365 /// Possibly translate the current token to an associative operator.
366 /// The method does not advance the current token.
368 /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
369 fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
370 let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
371 // When parsing const expressions, stop parsing when encountering `>`.
376 | AssocOp::GreaterEqual
377 | AssocOp::AssignOp(token::BinOpToken::Shr),
380 ) if self.restrictions.contains(Restrictions::CONST_EXPR) => {
383 (Some(op), _) => (op, self.token.span),
384 (None, Some((Ident { name: sym::and, span }, false))) => {
385 self.error_bad_logical_op("and", "&&", "conjunction");
386 (AssocOp::LAnd, span)
388 (None, Some((Ident { name: sym::or, span }, false))) => {
389 self.error_bad_logical_op("or", "||", "disjunction");
394 Some(source_map::respan(span, op))
397 /// Error on `and` and `or` suggesting `&&` and `||` respectively.
398 fn error_bad_logical_op(&self, bad: &str, good: &str, english: &str) {
399 self.struct_span_err(self.token.span, &format!("`{}` is not a logical operator", bad))
400 .span_suggestion_short(
402 &format!("use `{}` to perform logical {}", good, english),
404 Applicability::MachineApplicable,
406 .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators")
410 /// Checks if this expression is a successfully parsed statement.
411 fn expr_is_complete(&self, e: &Expr) -> bool {
412 self.restrictions.contains(Restrictions::STMT_EXPR)
413 && !classify::expr_requires_semi_to_be_stmt(e)
416 /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
417 /// The other two variants are handled in `parse_prefix_range_expr` below.
424 ) -> PResult<'a, P<Expr>> {
425 let rhs = if self.is_at_start_of_range_notation_rhs() {
426 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
430 let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
431 let span = self.mk_expr_sp(&lhs, lhs.span, rhs_span);
433 if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed };
434 Ok(self.mk_expr(span, self.mk_range(Some(lhs), rhs, limits), AttrVec::new()))
437 fn is_at_start_of_range_notation_rhs(&self) -> bool {
438 if self.token.can_begin_expr() {
439 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
440 if self.token == token::OpenDelim(token::Brace) {
441 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
449 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
450 fn parse_prefix_range_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
451 // Check for deprecated `...` syntax.
452 if self.token == token::DotDotDot {
453 self.err_dotdotdot_syntax(self.token.span);
457 [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
458 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
462 let limits = match self.token.kind {
463 token::DotDot => RangeLimits::HalfOpen,
464 _ => RangeLimits::Closed,
466 let op = AssocOp::from_token(&self.token);
467 // FIXME: `parse_prefix_range_expr` is called when the current
468 // token is `DotDot`, `DotDotDot`, or `DotDotEq`. If we haven't already
469 // parsed attributes, then trying to parse them here will always fail.
470 // We should figure out how we want attributes on range expressions to work.
471 let attrs = self.parse_or_use_outer_attributes(attrs)?;
472 self.collect_tokens_for_expr(attrs, |this, attrs| {
473 let lo = this.token.span;
475 let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() {
476 // RHS must be parsed with more associativity than the dots.
477 this.parse_assoc_expr_with(op.unwrap().precedence() + 1, LhsExpr::NotYetParsed)
478 .map(|x| (lo.to(x.span), Some(x)))?
482 Ok(this.mk_expr(span, this.mk_range(None, opt_end, limits), attrs.into()))
486 /// Parses a prefix-unary-operator expr.
487 fn parse_prefix_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
488 let attrs = self.parse_or_use_outer_attributes(attrs)?;
489 let lo = self.token.span;
491 macro_rules! make_it {
492 ($this:ident, $attrs:expr, |this, _| $body:expr) => {
493 $this.collect_tokens_for_expr($attrs, |$this, attrs| {
494 let (hi, ex) = $body?;
495 Ok($this.mk_expr(lo.to(hi), ex, attrs.into()))
502 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
503 match this.token.uninterpolate().kind {
504 token::Not => make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Not)), // `!expr`
505 token::Tilde => make_it!(this, attrs, |this, _| this.recover_tilde_expr(lo)), // `~expr`
506 token::BinOp(token::Minus) => {
507 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Neg))
509 token::BinOp(token::Star) => {
510 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Deref))
512 token::BinOp(token::And) | token::AndAnd => {
513 make_it!(this, attrs, |this, _| this.parse_borrow_expr(lo))
515 token::Ident(..) if this.token.is_keyword(kw::Box) => {
516 make_it!(this, attrs, |this, _| this.parse_box_expr(lo))
518 token::Ident(..) if this.is_mistaken_not_ident_negation() => {
519 make_it!(this, attrs, |this, _| this.recover_not_expr(lo))
521 _ => return this.parse_dot_or_call_expr(Some(attrs)),
525 fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P<Expr>)> {
527 let expr = self.parse_prefix_expr(None);
528 let (span, expr) = self.interpolated_or_expr_span(expr)?;
529 Ok((lo.to(span), expr))
532 fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
533 let (span, expr) = self.parse_prefix_expr_common(lo)?;
534 Ok((span, self.mk_unary(op, expr)))
537 // Recover on `!` suggesting for bitwise negation instead.
538 fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
539 self.struct_span_err(lo, "`~` cannot be used as a unary operator")
540 .span_suggestion_short(
542 "use `!` to perform bitwise not",
544 Applicability::MachineApplicable,
548 self.parse_unary_expr(lo, UnOp::Not)
551 /// Parse `box expr`.
552 fn parse_box_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
553 let (span, expr) = self.parse_prefix_expr_common(lo)?;
554 self.sess.gated_spans.gate(sym::box_syntax, span);
555 Ok((span, ExprKind::Box(expr)))
558 fn is_mistaken_not_ident_negation(&self) -> bool {
559 let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
560 // These tokens can start an expression after `!`, but
561 // can't continue an expression after an ident
562 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
563 token::Literal(..) | token::Pound => true,
564 _ => t.is_whole_expr(),
566 self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
569 /// Recover on `not expr` in favor of `!expr`.
570 fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
572 let not_token = self.look_ahead(1, |t| t.clone());
573 self.struct_span_err(
575 &format!("unexpected {} after identifier", super::token_descr(¬_token)),
577 .span_suggestion_short(
578 // Span the `not` plus trailing whitespace to avoid
579 // trailing whitespace after the `!` in our suggestion
580 self.sess.source_map().span_until_non_whitespace(lo.to(not_token.span)),
581 "use `!` to perform logical negation",
583 Applicability::MachineApplicable,
588 self.parse_unary_expr(lo, UnOp::Not)
591 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
592 fn interpolated_or_expr_span(
594 expr: PResult<'a, P<Expr>>,
595 ) -> PResult<'a, (Span, P<Expr>)> {
598 match self.prev_token.kind {
599 TokenKind::Interpolated(..) => self.prev_token.span,
607 fn parse_assoc_op_cast(
611 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind,
612 ) -> PResult<'a, P<Expr>> {
613 let mk_expr = |this: &mut Self, lhs: P<Expr>, rhs: P<Ty>| {
615 this.mk_expr_sp(&lhs, lhs_span, rhs.span),
621 // Save the state of the parser before parsing type normally, in case there is a
622 // LessThan comparison after this cast.
623 let parser_snapshot_before_type = self.clone();
624 let cast_expr = match self.parse_ty_no_plus() {
625 Ok(rhs) => mk_expr(self, lhs, rhs),
626 Err(mut type_err) => {
627 // Rewind to before attempting to parse the type with generics, to recover
628 // from situations like `x as usize < y` in which we first tried to parse
629 // `usize < y` as a type with generic arguments.
630 let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
632 // Check for typo of `'a: loop { break 'a }` with a missing `'`.
633 match (&lhs.kind, &self.token.kind) {
636 ExprKind::Path(None, ast::Path { segments, .. }),
637 TokenKind::Ident(kw::For | kw::Loop | kw::While, false),
638 ) if segments.len() == 1 => {
639 let snapshot = self.clone();
641 ident: Ident::from_str_and_span(
642 &format!("'{}", segments[0].ident),
643 segments[0].ident.span,
646 match self.parse_labeled_expr(label, AttrVec::new(), false) {
649 self.struct_span_err(label.ident.span, "malformed loop label")
652 "use the correct loop label format",
653 label.ident.to_string(),
654 Applicability::MachineApplicable,
668 match self.parse_path(PathStyle::Expr) {
670 let (op_noun, op_verb) = match self.token.kind {
671 token::Lt => ("comparison", "comparing"),
672 token::BinOp(token::Shl) => ("shift", "shifting"),
674 // We can end up here even without `<` being the next token, for
675 // example because `parse_ty_no_plus` returns `Err` on keywords,
676 // but `parse_path` returns `Ok` on them due to error recovery.
677 // Return original error and parser state.
678 *self = parser_snapshot_after_type;
679 return Err(type_err);
683 // Successfully parsed the type path leaving a `<` yet to parse.
686 // Report non-fatal diagnostics, keep `x as usize` as an expression
687 // in AST and continue parsing.
689 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
690 pprust::path_to_string(&path),
693 let span_after_type = parser_snapshot_after_type.token.span;
695 mk_expr(self, lhs, self.mk_ty(path.span, TyKind::Path(None, path)));
698 .span_to_snippet(expr.span)
699 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
701 self.struct_span_err(self.token.span, &msg)
703 self.look_ahead(1, |t| t.span).to(span_after_type),
704 "interpreted as generic arguments",
706 .span_label(self.token.span, format!("not interpreted as {}", op_noun))
709 &format!("try {} the cast value", op_verb),
710 format!("({})", expr_str),
711 Applicability::MachineApplicable,
717 Err(mut path_err) => {
718 // Couldn't parse as a path, return original error and parser state.
720 *self = parser_snapshot_after_type;
721 return Err(type_err);
727 self.parse_and_disallow_postfix_after_cast(cast_expr)
730 /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
731 /// then emits an error and returns the newly parsed tree.
732 /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
733 fn parse_and_disallow_postfix_after_cast(
736 ) -> PResult<'a, P<Expr>> {
737 // Save the memory location of expr before parsing any following postfix operators.
738 // This will be compared with the memory location of the output expression.
739 // If they different we can assume we parsed another expression because the existing expression is not reallocated.
740 let addr_before = &*cast_expr as *const _ as usize;
741 let span = cast_expr.span;
742 let with_postfix = self.parse_dot_or_call_expr_with_(cast_expr, span)?;
743 let changed = addr_before != &*with_postfix as *const _ as usize;
745 // Check if an illegal postfix operator has been added after the cast.
746 // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator.
747 if !matches!(with_postfix.kind, ExprKind::Cast(_, _) | ExprKind::Type(_, _)) || changed {
749 "casts cannot be followed by {}",
750 match with_postfix.kind {
751 ExprKind::Index(_, _) => "indexing",
752 ExprKind::Try(_) => "?",
753 ExprKind::Field(_, _) => "a field access",
754 ExprKind::MethodCall(_, _, _) => "a method call",
755 ExprKind::Call(_, _) => "a function call",
756 ExprKind::Await(_) => "`.await`",
757 ExprKind::Err => return Ok(with_postfix),
758 _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"),
761 let mut err = self.struct_span_err(span, &msg);
762 // If type ascription is "likely an error", the user will already be getting a useful
763 // help message, and doesn't need a second.
764 if self.last_type_ascription.map_or(false, |last_ascription| last_ascription.1) {
765 self.maybe_annotate_with_ascription(&mut err, false);
767 let suggestions = vec![
768 (span.shrink_to_lo(), "(".to_string()),
769 (span.shrink_to_hi(), ")".to_string()),
771 err.multipart_suggestion(
772 "try surrounding the expression in parentheses",
774 Applicability::MachineApplicable,
782 fn parse_assoc_op_ascribe(&mut self, lhs: P<Expr>, lhs_span: Span) -> PResult<'a, P<Expr>> {
783 let maybe_path = self.could_ascription_be_path(&lhs.kind);
784 self.last_type_ascription = Some((self.prev_token.span, maybe_path));
785 let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
786 self.sess.gated_spans.gate(sym::type_ascription, lhs.span);
790 /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
791 fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
793 let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
794 let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
795 let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo);
796 let expr = self.parse_prefix_expr(None);
797 let (hi, expr) = self.interpolated_or_expr_span(expr)?;
798 let span = lo.to(hi);
799 if let Some(lt) = lifetime {
800 self.error_remove_borrow_lifetime(span, lt.ident.span);
802 Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
805 fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
806 self.struct_span_err(span, "borrow expressions cannot be annotated with lifetimes")
807 .span_label(lt_span, "annotated with lifetime here")
810 "remove the lifetime annotation",
812 Applicability::MachineApplicable,
817 /// Parse `mut?` or `raw [ const | mut ]`.
818 fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) {
819 if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) {
820 // `raw [ const | mut ]`.
821 let found_raw = self.eat_keyword(kw::Raw);
823 let mutability = self.parse_const_or_mut().unwrap();
824 self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span));
825 (ast::BorrowKind::Raw, mutability)
828 (ast::BorrowKind::Ref, self.parse_mutability())
832 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
833 fn parse_dot_or_call_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
834 let attrs = self.parse_or_use_outer_attributes(attrs)?;
835 self.collect_tokens_for_expr(attrs, |this, attrs| {
836 let base = this.parse_bottom_expr();
837 let (span, base) = this.interpolated_or_expr_span(base)?;
838 this.parse_dot_or_call_expr_with(base, span, attrs)
842 pub(super) fn parse_dot_or_call_expr_with(
846 mut attrs: Vec<ast::Attribute>,
847 ) -> PResult<'a, P<Expr>> {
848 // Stitch the list of outer attributes onto the return value.
849 // A little bit ugly, but the best way given the current code
851 self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| {
852 expr.map(|mut expr| {
853 attrs.extend::<Vec<_>>(expr.attrs.into());
854 expr.attrs = attrs.into();
860 fn parse_dot_or_call_expr_with_(&mut self, mut e: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
862 if self.eat(&token::Question) {
864 e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e), AttrVec::new());
867 if self.eat(&token::Dot) {
869 e = self.parse_dot_suffix_expr(lo, e)?;
872 if self.expr_is_complete(&e) {
875 e = match self.token.kind {
876 token::OpenDelim(token::Paren) => self.parse_fn_call_expr(lo, e),
877 token::OpenDelim(token::Bracket) => self.parse_index_expr(lo, e)?,
883 fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
884 match self.token.uninterpolate().kind {
885 token::Ident(..) => self.parse_dot_suffix(base, lo),
886 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
887 Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix, None))
889 token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => {
890 Ok(self.parse_tuple_field_access_expr_float(lo, base, symbol, suffix))
893 self.error_unexpected_after_dot();
899 fn error_unexpected_after_dot(&self) {
900 // FIXME Could factor this out into non_fatal_unexpected or something.
901 let actual = pprust::token_to_string(&self.token);
902 self.struct_span_err(self.token.span, &format!("unexpected token: `{}`", actual)).emit();
905 // We need an identifier or integer, but the next token is a float.
906 // Break the float into components to extract the identifier or integer.
907 // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
908 // parts unless those parts are processed immediately. `TokenCursor` should either
909 // support pushing "future tokens" (would be also helpful to `break_and_eat`), or
910 // we should break everything including floats into more basic proc-macro style
911 // tokens in the lexer (probably preferable).
912 fn parse_tuple_field_access_expr_float(
917 suffix: Option<Symbol>,
920 enum FloatComponent {
924 use FloatComponent::*;
926 let float_str = float.as_str();
927 let mut components = Vec::new();
928 let mut ident_like = String::new();
929 for c in float_str.chars() {
930 if c == '_' || c.is_ascii_alphanumeric() {
932 } else if matches!(c, '.' | '+' | '-') {
933 if !ident_like.is_empty() {
934 components.push(IdentLike(mem::take(&mut ident_like)));
936 components.push(Punct(c));
938 panic!("unexpected character in a float token: {:?}", c)
941 if !ident_like.is_empty() {
942 components.push(IdentLike(ident_like));
945 // With proc macros the span can refer to anything, the source may be too short,
946 // or too long, or non-ASCII. It only makes sense to break our span into components
947 // if its underlying text is identical to our float literal.
948 let span = self.token.span;
949 let can_take_span_apart =
950 || self.span_to_snippet(span).as_deref() == Ok(float_str).as_deref();
955 self.parse_tuple_field_access_expr(lo, base, Symbol::intern(&i), suffix, None)
958 [IdentLike(i), Punct('.')] => {
959 let (ident_span, dot_span) = if can_take_span_apart() {
960 let (span, ident_len) = (span.data(), BytePos::from_usize(i.len()));
961 let ident_span = span.with_hi(span.lo + ident_len);
962 let dot_span = span.with_lo(span.lo + ident_len);
963 (ident_span, dot_span)
967 assert!(suffix.is_none());
968 let symbol = Symbol::intern(&i);
969 self.token = Token::new(token::Ident(symbol, false), ident_span);
970 let next_token = (Token::new(token::Dot, dot_span), self.token_spacing);
971 self.parse_tuple_field_access_expr(lo, base, symbol, None, Some(next_token))
974 [IdentLike(i1), Punct('.'), IdentLike(i2)] => {
975 let (ident1_span, dot_span, ident2_span) = if can_take_span_apart() {
976 let (span, ident1_len) = (span.data(), BytePos::from_usize(i1.len()));
977 let ident1_span = span.with_hi(span.lo + ident1_len);
979 .with_lo(span.lo + ident1_len)
980 .with_hi(span.lo + ident1_len + BytePos(1));
981 let ident2_span = self.token.span.with_lo(span.lo + ident1_len + BytePos(1));
982 (ident1_span, dot_span, ident2_span)
986 let symbol1 = Symbol::intern(&i1);
987 self.token = Token::new(token::Ident(symbol1, false), ident1_span);
988 // This needs to be `Spacing::Alone` to prevent regressions.
989 // See issue #76399 and PR #76285 for more details
990 let next_token1 = (Token::new(token::Dot, dot_span), Spacing::Alone);
992 self.parse_tuple_field_access_expr(lo, base, symbol1, None, Some(next_token1));
993 let symbol2 = Symbol::intern(&i2);
994 let next_token2 = Token::new(token::Ident(symbol2, false), ident2_span);
995 self.bump_with((next_token2, self.token_spacing)); // `.`
996 self.parse_tuple_field_access_expr(lo, base1, symbol2, suffix, None)
998 // 1e+ | 1e- (recovered)
999 [IdentLike(_), Punct('+' | '-')] |
1001 [IdentLike(_), Punct('+' | '-'), IdentLike(_)] |
1003 [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-'), IdentLike(_)] => {
1004 // See the FIXME about `TokenCursor` above.
1005 self.error_unexpected_after_dot();
1008 _ => panic!("unexpected components in a float token: {:?}", components),
1012 fn parse_tuple_field_access_expr(
1017 suffix: Option<Symbol>,
1018 next_token: Option<(Token, Spacing)>,
1021 Some(next_token) => self.bump_with(next_token),
1022 None => self.bump(),
1024 let span = self.prev_token.span;
1025 let field = ExprKind::Field(base, Ident::new(field, span));
1026 self.expect_no_suffix(span, "a tuple index", suffix);
1027 self.mk_expr(lo.to(span), field, AttrVec::new())
1030 /// Parse a function call expression, `expr(...)`.
1031 fn parse_fn_call_expr(&mut self, lo: Span, fun: P<Expr>) -> P<Expr> {
1032 let seq = self.parse_paren_expr_seq().map(|args| {
1033 self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args), AttrVec::new())
1035 self.recover_seq_parse_error(token::Paren, lo, seq)
1038 /// Parse an indexing expression `expr[...]`.
1039 fn parse_index_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
1041 let index = self.parse_expr()?;
1042 self.expect(&token::CloseDelim(token::Bracket))?;
1043 Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_index(base, index), AttrVec::new()))
1046 /// Assuming we have just parsed `.`, continue parsing into an expression.
1047 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
1048 if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) {
1049 return Ok(self.mk_await_expr(self_arg, lo));
1052 let fn_span_lo = self.token.span;
1053 let mut segment = self.parse_path_segment(PathStyle::Expr)?;
1054 self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(token::Paren)]);
1055 self.check_turbofish_missing_angle_brackets(&mut segment);
1057 if self.check(&token::OpenDelim(token::Paren)) {
1058 // Method call `expr.f()`
1059 let mut args = self.parse_paren_expr_seq()?;
1060 args.insert(0, self_arg);
1062 let fn_span = fn_span_lo.to(self.prev_token.span);
1063 let span = lo.to(self.prev_token.span);
1064 Ok(self.mk_expr(span, ExprKind::MethodCall(segment, args, fn_span), AttrVec::new()))
1066 // Field access `expr.f`
1067 if let Some(args) = segment.args {
1068 self.struct_span_err(
1070 "field expressions cannot have generic arguments",
1075 let span = lo.to(self.prev_token.span);
1076 Ok(self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), AttrVec::new()))
1080 /// At the bottom (top?) of the precedence hierarchy,
1081 /// Parses things like parenthesized exprs, macros, `return`, etc.
1083 /// N.B., this does not parse outer attributes, and is private because it only works
1084 /// correctly if called from `parse_dot_or_call_expr()`.
1085 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1086 maybe_recover_from_interpolated_ty_qpath!(self, true);
1087 maybe_whole_expr!(self);
1089 // Outer attributes are already parsed and will be
1090 // added to the return value after the fact.
1092 // Therefore, prevent sub-parser from parsing
1093 // attributes by giving them a empty "already-parsed" list.
1094 let attrs = AttrVec::new();
1096 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
1097 let lo = self.token.span;
1098 if let token::Literal(_) = self.token.kind {
1099 // This match arm is a special-case of the `_` match arm below and
1100 // could be removed without changing functionality, but it's faster
1101 // to have it here, especially for programs with large constants.
1102 self.parse_lit_expr(attrs)
1103 } else if self.check(&token::OpenDelim(token::Paren)) {
1104 self.parse_tuple_parens_expr(attrs)
1105 } else if self.check(&token::OpenDelim(token::Brace)) {
1106 self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs)
1107 } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) {
1108 self.parse_closure_expr(attrs)
1109 } else if self.check(&token::OpenDelim(token::Bracket)) {
1110 self.parse_array_or_repeat_expr(attrs)
1111 } else if self.eat_lt() {
1112 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
1113 Ok(self.mk_expr(lo.to(path.span), ExprKind::Path(Some(qself), path), attrs))
1114 } else if self.check_path() {
1115 self.parse_path_start_expr(attrs)
1116 } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
1117 self.parse_closure_expr(attrs)
1118 } else if self.eat_keyword(kw::If) {
1119 self.parse_if_expr(attrs)
1120 } else if self.check_keyword(kw::For) {
1121 if self.choose_generics_over_qpath(1) {
1122 // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery,
1123 // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns.
1124 // When `for <Foo as Bar>::Proj in $expr $block` is wanted,
1125 // you can disambiguate in favor of a pattern with `(...)`.
1126 self.recover_quantified_closure_expr(attrs)
1128 assert!(self.eat_keyword(kw::For));
1129 self.parse_for_expr(None, self.prev_token.span, attrs)
1131 } else if self.eat_keyword(kw::While) {
1132 self.parse_while_expr(None, self.prev_token.span, attrs)
1133 } else if let Some(label) = self.eat_label() {
1134 self.parse_labeled_expr(label, attrs, true)
1135 } else if self.eat_keyword(kw::Loop) {
1136 self.parse_loop_expr(None, self.prev_token.span, attrs)
1137 } else if self.eat_keyword(kw::Continue) {
1138 let kind = ExprKind::Continue(self.eat_label());
1139 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1140 } else if self.eat_keyword(kw::Match) {
1141 let match_sp = self.prev_token.span;
1142 self.parse_match_expr(attrs).map_err(|mut err| {
1143 err.span_label(match_sp, "while parsing this match expression");
1146 } else if self.eat_keyword(kw::Unsafe) {
1147 self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs)
1148 } else if self.check_inline_const(0) {
1149 self.parse_const_block(lo.to(self.token.span))
1150 } else if self.is_do_catch_block() {
1151 self.recover_do_catch(attrs)
1152 } else if self.is_try_block() {
1153 self.expect_keyword(kw::Try)?;
1154 self.parse_try_block(lo, attrs)
1155 } else if self.eat_keyword(kw::Return) {
1156 self.parse_return_expr(attrs)
1157 } else if self.eat_keyword(kw::Break) {
1158 self.parse_break_expr(attrs)
1159 } else if self.eat_keyword(kw::Yield) {
1160 self.parse_yield_expr(attrs)
1161 } else if self.eat_keyword(kw::Let) {
1162 self.parse_let_expr(attrs)
1163 } else if self.eat_keyword(kw::Underscore) {
1164 self.sess.gated_spans.gate(sym::destructuring_assignment, self.prev_token.span);
1165 Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore, attrs))
1166 } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1167 // Don't complain about bare semicolons after unclosed braces
1168 // recovery in order to keep the error count down. Fixing the
1169 // delimiters will possibly also fix the bare semicolon found in
1170 // expression context. For example, silence the following error:
1172 // error: expected expression, found `;`
1176 // | ^ expected expression
1178 Ok(self.mk_expr_err(self.token.span))
1179 } else if self.token.uninterpolated_span().rust_2018() {
1180 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1181 if self.check_keyword(kw::Async) {
1182 if self.is_async_block() {
1183 // Check for `async {` and `async move {`.
1184 self.parse_async_block(attrs)
1186 self.parse_closure_expr(attrs)
1188 } else if self.eat_keyword(kw::Await) {
1189 self.recover_incorrect_await_syntax(lo, self.prev_token.span, attrs)
1191 self.parse_lit_expr(attrs)
1194 self.parse_lit_expr(attrs)
1198 fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1199 let lo = self.token.span;
1200 match self.parse_opt_lit() {
1202 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs);
1203 self.maybe_recover_from_bad_qpath(expr, true)
1205 None => self.try_macro_suggestion(),
1209 fn parse_tuple_parens_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1210 let lo = self.token.span;
1211 self.expect(&token::OpenDelim(token::Paren))?;
1212 let (es, trailing_comma) = match self.parse_seq_to_end(
1213 &token::CloseDelim(token::Paren),
1214 SeqSep::trailing_allowed(token::Comma),
1215 |p| p.parse_expr_catch_underscore(),
1218 Err(err) => return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err))),
1220 let kind = if es.len() == 1 && !trailing_comma {
1221 // `(e)` is parenthesized `e`.
1222 ExprKind::Paren(es.into_iter().next().unwrap())
1224 // `(e,)` is a tuple with only one field, `e`.
1227 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1228 self.maybe_recover_from_bad_qpath(expr, true)
1231 fn parse_array_or_repeat_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1232 let lo = self.token.span;
1235 let close = &token::CloseDelim(token::Bracket);
1236 let kind = if self.eat(close) {
1238 ExprKind::Array(Vec::new())
1241 let first_expr = self.parse_expr()?;
1242 if self.eat(&token::Semi) {
1243 // Repeating array syntax: `[ 0; 512 ]`
1244 let count = self.parse_anon_const_expr()?;
1245 self.expect(close)?;
1246 ExprKind::Repeat(first_expr, count)
1247 } else if self.eat(&token::Comma) {
1248 // Vector with two or more elements.
1249 let sep = SeqSep::trailing_allowed(token::Comma);
1250 let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1251 let mut exprs = vec![first_expr];
1252 exprs.extend(remaining_exprs);
1253 ExprKind::Array(exprs)
1255 // Vector with one element
1256 self.expect(close)?;
1257 ExprKind::Array(vec![first_expr])
1260 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1261 self.maybe_recover_from_bad_qpath(expr, true)
1264 fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1265 let path = self.parse_path(PathStyle::Expr)?;
1268 // `!`, as an operator, is prefix, so we know this isn't that.
1269 let (hi, kind) = if self.eat(&token::Not) {
1270 // MACRO INVOCATION expression
1273 args: self.parse_mac_args()?,
1274 prior_type_ascription: self.last_type_ascription,
1276 (self.prev_token.span, ExprKind::MacCall(mac))
1277 } else if self.check(&token::OpenDelim(token::Brace)) {
1278 if let Some(expr) = self.maybe_parse_struct_expr(&path, &attrs) {
1281 (path.span, ExprKind::Path(None, path))
1284 (path.span, ExprKind::Path(None, path))
1287 let expr = self.mk_expr(lo.to(hi), kind, attrs);
1288 self.maybe_recover_from_bad_qpath(expr, true)
1291 /// Parse `'label: $expr`. The label is already parsed.
1292 fn parse_labeled_expr(
1296 consume_colon: bool,
1297 ) -> PResult<'a, P<Expr>> {
1298 let lo = label.ident.span;
1299 let label = Some(label);
1300 let ate_colon = self.eat(&token::Colon);
1301 let expr = if self.eat_keyword(kw::While) {
1302 self.parse_while_expr(label, lo, attrs)
1303 } else if self.eat_keyword(kw::For) {
1304 self.parse_for_expr(label, lo, attrs)
1305 } else if self.eat_keyword(kw::Loop) {
1306 self.parse_loop_expr(label, lo, attrs)
1307 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1308 self.parse_block_expr(label, lo, BlockCheckMode::Default, attrs)
1310 let msg = "expected `while`, `for`, `loop` or `{` after a label";
1311 self.struct_span_err(self.token.span, msg).span_label(self.token.span, msg).emit();
1312 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1316 if !ate_colon && consume_colon {
1317 self.error_labeled_expr_must_be_followed_by_colon(lo, expr.span);
1323 fn error_labeled_expr_must_be_followed_by_colon(&self, lo: Span, span: Span) {
1324 self.struct_span_err(span, "labeled expression must be followed by `:`")
1325 .span_label(lo, "the label")
1326 .span_suggestion_short(
1328 "add `:` after the label",
1330 Applicability::MachineApplicable,
1332 .note("labels are used before loops and blocks, allowing e.g., `break 'label` to them")
1336 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1337 fn recover_do_catch(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1338 let lo = self.token.span;
1340 self.bump(); // `do`
1341 self.bump(); // `catch`
1343 let span_dc = lo.to(self.prev_token.span);
1344 self.struct_span_err(span_dc, "found removed `do catch` syntax")
1347 "replace with the new syntax",
1349 Applicability::MachineApplicable,
1351 .note("following RFC #2388, the new non-placeholder syntax is `try`")
1354 self.parse_try_block(lo, attrs)
1357 /// Parse an expression if the token can begin one.
1358 fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1359 Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1362 /// Parse `"return" expr?`.
1363 fn parse_return_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1364 let lo = self.prev_token.span;
1365 let kind = ExprKind::Ret(self.parse_expr_opt()?);
1366 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1367 self.maybe_recover_from_bad_qpath(expr, true)
1370 /// Parse `"('label ":")? break expr?`.
1371 fn parse_break_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1372 let lo = self.prev_token.span;
1373 let label = self.eat_label();
1374 let kind = if self.token != token::OpenDelim(token::Brace)
1375 || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1377 self.parse_expr_opt()?
1381 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind), attrs);
1382 self.maybe_recover_from_bad_qpath(expr, true)
1385 /// Parse `"yield" expr?`.
1386 fn parse_yield_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1387 let lo = self.prev_token.span;
1388 let kind = ExprKind::Yield(self.parse_expr_opt()?);
1389 let span = lo.to(self.prev_token.span);
1390 self.sess.gated_spans.gate(sym::generators, span);
1391 let expr = self.mk_expr(span, kind, attrs);
1392 self.maybe_recover_from_bad_qpath(expr, true)
1395 /// Returns a string literal if the next token is a string literal.
1396 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1397 /// and returns `None` if the next token is not literal at all.
1398 pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
1399 match self.parse_opt_lit() {
1400 Some(lit) => match lit.kind {
1401 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1403 symbol: lit.token.symbol,
1404 suffix: lit.token.suffix,
1408 _ => Err(Some(lit)),
1414 pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> {
1415 self.parse_opt_lit().ok_or_else(|| {
1416 let msg = format!("unexpected token: {}", super::token_descr(&self.token));
1417 self.struct_span_err(self.token.span, &msg)
1421 /// Matches `lit = true | false | token_lit`.
1422 /// Returns `None` if the next token is not a literal.
1423 pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
1424 let mut recovered = None;
1425 if self.token == token::Dot {
1426 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1427 // dot would follow an optional literal, so we do this unconditionally.
1428 recovered = self.look_ahead(1, |next_token| {
1429 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1432 if self.token.span.hi() == next_token.span.lo() {
1433 let s = String::from("0.") + &symbol.as_str();
1434 let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1435 return Some(Token::new(kind, self.token.span.to(next_token.span)));
1440 if let Some(token) = &recovered {
1442 self.error_float_lits_must_have_int_part(&token);
1446 let token = recovered.as_ref().unwrap_or(&self.token);
1447 match Lit::from_token(token) {
1452 Err(LitError::NotLiteral) => None,
1454 let span = token.span;
1455 let lit = match token.kind {
1456 token::Literal(lit) => lit,
1457 _ => unreachable!(),
1460 self.report_lit_error(err, lit, span);
1461 // Pack possible quotes and prefixes from the original literal into
1462 // the error literal's symbol so they can be pretty-printed faithfully.
1463 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1464 let symbol = Symbol::intern(&suffixless_lit.to_string());
1465 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1466 Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!()))
1471 fn error_float_lits_must_have_int_part(&self, token: &Token) {
1472 self.struct_span_err(token.span, "float literals must have an integer part")
1475 "must have an integer part",
1476 pprust::token_to_string(token),
1477 Applicability::MachineApplicable,
1482 fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) {
1483 // Checks if `s` looks like i32 or u1234 etc.
1484 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1485 s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
1488 let token::Lit { kind, suffix, .. } = lit;
1490 // `NotLiteral` is not an error by itself, so we don't report
1491 // it and give the parser opportunity to try something else.
1492 LitError::NotLiteral => {}
1493 // `LexerError` *is* an error, but it was already reported
1494 // by lexer, so here we don't report it the second time.
1495 LitError::LexerError => {}
1496 LitError::InvalidSuffix => {
1497 self.expect_no_suffix(
1499 &format!("{} {} literal", kind.article(), kind.descr()),
1503 LitError::InvalidIntSuffix => {
1504 let suf = suffix.expect("suffix error with no suffix").as_str();
1505 if looks_like_width_suffix(&['i', 'u'], &suf) {
1506 // If it looks like a width, try to be helpful.
1507 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
1508 self.struct_span_err(span, &msg)
1509 .help("valid widths are 8, 16, 32, 64 and 128")
1512 let msg = format!("invalid suffix `{}` for number literal", suf);
1513 self.struct_span_err(span, &msg)
1514 .span_label(span, format!("invalid suffix `{}`", suf))
1515 .help("the suffix must be one of the numeric types (`u32`, `isize`, `f32`, etc.)")
1519 LitError::InvalidFloatSuffix => {
1520 let suf = suffix.expect("suffix error with no suffix").as_str();
1521 if looks_like_width_suffix(&['f'], &suf) {
1522 // If it looks like a width, try to be helpful.
1523 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
1524 self.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit();
1526 let msg = format!("invalid suffix `{}` for float literal", suf);
1527 self.struct_span_err(span, &msg)
1528 .span_label(span, format!("invalid suffix `{}`", suf))
1529 .help("valid suffixes are `f32` and `f64`")
1533 LitError::NonDecimalFloat(base) => {
1534 let descr = match base {
1535 16 => "hexadecimal",
1538 _ => unreachable!(),
1540 self.struct_span_err(span, &format!("{} float literal is not supported", descr))
1541 .span_label(span, "not supported")
1544 LitError::IntTooLarge => {
1545 self.struct_span_err(span, "integer literal is too large").emit();
1550 pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) {
1551 if let Some(suf) = suffix {
1552 let mut err = if kind == "a tuple index"
1553 && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf)
1555 // #59553: warn instead of reject out of hand to allow the fix to percolate
1556 // through the ecosystem when people fix their macros
1560 .struct_span_warn(sp, &format!("suffixes on {} are invalid", kind));
1562 "`{}` is *temporarily* accepted on tuple index fields as it was \
1563 incorrectly accepted on stable for a few releases",
1567 "on proc macros, you'll want to use `syn::Index::from` or \
1568 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1569 to tuple field access",
1572 "see issue #60210 <https://github.com/rust-lang/rust/issues/60210> \
1573 for more information",
1577 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1579 err.span_label(sp, format!("invalid suffix `{}`", suf));
1584 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1585 /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
1586 pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1587 maybe_whole_expr!(self);
1589 let lo = self.token.span;
1590 let minus_present = self.eat(&token::BinOp(token::Minus));
1591 let lit = self.parse_lit()?;
1592 let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new());
1596 lo.to(self.prev_token.span),
1597 self.mk_unary(UnOp::Neg, expr),
1605 /// Parses a block or unsafe block.
1606 pub(super) fn parse_block_expr(
1608 opt_label: Option<Label>,
1610 blk_mode: BlockCheckMode,
1612 ) -> PResult<'a, P<Expr>> {
1613 if let Some(label) = opt_label {
1614 self.sess.gated_spans.gate(sym::label_break_value, label.ident.span);
1617 if self.token.is_whole_block() {
1618 self.struct_span_err(self.token.span, "cannot use a `block` macro fragment here")
1619 .span_label(lo.to(self.token.span), "the `block` fragment is within this context")
1623 let (inner_attrs, blk) = self.parse_block_common(lo, blk_mode)?;
1624 attrs.extend(inner_attrs);
1625 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs))
1628 /// Recover on an explicitly quantified closure expression, e.g., `for<'a> |x: &'a u8| *x + 1`.
1629 fn recover_quantified_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1630 let lo = self.token.span;
1631 let _ = self.parse_late_bound_lifetime_defs()?;
1632 let span_for = lo.to(self.prev_token.span);
1633 let closure = self.parse_closure_expr(attrs)?;
1635 self.struct_span_err(span_for, "cannot introduce explicit parameters for a closure")
1636 .span_label(closure.span, "the parameters are attached to this closure")
1639 "remove the parameters",
1641 Applicability::MachineApplicable,
1645 Ok(self.mk_expr_err(lo.to(closure.span)))
1648 /// Parses a closure expression (e.g., `move |args| expr`).
1649 fn parse_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1650 let lo = self.token.span;
1653 if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
1655 let asyncness = if self.token.uninterpolated_span().rust_2018() {
1656 self.parse_asyncness()
1661 let capture_clause = self.parse_capture_clause()?;
1662 let decl = self.parse_fn_block_decl()?;
1663 let decl_hi = self.prev_token.span;
1664 let body = match decl.output {
1665 FnRetTy::Default(_) => {
1666 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
1667 self.parse_expr_res(restrictions, None)?
1670 // If an explicit return type is given, require a block to appear (RFC 968).
1671 let body_lo = self.token.span;
1672 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, AttrVec::new())?
1676 if let Async::Yes { span, .. } = asyncness {
1677 // Feature-gate `async ||` closures.
1678 self.sess.gated_spans.gate(sym::async_closure, span);
1683 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
1688 /// Parses an optional `move` prefix to a closure-like construct.
1689 fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> {
1690 if self.eat_keyword(kw::Move) {
1691 // Check for `move async` and recover
1692 if self.check_keyword(kw::Async) {
1693 let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
1694 Err(self.incorrect_move_async_order_found(move_async_span))
1696 Ok(CaptureBy::Value)
1703 /// Parses the `|arg, arg|` header of a closure.
1704 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
1705 let inputs = if self.eat(&token::OrOr) {
1708 self.expect(&token::BinOp(token::Or))?;
1710 .parse_seq_to_before_tokens(
1711 &[&token::BinOp(token::Or), &token::OrOr],
1712 SeqSep::trailing_allowed(token::Comma),
1713 TokenExpectType::NoExpect,
1714 |p| p.parse_fn_block_param(),
1721 self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes, RecoverReturnSign::Yes)?;
1723 Ok(P(FnDecl { inputs, output }))
1726 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1727 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
1728 let lo = self.token.span;
1729 let attrs = self.parse_outer_attributes()?;
1730 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1731 let pat = this.parse_pat_no_top_alt(PARAM_EXPECTED)?;
1732 let ty = if this.eat(&token::Colon) {
1735 this.mk_ty(this.prev_token.span, TyKind::Infer)
1740 attrs: attrs.into(),
1743 span: lo.to(this.token.span),
1745 is_placeholder: false,
1747 TrailingToken::MaybeComma,
1752 /// Parses an `if` expression (`if` token already eaten).
1753 fn parse_if_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1754 let lo = self.prev_token.span;
1755 let cond = self.parse_cond_expr()?;
1757 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1758 // verify that the last statement is either an implicit return (no `;`) or an explicit
1759 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1760 // the dead code lint.
1761 let thn = if self.eat_keyword(kw::Else) || !cond.returns() {
1762 self.error_missing_if_cond(lo, cond.span)
1764 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
1765 let not_block = self.token != token::OpenDelim(token::Brace);
1766 let block = self.parse_block().map_err(|mut err| {
1768 err.span_label(lo, "this `if` expression has a condition, but no block");
1769 if let ExprKind::Binary(_, _, ref right) = cond.kind {
1770 if let ExprKind::Block(_, _) = right.kind {
1771 err.help("maybe you forgot the right operand of the condition?");
1777 self.error_on_if_block_attrs(lo, false, block.span, &attrs);
1780 let els = if self.eat_keyword(kw::Else) { Some(self.parse_else_expr()?) } else { None };
1781 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els), attrs))
1784 fn error_missing_if_cond(&self, lo: Span, span: Span) -> P<ast::Block> {
1785 let sp = self.sess.source_map().next_point(lo);
1786 self.struct_span_err(sp, "missing condition for `if` expression")
1787 .span_label(sp, "expected if condition here")
1789 self.mk_block_err(span)
1792 /// Parses the condition of a `if` or `while` expression.
1793 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
1794 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1796 if let ExprKind::Let(..) = cond.kind {
1797 // Remove the last feature gating of a `let` expression since it's stable.
1798 self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
1804 /// Parses a `let $pat = $expr` pseudo-expression.
1805 /// The `let` token has already been eaten.
1806 fn parse_let_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1807 let lo = self.prev_token.span;
1808 let pat = self.parse_pat_allow_top_alt(None, RecoverComma::Yes)?;
1809 self.expect(&token::Eq)?;
1810 let expr = self.with_res(self.restrictions | Restrictions::NO_STRUCT_LITERAL, |this| {
1811 this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
1813 let span = lo.to(expr.span);
1814 self.sess.gated_spans.gate(sym::let_chains, span);
1815 Ok(self.mk_expr(span, ExprKind::Let(pat, expr), attrs))
1818 /// Parses an `else { ... }` expression (`else` token already eaten).
1819 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
1820 let ctx_span = self.prev_token.span; // `else`
1821 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
1822 let expr = if self.eat_keyword(kw::If) {
1823 self.parse_if_expr(AttrVec::new())?
1825 let blk = self.parse_block()?;
1826 self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new())
1828 self.error_on_if_block_attrs(ctx_span, true, expr.span, &attrs);
1832 fn error_on_if_block_attrs(
1837 attrs: &[ast::Attribute],
1839 let (span, last) = match attrs {
1841 [x0 @ xn] | [x0, .., xn] => (x0.span.to(xn.span), xn.span),
1843 let ctx = if is_ctx_else { "else" } else { "if" };
1844 self.struct_span_err(last, "outer attributes are not allowed on `if` and `else` branches")
1845 .span_label(branch_span, "the attributes are attached to this branch")
1846 .span_label(ctx_span, format!("the branch belongs to this `{}`", ctx))
1849 "remove the attributes",
1851 Applicability::MachineApplicable,
1856 /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
1859 opt_label: Option<Label>,
1862 ) -> PResult<'a, P<Expr>> {
1863 // Record whether we are about to parse `for (`.
1864 // This is used below for recovery in case of `for ( $stuff ) $block`
1865 // in which case we will suggest `for $stuff $block`.
1866 let begin_paren = match self.token.kind {
1867 token::OpenDelim(token::Paren) => Some(self.token.span),
1871 let pat = self.parse_pat_allow_top_alt(None, RecoverComma::Yes)?;
1872 if !self.eat_keyword(kw::In) {
1873 self.error_missing_in_for_loop();
1875 self.check_for_for_in_in_typo(self.prev_token.span);
1876 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1878 let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
1880 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
1881 attrs.extend(iattrs);
1883 let kind = ExprKind::ForLoop(pat, expr, loop_block, opt_label);
1884 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1887 fn error_missing_in_for_loop(&mut self) {
1888 let (span, msg, sugg) = if self.token.is_ident_named(sym::of) {
1889 // Possibly using JS syntax (#75311).
1890 let span = self.token.span;
1892 (span, "try using `in` here instead", "in")
1894 (self.prev_token.span.between(self.token.span), "try adding `in` here", " in ")
1896 self.struct_span_err(span, "missing `in` in `for` loop")
1897 .span_suggestion_short(
1901 // Has been misleading, at least in the past (closed Issue #48492).
1902 Applicability::MaybeIncorrect,
1907 /// Parses a `while` or `while let` expression (`while` token already eaten).
1908 fn parse_while_expr(
1910 opt_label: Option<Label>,
1913 ) -> PResult<'a, P<Expr>> {
1914 let cond = self.parse_cond_expr()?;
1915 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1916 attrs.extend(iattrs);
1917 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::While(cond, body, opt_label), attrs))
1920 /// Parses `loop { ... }` (`loop` token already eaten).
1923 opt_label: Option<Label>,
1926 ) -> PResult<'a, P<Expr>> {
1927 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1928 attrs.extend(iattrs);
1929 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::Loop(body, opt_label), attrs))
1932 fn eat_label(&mut self) -> Option<Label> {
1933 self.token.lifetime().map(|ident| {
1939 /// Parses a `match ... { ... }` expression (`match` token already eaten).
1940 fn parse_match_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1941 let match_span = self.prev_token.span;
1942 let lo = self.prev_token.span;
1943 let scrutinee = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1944 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
1945 if self.token == token::Semi {
1946 e.span_suggestion_short(
1948 "try removing this `match`",
1950 Applicability::MaybeIncorrect, // speculative
1956 let mut arms: Vec<Arm> = Vec::new();
1957 while self.token != token::CloseDelim(token::Brace) {
1958 match self.parse_arm() {
1959 Ok(arm) => arms.push(arm),
1961 // Recover by skipping to the end of the block.
1963 self.recover_stmt();
1964 let span = lo.to(self.token.span);
1965 if self.token == token::CloseDelim(token::Brace) {
1968 return Ok(self.mk_expr(span, ExprKind::Match(scrutinee, arms), attrs));
1972 let hi = self.token.span;
1974 Ok(self.mk_expr(lo.to(hi), ExprKind::Match(scrutinee, arms), attrs))
1977 /// Attempt to recover from match arm body with statements and no surrounding braces.
1978 fn parse_arm_body_missing_braces(
1980 first_expr: &P<Expr>,
1982 ) -> Option<P<Expr>> {
1983 if self.token.kind != token::Semi {
1986 let start_snapshot = self.clone();
1987 let semi_sp = self.token.span;
1990 vec![self.mk_stmt(first_expr.span, ast::StmtKind::Expr(first_expr.clone()))];
1991 let err = |this: &mut Parser<'_>, stmts: Vec<ast::Stmt>| {
1992 let span = stmts[0].span.to(stmts[stmts.len() - 1].span);
1993 let mut err = this.struct_span_err(span, "`match` arm body without braces");
1994 let (these, s, are) =
1995 if stmts.len() > 1 { ("these", "s", "are") } else { ("this", "", "is") };
1999 "{these} statement{s} {are} not surrounded by a body",
2005 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2006 if stmts.len() > 1 {
2007 err.multipart_suggestion(
2008 &format!("surround the statement{} with a body", s),
2010 (span.shrink_to_lo(), "{ ".to_string()),
2011 (span.shrink_to_hi(), " }".to_string()),
2013 Applicability::MachineApplicable,
2016 err.span_suggestion(
2018 "use a comma to end a `match` arm expression",
2020 Applicability::MachineApplicable,
2024 this.mk_expr_err(span)
2026 // We might have either a `,` -> `;` typo, or a block without braces. We need
2027 // a more subtle parsing strategy.
2029 if self.token.kind == token::CloseDelim(token::Brace) {
2030 // We have reached the closing brace of the `match` expression.
2031 return Some(err(self, stmts));
2033 if self.token.kind == token::Comma {
2034 *self = start_snapshot;
2037 let pre_pat_snapshot = self.clone();
2038 match self.parse_pat_no_top_alt(None) {
2040 if self.token.kind == token::FatArrow {
2042 *self = pre_pat_snapshot;
2043 return Some(err(self, stmts));
2051 *self = pre_pat_snapshot;
2052 match self.parse_stmt_without_recovery(true, ForceCollect::No) {
2053 // Consume statements for as long as possible.
2058 *self = start_snapshot;
2061 // We couldn't parse either yet another statement missing it's
2062 // enclosing block nor the next arm's pattern or closing brace.
2063 Err(mut stmt_err) => {
2065 *self = start_snapshot;
2073 pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
2074 let attrs = self.parse_outer_attributes()?;
2075 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2076 let lo = this.token.span;
2077 let pat = this.parse_pat_allow_top_alt(None, RecoverComma::Yes)?;
2078 let guard = if this.eat_keyword(kw::If) {
2079 let if_span = this.prev_token.span;
2080 let cond = this.parse_expr()?;
2081 if let ExprKind::Let(..) = cond.kind {
2082 // Remove the last feature gating of a `let` expression since it's stable.
2083 this.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2084 let span = if_span.to(cond.span);
2085 this.sess.gated_spans.gate(sym::if_let_guard, span);
2091 let arrow_span = this.token.span;
2092 this.expect(&token::FatArrow)?;
2093 let arm_start_span = this.token.span;
2095 let expr = this.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| {
2096 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2100 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
2101 && this.token != token::CloseDelim(token::Brace);
2103 let hi = this.prev_token.span;
2106 let sm = this.sess.source_map();
2107 if let Some(body) = this.parse_arm_body_missing_braces(&expr, arrow_span) {
2108 let span = body.span;
2117 is_placeholder: false,
2119 TrailingToken::None,
2122 this.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]).map_err(
2124 match (sm.span_to_lines(expr.span), sm.span_to_lines(arm_start_span)) {
2125 (Ok(ref expr_lines), Ok(ref arm_start_lines))
2126 if arm_start_lines.lines[0].end_col
2127 == expr_lines.lines[0].end_col
2128 && expr_lines.lines.len() == 2
2129 && this.token == token::FatArrow =>
2131 // We check whether there's any trailing code in the parse span,
2132 // if there isn't, we very likely have the following:
2135 // | -- - missing comma
2139 // | - ^^ self.token.span
2141 // | parsed until here as `"y" & X`
2142 err.span_suggestion_short(
2143 arm_start_span.shrink_to_hi(),
2144 "missing a comma here to end this `match` arm",
2146 Applicability::MachineApplicable,
2152 "while parsing the `match` arm starting here",
2160 this.eat(&token::Comma);
2171 is_placeholder: false,
2173 TrailingToken::None,
2178 /// Parses a `try {...}` expression (`try` token already eaten).
2179 fn parse_try_block(&mut self, span_lo: Span, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2180 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2181 attrs.extend(iattrs);
2182 if self.eat_keyword(kw::Catch) {
2183 let mut error = self.struct_span_err(
2184 self.prev_token.span,
2185 "keyword `catch` cannot follow a `try` block",
2187 error.help("try using `match` on the result of the `try` block instead");
2191 let span = span_lo.to(body.span);
2192 self.sess.gated_spans.gate(sym::try_blocks, span);
2193 Ok(self.mk_expr(span, ExprKind::TryBlock(body), attrs))
2197 fn is_do_catch_block(&self) -> bool {
2198 self.token.is_keyword(kw::Do)
2199 && self.is_keyword_ahead(1, &[kw::Catch])
2200 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2201 && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
2204 fn is_try_block(&self) -> bool {
2205 self.token.is_keyword(kw::Try)
2206 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2207 && self.token.uninterpolated_span().rust_2018()
2210 /// Parses an `async move? {...}` expression.
2211 fn parse_async_block(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2212 let lo = self.token.span;
2213 self.expect_keyword(kw::Async)?;
2214 let capture_clause = self.parse_capture_clause()?;
2215 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2216 attrs.extend(iattrs);
2217 let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);
2218 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
2221 fn is_async_block(&self) -> bool {
2222 self.token.is_keyword(kw::Async)
2225 self.is_keyword_ahead(1, &[kw::Move])
2226 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2229 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2233 fn is_certainly_not_a_block(&self) -> bool {
2234 self.look_ahead(1, |t| t.is_ident())
2236 // `{ ident, ` cannot start a block.
2237 self.look_ahead(2, |t| t == &token::Comma)
2238 || self.look_ahead(2, |t| t == &token::Colon)
2240 // `{ ident: token, ` cannot start a block.
2241 self.look_ahead(4, |t| t == &token::Comma) ||
2242 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
2243 self.look_ahead(3, |t| !t.can_begin_type())
2248 fn maybe_parse_struct_expr(
2252 ) -> Option<PResult<'a, P<Expr>>> {
2253 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2254 if struct_allowed || self.is_certainly_not_a_block() {
2255 if let Err(err) = self.expect(&token::OpenDelim(token::Brace)) {
2256 return Some(Err(err));
2258 let expr = self.parse_struct_expr(path.clone(), attrs.clone(), true);
2259 if let (Ok(expr), false) = (&expr, struct_allowed) {
2260 // This is a struct literal, but we don't can't accept them here.
2261 self.error_struct_lit_not_allowed_here(path.span, expr.span);
2268 fn error_struct_lit_not_allowed_here(&self, lo: Span, sp: Span) {
2269 self.struct_span_err(sp, "struct literals are not allowed here")
2270 .multipart_suggestion(
2271 "surround the struct literal with parentheses",
2272 vec![(lo.shrink_to_lo(), "(".to_string()), (sp.shrink_to_hi(), ")".to_string())],
2273 Applicability::MachineApplicable,
2278 /// Precondition: already parsed the '{'.
2279 pub(super) fn parse_struct_expr(
2284 ) -> PResult<'a, P<Expr>> {
2285 let mut fields = Vec::new();
2286 let mut base = ast::StructRest::None;
2287 let mut recover_async = false;
2289 let mut async_block_err = |e: &mut DiagnosticBuilder<'_>, span: Span| {
2290 recover_async = true;
2291 e.span_label(span, "`async` blocks are only allowed in Rust 2018 or later");
2292 e.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
2293 e.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
2296 while self.token != token::CloseDelim(token::Brace) {
2297 if self.eat(&token::DotDot) {
2298 let exp_span = self.prev_token.span;
2299 // We permit `.. }` on the left-hand side of a destructuring assignment.
2300 if self.check(&token::CloseDelim(token::Brace)) {
2301 self.sess.gated_spans.gate(sym::destructuring_assignment, self.prev_token.span);
2302 base = ast::StructRest::Rest(self.prev_token.span.shrink_to_hi());
2305 match self.parse_expr() {
2306 Ok(e) => base = ast::StructRest::Base(e),
2307 Err(mut e) if recover => {
2309 self.recover_stmt();
2311 Err(e) => return Err(e),
2313 self.recover_struct_comma_after_dotdot(exp_span);
2317 let recovery_field = self.find_struct_error_after_field_looking_code();
2318 let parsed_field = match self.parse_expr_field() {
2321 if pth == kw::Async {
2322 async_block_err(&mut e, pth.span);
2324 e.span_label(pth.span, "while parsing this struct");
2328 // If the next token is a comma, then try to parse
2329 // what comes next as additional fields, rather than
2330 // bailing out until next `}`.
2331 if self.token != token::Comma {
2332 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2333 if self.token != token::Comma {
2341 match self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]) {
2343 if let Some(f) = parsed_field.or(recovery_field) {
2344 // Only include the field if there's no parse error for the field name.
2349 if pth == kw::Async {
2350 async_block_err(&mut e, pth.span);
2352 e.span_label(pth.span, "while parsing this struct");
2353 if let Some(f) = recovery_field {
2356 self.prev_token.span.shrink_to_hi(),
2357 "try adding a comma",
2359 Applicability::MachineApplicable,
2367 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2368 self.eat(&token::Comma);
2373 let span = pth.span.to(self.token.span);
2374 self.expect(&token::CloseDelim(token::Brace))?;
2375 let expr = if recover_async {
2378 ExprKind::Struct(P(ast::StructExpr { path: pth, fields, rest: base }))
2380 Ok(self.mk_expr(span, expr, attrs))
2383 /// Use in case of error after field-looking code: `S { foo: () with a }`.
2384 fn find_struct_error_after_field_looking_code(&self) -> Option<ExprField> {
2385 match self.token.ident() {
2386 Some((ident, is_raw))
2387 if (is_raw || !ident.is_reserved())
2388 && self.look_ahead(1, |t| *t == token::Colon) =>
2390 Some(ast::ExprField {
2392 span: self.token.span,
2393 expr: self.mk_expr_err(self.token.span),
2394 is_shorthand: false,
2395 attrs: AttrVec::new(),
2397 is_placeholder: false,
2404 fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
2405 if self.token != token::Comma {
2408 self.struct_span_err(
2409 span.to(self.prev_token.span),
2410 "cannot use a comma after the base struct",
2412 .span_suggestion_short(
2414 "remove this comma",
2416 Applicability::MachineApplicable,
2418 .note("the base struct must always be the last field")
2420 self.recover_stmt();
2423 /// Parses `ident (COLON expr)?`.
2424 fn parse_expr_field(&mut self) -> PResult<'a, ExprField> {
2425 let attrs = self.parse_outer_attributes()?;
2426 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2427 let lo = this.token.span;
2429 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2430 let is_shorthand = !this.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
2431 let (ident, expr) = if is_shorthand {
2432 // Mimic `x: x` for the `x` field shorthand.
2433 let ident = this.parse_ident_common(false)?;
2434 let path = ast::Path::from_ident(ident);
2435 (ident, this.mk_expr(ident.span, ExprKind::Path(None, path), AttrVec::new()))
2437 let ident = this.parse_field_name()?;
2438 this.error_on_eq_field_init(ident);
2440 (ident, this.parse_expr()?)
2446 span: lo.to(expr.span),
2449 attrs: attrs.into(),
2451 is_placeholder: false,
2453 TrailingToken::MaybeComma,
2458 /// Check for `=`. This means the source incorrectly attempts to
2459 /// initialize a field with an eq rather than a colon.
2460 fn error_on_eq_field_init(&self, field_name: Ident) {
2461 if self.token != token::Eq {
2465 self.struct_span_err(self.token.span, "expected `:`, found `=`")
2467 field_name.span.shrink_to_hi().to(self.token.span),
2468 "replace equals symbol with a colon",
2470 Applicability::MachineApplicable,
2475 fn err_dotdotdot_syntax(&self, span: Span) {
2476 self.struct_span_err(span, "unexpected token: `...`")
2479 "use `..` for an exclusive range",
2481 Applicability::MaybeIncorrect,
2485 "or `..=` for an inclusive range",
2487 Applicability::MaybeIncorrect,
2492 fn err_larrow_operator(&self, span: Span) {
2493 self.struct_span_err(span, "unexpected token: `<-`")
2496 "if you meant to write a comparison against a negative value, add a \
2497 space in between `<` and `-`",
2499 Applicability::MaybeIncorrect,
2504 fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2505 ExprKind::AssignOp(binop, lhs, rhs)
2510 start: Option<P<Expr>>,
2511 end: Option<P<Expr>>,
2512 limits: RangeLimits,
2514 if end.is_none() && limits == RangeLimits::Closed {
2515 self.error_inclusive_range_with_no_end(self.prev_token.span);
2518 ExprKind::Range(start, end, limits)
2522 fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
2523 ExprKind::Unary(unop, expr)
2526 fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2527 ExprKind::Binary(binop, lhs, rhs)
2530 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
2531 ExprKind::Index(expr, idx)
2534 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
2535 ExprKind::Call(f, args)
2538 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> P<Expr> {
2539 let span = lo.to(self.prev_token.span);
2540 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), AttrVec::new());
2541 self.recover_from_await_method_call();
2545 crate fn mk_expr(&self, span: Span, kind: ExprKind, attrs: AttrVec) -> P<Expr> {
2546 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None })
2549 pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
2550 self.mk_expr(span, ExprKind::Err, AttrVec::new())
2553 /// Create expression span ensuring the span of the parent node
2554 /// is larger than the span of lhs and rhs, including the attributes.
2555 fn mk_expr_sp(&self, lhs: &P<Expr>, lhs_span: Span, rhs_span: Span) -> Span {
2558 .find(|a| a.style == AttrStyle::Outer)
2559 .map_or(lhs_span, |a| a.span)
2563 fn collect_tokens_for_expr(
2566 f: impl FnOnce(&mut Self, Vec<ast::Attribute>) -> PResult<'a, P<Expr>>,
2567 ) -> PResult<'a, P<Expr>> {
2568 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2569 let res = f(this, attrs)?;
2570 let trailing = if this.restrictions.contains(Restrictions::STMT_EXPR)
2571 && this.token.kind == token::Semi
2575 // FIXME - pass this through from the place where we know
2576 // we need a comma, rather than assuming that `#[attr] expr,`
2577 // always captures a trailing comma
2578 TrailingToken::MaybeComma