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.check_path() {
1112 self.parse_path_start_expr(attrs)
1113 } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
1114 self.parse_closure_expr(attrs)
1115 } else if self.eat_keyword(kw::If) {
1116 self.parse_if_expr(attrs)
1117 } else if self.check_keyword(kw::For) {
1118 if self.choose_generics_over_qpath(1) {
1119 // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery,
1120 // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns.
1121 // When `for <Foo as Bar>::Proj in $expr $block` is wanted,
1122 // you can disambiguate in favor of a pattern with `(...)`.
1123 self.recover_quantified_closure_expr(attrs)
1125 assert!(self.eat_keyword(kw::For));
1126 self.parse_for_expr(None, self.prev_token.span, attrs)
1128 } else if self.eat_keyword(kw::While) {
1129 self.parse_while_expr(None, self.prev_token.span, attrs)
1130 } else if let Some(label) = self.eat_label() {
1131 self.parse_labeled_expr(label, attrs, true)
1132 } else if self.eat_keyword(kw::Loop) {
1133 self.parse_loop_expr(None, self.prev_token.span, attrs)
1134 } else if self.eat_keyword(kw::Continue) {
1135 let kind = ExprKind::Continue(self.eat_label());
1136 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1137 } else if self.eat_keyword(kw::Match) {
1138 let match_sp = self.prev_token.span;
1139 self.parse_match_expr(attrs).map_err(|mut err| {
1140 err.span_label(match_sp, "while parsing this match expression");
1143 } else if self.eat_keyword(kw::Unsafe) {
1144 self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs)
1145 } else if self.check_inline_const(0) {
1146 self.parse_const_block(lo.to(self.token.span))
1147 } else if self.is_do_catch_block() {
1148 self.recover_do_catch(attrs)
1149 } else if self.is_try_block() {
1150 self.expect_keyword(kw::Try)?;
1151 self.parse_try_block(lo, attrs)
1152 } else if self.eat_keyword(kw::Return) {
1153 self.parse_return_expr(attrs)
1154 } else if self.eat_keyword(kw::Break) {
1155 self.parse_break_expr(attrs)
1156 } else if self.eat_keyword(kw::Yield) {
1157 self.parse_yield_expr(attrs)
1158 } else if self.eat_keyword(kw::Let) {
1159 self.parse_let_expr(attrs)
1160 } else if self.eat_keyword(kw::Underscore) {
1161 self.sess.gated_spans.gate(sym::destructuring_assignment, self.prev_token.span);
1162 Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore, attrs))
1163 } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1164 // Don't complain about bare semicolons after unclosed braces
1165 // recovery in order to keep the error count down. Fixing the
1166 // delimiters will possibly also fix the bare semicolon found in
1167 // expression context. For example, silence the following error:
1169 // error: expected expression, found `;`
1173 // | ^ expected expression
1175 Ok(self.mk_expr_err(self.token.span))
1176 } else if self.token.uninterpolated_span().rust_2018() {
1177 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1178 if self.check_keyword(kw::Async) {
1179 if self.is_async_block() {
1180 // Check for `async {` and `async move {`.
1181 self.parse_async_block(attrs)
1183 self.parse_closure_expr(attrs)
1185 } else if self.eat_keyword(kw::Await) {
1186 self.recover_incorrect_await_syntax(lo, self.prev_token.span, attrs)
1188 self.parse_lit_expr(attrs)
1191 self.parse_lit_expr(attrs)
1195 fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1196 let lo = self.token.span;
1197 match self.parse_opt_lit() {
1199 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs);
1200 self.maybe_recover_from_bad_qpath(expr, true)
1202 None => self.try_macro_suggestion(),
1206 fn parse_tuple_parens_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1207 let lo = self.token.span;
1208 self.expect(&token::OpenDelim(token::Paren))?;
1209 let (es, trailing_comma) = match self.parse_seq_to_end(
1210 &token::CloseDelim(token::Paren),
1211 SeqSep::trailing_allowed(token::Comma),
1212 |p| p.parse_expr_catch_underscore(),
1215 Err(err) => return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err))),
1217 let kind = if es.len() == 1 && !trailing_comma {
1218 // `(e)` is parenthesized `e`.
1219 ExprKind::Paren(es.into_iter().next().unwrap())
1221 // `(e,)` is a tuple with only one field, `e`.
1224 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1225 self.maybe_recover_from_bad_qpath(expr, true)
1228 fn parse_array_or_repeat_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1229 let lo = self.token.span;
1232 let close = &token::CloseDelim(token::Bracket);
1233 let kind = if self.eat(close) {
1235 ExprKind::Array(Vec::new())
1238 let first_expr = self.parse_expr()?;
1239 if self.eat(&token::Semi) {
1240 // Repeating array syntax: `[ 0; 512 ]`
1241 let count = self.parse_anon_const_expr()?;
1242 self.expect(close)?;
1243 ExprKind::Repeat(first_expr, count)
1244 } else if self.eat(&token::Comma) {
1245 // Vector with two or more elements.
1246 let sep = SeqSep::trailing_allowed(token::Comma);
1247 let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1248 let mut exprs = vec![first_expr];
1249 exprs.extend(remaining_exprs);
1250 ExprKind::Array(exprs)
1252 // Vector with one element
1253 self.expect(close)?;
1254 ExprKind::Array(vec![first_expr])
1257 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1258 self.maybe_recover_from_bad_qpath(expr, true)
1261 fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1262 let (qself, path) = if self.eat_lt() {
1263 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
1266 (None, self.parse_path(PathStyle::Expr)?)
1270 // `!`, as an operator, is prefix, so we know this isn't that.
1271 let (hi, kind) = if self.eat(&token::Not) {
1272 // MACRO INVOCATION expression
1273 if qself.is_some() {
1274 self.struct_span_err(path.span, "macros cannot use qualified paths").emit();
1278 args: self.parse_mac_args()?,
1279 prior_type_ascription: self.last_type_ascription,
1281 (self.prev_token.span, ExprKind::MacCall(mac))
1282 } else if self.check(&token::OpenDelim(token::Brace)) {
1283 if let Some(expr) = self.maybe_parse_struct_expr(qself.as_ref(), &path, &attrs) {
1284 if qself.is_some() {
1285 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
1289 (path.span, ExprKind::Path(qself, path))
1292 (path.span, ExprKind::Path(qself, path))
1295 let expr = self.mk_expr(lo.to(hi), kind, attrs);
1296 self.maybe_recover_from_bad_qpath(expr, true)
1299 /// Parse `'label: $expr`. The label is already parsed.
1300 fn parse_labeled_expr(
1304 consume_colon: bool,
1305 ) -> PResult<'a, P<Expr>> {
1306 let lo = label.ident.span;
1307 let label = Some(label);
1308 let ate_colon = self.eat(&token::Colon);
1309 let expr = if self.eat_keyword(kw::While) {
1310 self.parse_while_expr(label, lo, attrs)
1311 } else if self.eat_keyword(kw::For) {
1312 self.parse_for_expr(label, lo, attrs)
1313 } else if self.eat_keyword(kw::Loop) {
1314 self.parse_loop_expr(label, lo, attrs)
1315 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1316 self.parse_block_expr(label, lo, BlockCheckMode::Default, attrs)
1318 let msg = "expected `while`, `for`, `loop` or `{` after a label";
1319 self.struct_span_err(self.token.span, msg).span_label(self.token.span, msg).emit();
1320 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1324 if !ate_colon && consume_colon {
1325 self.error_labeled_expr_must_be_followed_by_colon(lo, expr.span);
1331 fn error_labeled_expr_must_be_followed_by_colon(&self, lo: Span, span: Span) {
1332 self.struct_span_err(span, "labeled expression must be followed by `:`")
1333 .span_label(lo, "the label")
1334 .span_suggestion_short(
1336 "add `:` after the label",
1338 Applicability::MachineApplicable,
1340 .note("labels are used before loops and blocks, allowing e.g., `break 'label` to them")
1344 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1345 fn recover_do_catch(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1346 let lo = self.token.span;
1348 self.bump(); // `do`
1349 self.bump(); // `catch`
1351 let span_dc = lo.to(self.prev_token.span);
1352 self.struct_span_err(span_dc, "found removed `do catch` syntax")
1355 "replace with the new syntax",
1357 Applicability::MachineApplicable,
1359 .note("following RFC #2388, the new non-placeholder syntax is `try`")
1362 self.parse_try_block(lo, attrs)
1365 /// Parse an expression if the token can begin one.
1366 fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1367 Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1370 /// Parse `"return" expr?`.
1371 fn parse_return_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1372 let lo = self.prev_token.span;
1373 let kind = ExprKind::Ret(self.parse_expr_opt()?);
1374 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1375 self.maybe_recover_from_bad_qpath(expr, true)
1378 /// Parse `"('label ":")? break expr?`.
1379 fn parse_break_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1380 let lo = self.prev_token.span;
1381 let label = self.eat_label();
1382 let kind = if self.token != token::OpenDelim(token::Brace)
1383 || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1385 self.parse_expr_opt()?
1389 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind), attrs);
1390 self.maybe_recover_from_bad_qpath(expr, true)
1393 /// Parse `"yield" expr?`.
1394 fn parse_yield_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1395 let lo = self.prev_token.span;
1396 let kind = ExprKind::Yield(self.parse_expr_opt()?);
1397 let span = lo.to(self.prev_token.span);
1398 self.sess.gated_spans.gate(sym::generators, span);
1399 let expr = self.mk_expr(span, kind, attrs);
1400 self.maybe_recover_from_bad_qpath(expr, true)
1403 /// Returns a string literal if the next token is a string literal.
1404 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1405 /// and returns `None` if the next token is not literal at all.
1406 pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
1407 match self.parse_opt_lit() {
1408 Some(lit) => match lit.kind {
1409 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1411 symbol: lit.token.symbol,
1412 suffix: lit.token.suffix,
1416 _ => Err(Some(lit)),
1422 pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> {
1423 self.parse_opt_lit().ok_or_else(|| {
1424 let msg = format!("unexpected token: {}", super::token_descr(&self.token));
1425 self.struct_span_err(self.token.span, &msg)
1429 /// Matches `lit = true | false | token_lit`.
1430 /// Returns `None` if the next token is not a literal.
1431 pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
1432 let mut recovered = None;
1433 if self.token == token::Dot {
1434 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1435 // dot would follow an optional literal, so we do this unconditionally.
1436 recovered = self.look_ahead(1, |next_token| {
1437 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1440 if self.token.span.hi() == next_token.span.lo() {
1441 let s = String::from("0.") + &symbol.as_str();
1442 let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1443 return Some(Token::new(kind, self.token.span.to(next_token.span)));
1448 if let Some(token) = &recovered {
1450 self.error_float_lits_must_have_int_part(&token);
1454 let token = recovered.as_ref().unwrap_or(&self.token);
1455 match Lit::from_token(token) {
1460 Err(LitError::NotLiteral) => None,
1462 let span = token.span;
1463 let lit = match token.kind {
1464 token::Literal(lit) => lit,
1465 _ => unreachable!(),
1468 self.report_lit_error(err, lit, span);
1469 // Pack possible quotes and prefixes from the original literal into
1470 // the error literal's symbol so they can be pretty-printed faithfully.
1471 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1472 let symbol = Symbol::intern(&suffixless_lit.to_string());
1473 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1474 Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!()))
1479 fn error_float_lits_must_have_int_part(&self, token: &Token) {
1480 self.struct_span_err(token.span, "float literals must have an integer part")
1483 "must have an integer part",
1484 pprust::token_to_string(token),
1485 Applicability::MachineApplicable,
1490 fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) {
1491 // Checks if `s` looks like i32 or u1234 etc.
1492 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1493 s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
1496 let token::Lit { kind, suffix, .. } = lit;
1498 // `NotLiteral` is not an error by itself, so we don't report
1499 // it and give the parser opportunity to try something else.
1500 LitError::NotLiteral => {}
1501 // `LexerError` *is* an error, but it was already reported
1502 // by lexer, so here we don't report it the second time.
1503 LitError::LexerError => {}
1504 LitError::InvalidSuffix => {
1505 self.expect_no_suffix(
1507 &format!("{} {} literal", kind.article(), kind.descr()),
1511 LitError::InvalidIntSuffix => {
1512 let suf = suffix.expect("suffix error with no suffix").as_str();
1513 if looks_like_width_suffix(&['i', 'u'], &suf) {
1514 // If it looks like a width, try to be helpful.
1515 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
1516 self.struct_span_err(span, &msg)
1517 .help("valid widths are 8, 16, 32, 64 and 128")
1520 let msg = format!("invalid suffix `{}` for number literal", suf);
1521 self.struct_span_err(span, &msg)
1522 .span_label(span, format!("invalid suffix `{}`", suf))
1523 .help("the suffix must be one of the numeric types (`u32`, `isize`, `f32`, etc.)")
1527 LitError::InvalidFloatSuffix => {
1528 let suf = suffix.expect("suffix error with no suffix").as_str();
1529 if looks_like_width_suffix(&['f'], &suf) {
1530 // If it looks like a width, try to be helpful.
1531 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
1532 self.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit();
1534 let msg = format!("invalid suffix `{}` for float literal", suf);
1535 self.struct_span_err(span, &msg)
1536 .span_label(span, format!("invalid suffix `{}`", suf))
1537 .help("valid suffixes are `f32` and `f64`")
1541 LitError::NonDecimalFloat(base) => {
1542 let descr = match base {
1543 16 => "hexadecimal",
1546 _ => unreachable!(),
1548 self.struct_span_err(span, &format!("{} float literal is not supported", descr))
1549 .span_label(span, "not supported")
1552 LitError::IntTooLarge => {
1553 self.struct_span_err(span, "integer literal is too large").emit();
1558 pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) {
1559 if let Some(suf) = suffix {
1560 let mut err = if kind == "a tuple index"
1561 && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf)
1563 // #59553: warn instead of reject out of hand to allow the fix to percolate
1564 // through the ecosystem when people fix their macros
1568 .struct_span_warn(sp, &format!("suffixes on {} are invalid", kind));
1570 "`{}` is *temporarily* accepted on tuple index fields as it was \
1571 incorrectly accepted on stable for a few releases",
1575 "on proc macros, you'll want to use `syn::Index::from` or \
1576 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1577 to tuple field access",
1580 "see issue #60210 <https://github.com/rust-lang/rust/issues/60210> \
1581 for more information",
1585 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1587 err.span_label(sp, format!("invalid suffix `{}`", suf));
1592 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1593 /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
1594 pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1595 maybe_whole_expr!(self);
1597 let lo = self.token.span;
1598 let minus_present = self.eat(&token::BinOp(token::Minus));
1599 let lit = self.parse_lit()?;
1600 let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new());
1604 lo.to(self.prev_token.span),
1605 self.mk_unary(UnOp::Neg, expr),
1613 /// Parses a block or unsafe block.
1614 pub(super) fn parse_block_expr(
1616 opt_label: Option<Label>,
1618 blk_mode: BlockCheckMode,
1620 ) -> PResult<'a, P<Expr>> {
1621 if let Some(label) = opt_label {
1622 self.sess.gated_spans.gate(sym::label_break_value, label.ident.span);
1625 if self.token.is_whole_block() {
1626 self.struct_span_err(self.token.span, "cannot use a `block` macro fragment here")
1627 .span_label(lo.to(self.token.span), "the `block` fragment is within this context")
1631 let (inner_attrs, blk) = self.parse_block_common(lo, blk_mode)?;
1632 attrs.extend(inner_attrs);
1633 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs))
1636 /// Recover on an explicitly quantified closure expression, e.g., `for<'a> |x: &'a u8| *x + 1`.
1637 fn recover_quantified_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1638 let lo = self.token.span;
1639 let _ = self.parse_late_bound_lifetime_defs()?;
1640 let span_for = lo.to(self.prev_token.span);
1641 let closure = self.parse_closure_expr(attrs)?;
1643 self.struct_span_err(span_for, "cannot introduce explicit parameters for a closure")
1644 .span_label(closure.span, "the parameters are attached to this closure")
1647 "remove the parameters",
1649 Applicability::MachineApplicable,
1653 Ok(self.mk_expr_err(lo.to(closure.span)))
1656 /// Parses a closure expression (e.g., `move |args| expr`).
1657 fn parse_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1658 let lo = self.token.span;
1661 if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
1663 let asyncness = if self.token.uninterpolated_span().rust_2018() {
1664 self.parse_asyncness()
1669 let capture_clause = self.parse_capture_clause()?;
1670 let decl = self.parse_fn_block_decl()?;
1671 let decl_hi = self.prev_token.span;
1672 let body = match decl.output {
1673 FnRetTy::Default(_) => {
1674 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
1675 self.parse_expr_res(restrictions, None)?
1678 // If an explicit return type is given, require a block to appear (RFC 968).
1679 let body_lo = self.token.span;
1680 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, AttrVec::new())?
1684 if let Async::Yes { span, .. } = asyncness {
1685 // Feature-gate `async ||` closures.
1686 self.sess.gated_spans.gate(sym::async_closure, span);
1691 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
1696 /// Parses an optional `move` prefix to a closure-like construct.
1697 fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> {
1698 if self.eat_keyword(kw::Move) {
1699 // Check for `move async` and recover
1700 if self.check_keyword(kw::Async) {
1701 let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
1702 Err(self.incorrect_move_async_order_found(move_async_span))
1704 Ok(CaptureBy::Value)
1711 /// Parses the `|arg, arg|` header of a closure.
1712 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
1713 let inputs = if self.eat(&token::OrOr) {
1716 self.expect(&token::BinOp(token::Or))?;
1718 .parse_seq_to_before_tokens(
1719 &[&token::BinOp(token::Or), &token::OrOr],
1720 SeqSep::trailing_allowed(token::Comma),
1721 TokenExpectType::NoExpect,
1722 |p| p.parse_fn_block_param(),
1729 self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes, RecoverReturnSign::Yes)?;
1731 Ok(P(FnDecl { inputs, output }))
1734 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1735 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
1736 let lo = self.token.span;
1737 let attrs = self.parse_outer_attributes()?;
1738 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1739 let pat = this.parse_pat_no_top_alt(PARAM_EXPECTED)?;
1740 let ty = if this.eat(&token::Colon) {
1743 this.mk_ty(this.prev_token.span, TyKind::Infer)
1748 attrs: attrs.into(),
1751 span: lo.to(this.token.span),
1753 is_placeholder: false,
1755 TrailingToken::MaybeComma,
1760 /// Parses an `if` expression (`if` token already eaten).
1761 fn parse_if_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1762 let lo = self.prev_token.span;
1763 let cond = self.parse_cond_expr()?;
1765 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1766 // verify that the last statement is either an implicit return (no `;`) or an explicit
1767 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1768 // the dead code lint.
1769 let thn = if self.eat_keyword(kw::Else) || !cond.returns() {
1770 self.error_missing_if_cond(lo, cond.span)
1772 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
1773 let not_block = self.token != token::OpenDelim(token::Brace);
1774 let block = self.parse_block().map_err(|mut err| {
1776 err.span_label(lo, "this `if` expression has a condition, but no block");
1777 if let ExprKind::Binary(_, _, ref right) = cond.kind {
1778 if let ExprKind::Block(_, _) = right.kind {
1779 err.help("maybe you forgot the right operand of the condition?");
1785 self.error_on_if_block_attrs(lo, false, block.span, &attrs);
1788 let els = if self.eat_keyword(kw::Else) { Some(self.parse_else_expr()?) } else { None };
1789 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els), attrs))
1792 fn error_missing_if_cond(&self, lo: Span, span: Span) -> P<ast::Block> {
1793 let sp = self.sess.source_map().next_point(lo);
1794 self.struct_span_err(sp, "missing condition for `if` expression")
1795 .span_label(sp, "expected if condition here")
1797 self.mk_block_err(span)
1800 /// Parses the condition of a `if` or `while` expression.
1801 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
1802 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1804 if let ExprKind::Let(..) = cond.kind {
1805 // Remove the last feature gating of a `let` expression since it's stable.
1806 self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
1812 /// Parses a `let $pat = $expr` pseudo-expression.
1813 /// The `let` token has already been eaten.
1814 fn parse_let_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1815 let lo = self.prev_token.span;
1816 let pat = self.parse_pat_allow_top_alt(None, RecoverComma::Yes)?;
1817 self.expect(&token::Eq)?;
1818 let expr = self.with_res(self.restrictions | Restrictions::NO_STRUCT_LITERAL, |this| {
1819 this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
1821 let span = lo.to(expr.span);
1822 self.sess.gated_spans.gate(sym::let_chains, span);
1823 Ok(self.mk_expr(span, ExprKind::Let(pat, expr), attrs))
1826 /// Parses an `else { ... }` expression (`else` token already eaten).
1827 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
1828 let ctx_span = self.prev_token.span; // `else`
1829 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
1830 let expr = if self.eat_keyword(kw::If) {
1831 self.parse_if_expr(AttrVec::new())?
1833 let blk = self.parse_block()?;
1834 self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new())
1836 self.error_on_if_block_attrs(ctx_span, true, expr.span, &attrs);
1840 fn error_on_if_block_attrs(
1845 attrs: &[ast::Attribute],
1847 let (span, last) = match attrs {
1849 [x0 @ xn] | [x0, .., xn] => (x0.span.to(xn.span), xn.span),
1851 let ctx = if is_ctx_else { "else" } else { "if" };
1852 self.struct_span_err(last, "outer attributes are not allowed on `if` and `else` branches")
1853 .span_label(branch_span, "the attributes are attached to this branch")
1854 .span_label(ctx_span, format!("the branch belongs to this `{}`", ctx))
1857 "remove the attributes",
1859 Applicability::MachineApplicable,
1864 /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
1867 opt_label: Option<Label>,
1870 ) -> PResult<'a, P<Expr>> {
1871 // Record whether we are about to parse `for (`.
1872 // This is used below for recovery in case of `for ( $stuff ) $block`
1873 // in which case we will suggest `for $stuff $block`.
1874 let begin_paren = match self.token.kind {
1875 token::OpenDelim(token::Paren) => Some(self.token.span),
1879 let pat = self.parse_pat_allow_top_alt(None, RecoverComma::Yes)?;
1880 if !self.eat_keyword(kw::In) {
1881 self.error_missing_in_for_loop();
1883 self.check_for_for_in_in_typo(self.prev_token.span);
1884 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1886 let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
1888 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
1889 attrs.extend(iattrs);
1891 let kind = ExprKind::ForLoop(pat, expr, loop_block, opt_label);
1892 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1895 fn error_missing_in_for_loop(&mut self) {
1896 let (span, msg, sugg) = if self.token.is_ident_named(sym::of) {
1897 // Possibly using JS syntax (#75311).
1898 let span = self.token.span;
1900 (span, "try using `in` here instead", "in")
1902 (self.prev_token.span.between(self.token.span), "try adding `in` here", " in ")
1904 self.struct_span_err(span, "missing `in` in `for` loop")
1905 .span_suggestion_short(
1909 // Has been misleading, at least in the past (closed Issue #48492).
1910 Applicability::MaybeIncorrect,
1915 /// Parses a `while` or `while let` expression (`while` token already eaten).
1916 fn parse_while_expr(
1918 opt_label: Option<Label>,
1921 ) -> PResult<'a, P<Expr>> {
1922 let cond = self.parse_cond_expr()?;
1923 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1924 attrs.extend(iattrs);
1925 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::While(cond, body, opt_label), attrs))
1928 /// Parses `loop { ... }` (`loop` token already eaten).
1931 opt_label: Option<Label>,
1934 ) -> PResult<'a, P<Expr>> {
1935 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1936 attrs.extend(iattrs);
1937 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::Loop(body, opt_label), attrs))
1940 fn eat_label(&mut self) -> Option<Label> {
1941 self.token.lifetime().map(|ident| {
1947 /// Parses a `match ... { ... }` expression (`match` token already eaten).
1948 fn parse_match_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1949 let match_span = self.prev_token.span;
1950 let lo = self.prev_token.span;
1951 let scrutinee = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1952 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
1953 if self.token == token::Semi {
1954 e.span_suggestion_short(
1956 "try removing this `match`",
1958 Applicability::MaybeIncorrect, // speculative
1964 let mut arms: Vec<Arm> = Vec::new();
1965 while self.token != token::CloseDelim(token::Brace) {
1966 match self.parse_arm() {
1967 Ok(arm) => arms.push(arm),
1969 // Recover by skipping to the end of the block.
1971 self.recover_stmt();
1972 let span = lo.to(self.token.span);
1973 if self.token == token::CloseDelim(token::Brace) {
1976 return Ok(self.mk_expr(span, ExprKind::Match(scrutinee, arms), attrs));
1980 let hi = self.token.span;
1982 Ok(self.mk_expr(lo.to(hi), ExprKind::Match(scrutinee, arms), attrs))
1985 /// Attempt to recover from match arm body with statements and no surrounding braces.
1986 fn parse_arm_body_missing_braces(
1988 first_expr: &P<Expr>,
1990 ) -> Option<P<Expr>> {
1991 if self.token.kind != token::Semi {
1994 let start_snapshot = self.clone();
1995 let semi_sp = self.token.span;
1998 vec![self.mk_stmt(first_expr.span, ast::StmtKind::Expr(first_expr.clone()))];
1999 let err = |this: &mut Parser<'_>, stmts: Vec<ast::Stmt>| {
2000 let span = stmts[0].span.to(stmts[stmts.len() - 1].span);
2001 let mut err = this.struct_span_err(span, "`match` arm body without braces");
2002 let (these, s, are) =
2003 if stmts.len() > 1 { ("these", "s", "are") } else { ("this", "", "is") };
2007 "{these} statement{s} {are} not surrounded by a body",
2013 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2014 if stmts.len() > 1 {
2015 err.multipart_suggestion(
2016 &format!("surround the statement{} with a body", s),
2018 (span.shrink_to_lo(), "{ ".to_string()),
2019 (span.shrink_to_hi(), " }".to_string()),
2021 Applicability::MachineApplicable,
2024 err.span_suggestion(
2026 "use a comma to end a `match` arm expression",
2028 Applicability::MachineApplicable,
2032 this.mk_expr_err(span)
2034 // We might have either a `,` -> `;` typo, or a block without braces. We need
2035 // a more subtle parsing strategy.
2037 if self.token.kind == token::CloseDelim(token::Brace) {
2038 // We have reached the closing brace of the `match` expression.
2039 return Some(err(self, stmts));
2041 if self.token.kind == token::Comma {
2042 *self = start_snapshot;
2045 let pre_pat_snapshot = self.clone();
2046 match self.parse_pat_no_top_alt(None) {
2048 if self.token.kind == token::FatArrow {
2050 *self = pre_pat_snapshot;
2051 return Some(err(self, stmts));
2059 *self = pre_pat_snapshot;
2060 match self.parse_stmt_without_recovery(true, ForceCollect::No) {
2061 // Consume statements for as long as possible.
2066 *self = start_snapshot;
2069 // We couldn't parse either yet another statement missing it's
2070 // enclosing block nor the next arm's pattern or closing brace.
2071 Err(mut stmt_err) => {
2073 *self = start_snapshot;
2081 pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
2082 let attrs = self.parse_outer_attributes()?;
2083 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2084 let lo = this.token.span;
2085 let pat = this.parse_pat_allow_top_alt(None, RecoverComma::Yes)?;
2086 let guard = if this.eat_keyword(kw::If) {
2087 let if_span = this.prev_token.span;
2088 let cond = this.parse_expr()?;
2089 if let ExprKind::Let(..) = cond.kind {
2090 // Remove the last feature gating of a `let` expression since it's stable.
2091 this.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2092 let span = if_span.to(cond.span);
2093 this.sess.gated_spans.gate(sym::if_let_guard, span);
2099 let arrow_span = this.token.span;
2100 this.expect(&token::FatArrow)?;
2101 let arm_start_span = this.token.span;
2103 let expr = this.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| {
2104 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2108 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
2109 && this.token != token::CloseDelim(token::Brace);
2111 let hi = this.prev_token.span;
2114 let sm = this.sess.source_map();
2115 if let Some(body) = this.parse_arm_body_missing_braces(&expr, arrow_span) {
2116 let span = body.span;
2125 is_placeholder: false,
2127 TrailingToken::None,
2130 this.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]).map_err(
2132 match (sm.span_to_lines(expr.span), sm.span_to_lines(arm_start_span)) {
2133 (Ok(ref expr_lines), Ok(ref arm_start_lines))
2134 if arm_start_lines.lines[0].end_col
2135 == expr_lines.lines[0].end_col
2136 && expr_lines.lines.len() == 2
2137 && this.token == token::FatArrow =>
2139 // We check whether there's any trailing code in the parse span,
2140 // if there isn't, we very likely have the following:
2143 // | -- - missing comma
2147 // | - ^^ self.token.span
2149 // | parsed until here as `"y" & X`
2150 err.span_suggestion_short(
2151 arm_start_span.shrink_to_hi(),
2152 "missing a comma here to end this `match` arm",
2154 Applicability::MachineApplicable,
2160 "while parsing the `match` arm starting here",
2168 this.eat(&token::Comma);
2179 is_placeholder: false,
2181 TrailingToken::None,
2186 /// Parses a `try {...}` expression (`try` token already eaten).
2187 fn parse_try_block(&mut self, span_lo: Span, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2188 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2189 attrs.extend(iattrs);
2190 if self.eat_keyword(kw::Catch) {
2191 let mut error = self.struct_span_err(
2192 self.prev_token.span,
2193 "keyword `catch` cannot follow a `try` block",
2195 error.help("try using `match` on the result of the `try` block instead");
2199 let span = span_lo.to(body.span);
2200 self.sess.gated_spans.gate(sym::try_blocks, span);
2201 Ok(self.mk_expr(span, ExprKind::TryBlock(body), attrs))
2205 fn is_do_catch_block(&self) -> bool {
2206 self.token.is_keyword(kw::Do)
2207 && self.is_keyword_ahead(1, &[kw::Catch])
2208 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2209 && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
2212 fn is_try_block(&self) -> bool {
2213 self.token.is_keyword(kw::Try)
2214 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2215 && self.token.uninterpolated_span().rust_2018()
2218 /// Parses an `async move? {...}` expression.
2219 fn parse_async_block(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2220 let lo = self.token.span;
2221 self.expect_keyword(kw::Async)?;
2222 let capture_clause = self.parse_capture_clause()?;
2223 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2224 attrs.extend(iattrs);
2225 let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);
2226 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
2229 fn is_async_block(&self) -> bool {
2230 self.token.is_keyword(kw::Async)
2233 self.is_keyword_ahead(1, &[kw::Move])
2234 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2237 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2241 fn is_certainly_not_a_block(&self) -> bool {
2242 self.look_ahead(1, |t| t.is_ident())
2244 // `{ ident, ` cannot start a block.
2245 self.look_ahead(2, |t| t == &token::Comma)
2246 || self.look_ahead(2, |t| t == &token::Colon)
2248 // `{ ident: token, ` cannot start a block.
2249 self.look_ahead(4, |t| t == &token::Comma) ||
2250 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
2251 self.look_ahead(3, |t| !t.can_begin_type())
2256 fn maybe_parse_struct_expr(
2258 qself: Option<&ast::QSelf>,
2261 ) -> Option<PResult<'a, P<Expr>>> {
2262 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2263 if struct_allowed || self.is_certainly_not_a_block() {
2264 if let Err(err) = self.expect(&token::OpenDelim(token::Brace)) {
2265 return Some(Err(err));
2267 let expr = self.parse_struct_expr(qself.cloned(), path.clone(), attrs.clone(), true);
2268 if let (Ok(expr), false) = (&expr, struct_allowed) {
2269 // This is a struct literal, but we don't can't accept them here.
2270 self.error_struct_lit_not_allowed_here(path.span, expr.span);
2277 fn error_struct_lit_not_allowed_here(&self, lo: Span, sp: Span) {
2278 self.struct_span_err(sp, "struct literals are not allowed here")
2279 .multipart_suggestion(
2280 "surround the struct literal with parentheses",
2281 vec![(lo.shrink_to_lo(), "(".to_string()), (sp.shrink_to_hi(), ")".to_string())],
2282 Applicability::MachineApplicable,
2287 /// Precondition: already parsed the '{'.
2288 pub(super) fn parse_struct_expr(
2290 qself: Option<ast::QSelf>,
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 { qself, 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