1 use super::pat::{CommaRecoveryMode, RecoverColon, RecoverComma, PARAM_EXPECTED};
2 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
4 AttrWrapper, BlockMode, ClosureSpans, ForceCollect, Parser, PathStyle, Restrictions, TokenType,
6 use super::{SemiColonMode, SeqSep, TokenExpectType, TrailingToken};
7 use crate::maybe_recover_from_interpolated_ty_qpath;
9 use ast::token::DelimToken;
10 use rustc_ast::ptr::P;
11 use rustc_ast::token::{self, Token, TokenKind};
12 use rustc_ast::tokenstream::Spacing;
13 use rustc_ast::util::classify;
14 use rustc_ast::util::literal::LitError;
15 use rustc_ast::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity};
16 use rustc_ast::{self as ast, AttrStyle, AttrVec, CaptureBy, ExprField, Lit, UnOp, DUMMY_NODE_ID};
17 use rustc_ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty, TyKind};
18 use rustc_ast::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits};
19 use rustc_ast_pretty::pprust;
20 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, PResult};
21 use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP;
22 use rustc_session::lint::BuiltinLintDiagnostics;
23 use rustc_span::edition::LATEST_STABLE_EDITION;
24 use rustc_span::source_map::{self, Span, Spanned};
25 use rustc_span::symbol::{kw, sym, Ident, Symbol};
26 use rustc_span::{BytePos, Pos};
29 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
30 /// dropped into the token stream, which happens while parsing the result of
31 /// macro expansion). Placement of these is not as complex as I feared it would
32 /// be. The important thing is to make sure that lookahead doesn't balk at
33 /// `token::Interpolated` tokens.
34 macro_rules! maybe_whole_expr {
36 if let token::Interpolated(nt) = &$p.token.kind {
38 token::NtExpr(e) | token::NtLiteral(e) => {
43 token::NtPath(path) => {
44 let path = path.clone();
48 ExprKind::Path(None, path),
52 token::NtBlock(block) => {
53 let block = block.clone();
57 ExprKind::Block(block, None),
68 pub(super) enum LhsExpr {
70 AttributesParsed(AttrWrapper),
71 AlreadyParsed(P<Expr>),
74 impl From<Option<AttrWrapper>> for LhsExpr {
75 /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
76 /// and `None` into `LhsExpr::NotYetParsed`.
78 /// This conversion does not allocate.
79 fn from(o: Option<AttrWrapper>) -> Self {
80 if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed }
84 impl From<P<Expr>> for LhsExpr {
85 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
87 /// This conversion does not allocate.
88 fn from(expr: P<Expr>) -> Self {
89 LhsExpr::AlreadyParsed(expr)
94 /// Parses an expression.
96 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
97 self.current_closure.take();
99 self.parse_expr_res(Restrictions::empty(), None)
102 /// Parses an expression, forcing tokens to be collected
103 pub fn parse_expr_force_collect(&mut self) -> PResult<'a, P<Expr>> {
104 self.collect_tokens_no_attrs(|this| this.parse_expr())
107 pub fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> {
108 self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
111 fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P<Expr>> {
112 match self.parse_expr() {
113 Ok(expr) => Ok(expr),
114 Err(mut err) => match self.token.ident() {
115 Some((Ident { name: kw::Underscore, .. }, false))
116 if self.look_ahead(1, |t| t == &token::Comma) =>
118 // Special-case handling of `foo(_, _, _)`
121 Ok(self.mk_expr(self.prev_token.span, ExprKind::Err, AttrVec::new()))
128 /// Parses a sequence of expressions delimited by parentheses.
129 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
130 self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r)
133 /// Parses an expression, subject to the given restrictions.
135 pub(super) fn parse_expr_res(
138 already_parsed_attrs: Option<AttrWrapper>,
139 ) -> PResult<'a, P<Expr>> {
140 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
143 /// Parses an associative expression.
145 /// This parses an expression accounting for associativity and precedence of the operators in
150 already_parsed_attrs: Option<AttrWrapper>,
151 ) -> PResult<'a, P<Expr>> {
152 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
155 /// Parses an associative expression with operators of at least `min_prec` precedence.
156 pub(super) fn parse_assoc_expr_with(
160 ) -> PResult<'a, P<Expr>> {
161 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
164 let attrs = match lhs {
165 LhsExpr::AttributesParsed(attrs) => Some(attrs),
168 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
169 return self.parse_prefix_range_expr(attrs);
171 self.parse_prefix_expr(attrs)?
174 let last_type_ascription_set = self.last_type_ascription.is_some();
176 if !self.should_continue_as_assoc_expr(&lhs) {
177 self.last_type_ascription = None;
181 self.expected_tokens.push(TokenType::Operator);
182 while let Some(op) = self.check_assoc_op() {
183 // Adjust the span for interpolated LHS to point to the `$lhs` token
184 // and not to what it refers to.
185 let lhs_span = match self.prev_token.kind {
186 TokenKind::Interpolated(..) => self.prev_token.span,
190 let cur_op_span = self.token.span;
191 let restrictions = if op.node.is_assign_like() {
192 self.restrictions & Restrictions::NO_STRUCT_LITERAL
196 let prec = op.node.precedence();
200 // Check for deprecated `...` syntax
201 if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq {
202 self.err_dotdotdot_syntax(self.token.span);
205 if self.token == token::LArrow {
206 self.err_larrow_operator(self.token.span);
210 if op.node.is_comparison() {
211 if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
216 // Look for JS' `===` and `!==` and recover
217 if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual)
218 && self.token.kind == token::Eq
219 && self.prev_token.span.hi() == self.token.span.lo()
221 let sp = op.span.to(self.token.span);
222 let sugg = match op.node {
223 AssocOp::Equal => "==",
224 AssocOp::NotEqual => "!=",
227 self.struct_span_err(sp, &format!("invalid comparison operator `{}=`", sugg))
228 .span_suggestion_short(
230 &format!("`{s}=` is not a valid comparison operator, use `{s}`", s = sugg),
232 Applicability::MachineApplicable,
238 // Look for PHP's `<>` and recover
239 if op.node == AssocOp::Less
240 && self.token.kind == token::Gt
241 && self.prev_token.span.hi() == self.token.span.lo()
243 let sp = op.span.to(self.token.span);
244 self.struct_span_err(sp, "invalid comparison operator `<>`")
245 .span_suggestion_short(
247 "`<>` is not a valid comparison operator, use `!=`",
249 Applicability::MachineApplicable,
255 // Look for C++'s `<=>` and recover
256 if op.node == AssocOp::LessEqual
257 && self.token.kind == token::Gt
258 && self.prev_token.span.hi() == self.token.span.lo()
260 let sp = op.span.to(self.token.span);
261 self.struct_span_err(sp, "invalid comparison operator `<=>`")
264 "`<=>` is not a valid comparison operator, use `std::cmp::Ordering`",
272 if op == AssocOp::As {
273 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
275 } else if op == AssocOp::Colon {
276 lhs = self.parse_assoc_op_ascribe(lhs, lhs_span)?;
278 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
279 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
280 // generalise it to the Fixity::None code.
281 lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?;
285 let fixity = op.fixity();
286 let prec_adjustment = match fixity {
289 // We currently have no non-associative operators that are not handled above by
290 // the special cases. The code is here only for future convenience.
293 let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
294 this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
297 let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span);
310 | AssocOp::ShiftRight
316 | AssocOp::GreaterEqual => {
317 let ast_op = op.to_ast_binop().unwrap();
318 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
319 self.mk_expr(span, binary, AttrVec::new())
322 self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span), AttrVec::new())
324 AssocOp::AssignOp(k) => {
326 token::Plus => BinOpKind::Add,
327 token::Minus => BinOpKind::Sub,
328 token::Star => BinOpKind::Mul,
329 token::Slash => BinOpKind::Div,
330 token::Percent => BinOpKind::Rem,
331 token::Caret => BinOpKind::BitXor,
332 token::And => BinOpKind::BitAnd,
333 token::Or => BinOpKind::BitOr,
334 token::Shl => BinOpKind::Shl,
335 token::Shr => BinOpKind::Shr,
337 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
338 self.mk_expr(span, aopexpr, AttrVec::new())
340 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
341 self.span_bug(span, "AssocOp should have been handled by special case")
345 if let Fixity::None = fixity {
349 if last_type_ascription_set {
350 self.last_type_ascription = None;
355 fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
356 match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) {
357 // Semi-statement forms are odd:
358 // See https://github.com/rust-lang/rust/issues/29071
359 (true, None) => false,
360 (false, _) => true, // Continue parsing the expression.
361 // An exhaustive check is done in the following block, but these are checked first
362 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
363 // want to keep their span info to improve diagnostics in these cases in a later stage.
364 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
365 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
366 (true, Some(AssocOp::Add)) // `{ 42 } + 42
367 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
368 // `if x { a } else { b } && if y { c } else { d }`
369 if !self.look_ahead(1, |t| t.is_used_keyword()) => {
370 // These cases are ambiguous and can't be identified in the parser alone.
371 let sp = self.sess.source_map().start_point(self.token.span);
372 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
375 (true, Some(AssocOp::LAnd)) |
376 (true, Some(AssocOp::LOr)) |
377 (true, Some(AssocOp::BitOr)) => {
378 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`. Separated from the
379 // above due to #74233.
380 // These cases are ambiguous and can't be identified in the parser alone.
382 // Bitwise AND is left out because guessing intent is hard. We can make
383 // suggestions based on the assumption that double-refs are rarely intentional,
384 // and closures are distinct enough that they don't get mixed up with their
386 let sp = self.sess.source_map().start_point(self.token.span);
387 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
390 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => false,
392 self.error_found_expr_would_be_stmt(lhs);
398 /// We've found an expression that would be parsed as a statement,
399 /// but the next token implies this should be parsed as an expression.
400 /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
401 fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
402 let mut err = self.struct_span_err(
404 &format!("expected expression, found `{}`", pprust::token_to_string(&self.token),),
406 err.span_label(self.token.span, "expected expression");
407 self.sess.expr_parentheses_needed(&mut err, lhs.span);
411 /// Possibly translate the current token to an associative operator.
412 /// The method does not advance the current token.
414 /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
415 fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
416 let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
417 // When parsing const expressions, stop parsing when encountering `>`.
422 | AssocOp::GreaterEqual
423 | AssocOp::AssignOp(token::BinOpToken::Shr),
426 ) if self.restrictions.contains(Restrictions::CONST_EXPR) => {
429 (Some(op), _) => (op, self.token.span),
430 (None, Some((Ident { name: sym::and, span }, false))) => {
431 self.error_bad_logical_op("and", "&&", "conjunction");
432 (AssocOp::LAnd, span)
434 (None, Some((Ident { name: sym::or, span }, false))) => {
435 self.error_bad_logical_op("or", "||", "disjunction");
440 Some(source_map::respan(span, op))
443 /// Error on `and` and `or` suggesting `&&` and `||` respectively.
444 fn error_bad_logical_op(&self, bad: &str, good: &str, english: &str) {
445 self.struct_span_err(self.token.span, &format!("`{}` is not a logical operator", bad))
446 .span_suggestion_short(
448 &format!("use `{}` to perform logical {}", good, english),
450 Applicability::MachineApplicable,
452 .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators")
456 /// Checks if this expression is a successfully parsed statement.
457 fn expr_is_complete(&self, e: &Expr) -> bool {
458 self.restrictions.contains(Restrictions::STMT_EXPR)
459 && !classify::expr_requires_semi_to_be_stmt(e)
462 /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
463 /// The other two variants are handled in `parse_prefix_range_expr` below.
470 ) -> PResult<'a, P<Expr>> {
471 let rhs = if self.is_at_start_of_range_notation_rhs() {
472 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
476 let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
477 let span = self.mk_expr_sp(&lhs, lhs.span, rhs_span);
479 if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed };
480 let range = self.mk_range(Some(lhs), rhs, limits);
481 Ok(self.mk_expr(span, range, AttrVec::new()))
484 fn is_at_start_of_range_notation_rhs(&self) -> bool {
485 if self.token.can_begin_expr() {
486 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
487 if self.token == token::OpenDelim(token::Brace) {
488 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
496 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
497 fn parse_prefix_range_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
498 // Check for deprecated `...` syntax.
499 if self.token == token::DotDotDot {
500 self.err_dotdotdot_syntax(self.token.span);
504 [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
505 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
509 let limits = match self.token.kind {
510 token::DotDot => RangeLimits::HalfOpen,
511 _ => RangeLimits::Closed,
513 let op = AssocOp::from_token(&self.token);
514 // FIXME: `parse_prefix_range_expr` is called when the current
515 // token is `DotDot`, `DotDotDot`, or `DotDotEq`. If we haven't already
516 // parsed attributes, then trying to parse them here will always fail.
517 // We should figure out how we want attributes on range expressions to work.
518 let attrs = self.parse_or_use_outer_attributes(attrs)?;
519 self.collect_tokens_for_expr(attrs, |this, attrs| {
520 let lo = this.token.span;
522 let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() {
523 // RHS must be parsed with more associativity than the dots.
524 this.parse_assoc_expr_with(op.unwrap().precedence() + 1, LhsExpr::NotYetParsed)
525 .map(|x| (lo.to(x.span), Some(x)))?
529 let range = this.mk_range(None, opt_end, limits);
530 Ok(this.mk_expr(span, range, attrs.into()))
534 /// Parses a prefix-unary-operator expr.
535 fn parse_prefix_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
536 let attrs = self.parse_or_use_outer_attributes(attrs)?;
537 let lo = self.token.span;
539 macro_rules! make_it {
540 ($this:ident, $attrs:expr, |this, _| $body:expr) => {
541 $this.collect_tokens_for_expr($attrs, |$this, attrs| {
542 let (hi, ex) = $body?;
543 Ok($this.mk_expr(lo.to(hi), ex, attrs.into()))
550 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
551 match this.token.uninterpolate().kind {
552 token::Not => make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Not)), // `!expr`
553 token::Tilde => make_it!(this, attrs, |this, _| this.recover_tilde_expr(lo)), // `~expr`
554 token::BinOp(token::Minus) => {
555 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Neg))
557 token::BinOp(token::Star) => {
558 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Deref))
560 token::BinOp(token::And) | token::AndAnd => {
561 make_it!(this, attrs, |this, _| this.parse_borrow_expr(lo))
563 token::BinOp(token::Plus) if this.look_ahead(1, |tok| tok.is_numeric_lit()) => {
564 let mut err = this.struct_span_err(lo, "leading `+` is not supported");
565 err.span_label(lo, "unexpected `+`");
567 // a block on the LHS might have been intended to be an expression instead
568 if let Some(sp) = this.sess.ambiguous_block_expr_parse.borrow().get(&lo) {
569 this.sess.expr_parentheses_needed(&mut err, *sp);
571 err.span_suggestion_verbose(
573 "try removing the `+`",
575 Applicability::MachineApplicable,
581 this.parse_prefix_expr(None)
583 token::Ident(..) if this.token.is_keyword(kw::Box) => {
584 make_it!(this, attrs, |this, _| this.parse_box_expr(lo))
586 token::Ident(..) if this.is_mistaken_not_ident_negation() => {
587 make_it!(this, attrs, |this, _| this.recover_not_expr(lo))
589 _ => return this.parse_dot_or_call_expr(Some(attrs)),
593 fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P<Expr>)> {
595 let expr = self.parse_prefix_expr(None);
596 let (span, expr) = self.interpolated_or_expr_span(expr)?;
597 Ok((lo.to(span), expr))
600 fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
601 let (span, expr) = self.parse_prefix_expr_common(lo)?;
602 Ok((span, self.mk_unary(op, expr)))
605 // Recover on `!` suggesting for bitwise negation instead.
606 fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
607 self.struct_span_err(lo, "`~` cannot be used as a unary operator")
608 .span_suggestion_short(
610 "use `!` to perform bitwise not",
612 Applicability::MachineApplicable,
616 self.parse_unary_expr(lo, UnOp::Not)
619 /// Parse `box expr`.
620 fn parse_box_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
621 let (span, expr) = self.parse_prefix_expr_common(lo)?;
622 self.sess.gated_spans.gate(sym::box_syntax, span);
623 Ok((span, ExprKind::Box(expr)))
626 fn is_mistaken_not_ident_negation(&self) -> bool {
627 let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
628 // These tokens can start an expression after `!`, but
629 // can't continue an expression after an ident
630 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
631 token::Literal(..) | token::Pound => true,
632 _ => t.is_whole_expr(),
634 self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
637 /// Recover on `not expr` in favor of `!expr`.
638 fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
640 let not_token = self.look_ahead(1, |t| t.clone());
641 self.struct_span_err(
643 &format!("unexpected {} after identifier", super::token_descr(¬_token)),
645 .span_suggestion_short(
646 // Span the `not` plus trailing whitespace to avoid
647 // trailing whitespace after the `!` in our suggestion
648 self.sess.source_map().span_until_non_whitespace(lo.to(not_token.span)),
649 "use `!` to perform logical negation",
651 Applicability::MachineApplicable,
656 self.parse_unary_expr(lo, UnOp::Not)
659 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
660 fn interpolated_or_expr_span(
662 expr: PResult<'a, P<Expr>>,
663 ) -> PResult<'a, (Span, P<Expr>)> {
666 match self.prev_token.kind {
667 TokenKind::Interpolated(..) => self.prev_token.span,
675 fn parse_assoc_op_cast(
679 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind,
680 ) -> PResult<'a, P<Expr>> {
681 let mk_expr = |this: &mut Self, lhs: P<Expr>, rhs: P<Ty>| {
683 this.mk_expr_sp(&lhs, lhs_span, rhs.span),
689 // Save the state of the parser before parsing type normally, in case there is a
690 // LessThan comparison after this cast.
691 let parser_snapshot_before_type = self.clone();
692 let cast_expr = match self.parse_as_cast_ty() {
693 Ok(rhs) => mk_expr(self, lhs, rhs),
695 // Rewind to before attempting to parse the type with generics, to recover
696 // from situations like `x as usize < y` in which we first tried to parse
697 // `usize < y` as a type with generic arguments.
698 let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
700 // Check for typo of `'a: loop { break 'a }` with a missing `'`.
701 match (&lhs.kind, &self.token.kind) {
704 ExprKind::Path(None, ast::Path { segments, .. }),
705 TokenKind::Ident(kw::For | kw::Loop | kw::While, false),
706 ) if segments.len() == 1 => {
707 let snapshot = self.clone();
709 ident: Ident::from_str_and_span(
710 &format!("'{}", segments[0].ident),
711 segments[0].ident.span,
714 match self.parse_labeled_expr(label, AttrVec::new(), false) {
717 self.struct_span_err(label.ident.span, "malformed loop label")
720 "use the correct loop label format",
721 label.ident.to_string(),
722 Applicability::MachineApplicable,
736 match self.parse_path(PathStyle::Expr) {
738 let (op_noun, op_verb) = match self.token.kind {
739 token::Lt => ("comparison", "comparing"),
740 token::BinOp(token::Shl) => ("shift", "shifting"),
742 // We can end up here even without `<` being the next token, for
743 // example because `parse_ty_no_plus` returns `Err` on keywords,
744 // but `parse_path` returns `Ok` on them due to error recovery.
745 // Return original error and parser state.
746 *self = parser_snapshot_after_type;
747 return Err(type_err);
751 // Successfully parsed the type path leaving a `<` yet to parse.
754 // Report non-fatal diagnostics, keep `x as usize` as an expression
755 // in AST and continue parsing.
757 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
758 pprust::path_to_string(&path),
761 let span_after_type = parser_snapshot_after_type.token.span;
763 mk_expr(self, lhs, self.mk_ty(path.span, TyKind::Path(None, path)));
765 self.struct_span_err(self.token.span, &msg)
767 self.look_ahead(1, |t| t.span).to(span_after_type),
768 "interpreted as generic arguments",
770 .span_label(self.token.span, format!("not interpreted as {}", op_noun))
771 .multipart_suggestion(
772 &format!("try {} the cast value", op_verb),
774 (expr.span.shrink_to_lo(), "(".to_string()),
775 (expr.span.shrink_to_hi(), ")".to_string()),
777 Applicability::MachineApplicable,
784 // Couldn't parse as a path, return original error and parser state.
786 *self = parser_snapshot_after_type;
787 return Err(type_err);
793 self.parse_and_disallow_postfix_after_cast(cast_expr)
796 /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
797 /// then emits an error and returns the newly parsed tree.
798 /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
799 fn parse_and_disallow_postfix_after_cast(
802 ) -> PResult<'a, P<Expr>> {
803 // Save the memory location of expr before parsing any following postfix operators.
804 // This will be compared with the memory location of the output expression.
805 // If they different we can assume we parsed another expression because the existing expression is not reallocated.
806 let addr_before = &*cast_expr as *const _ as usize;
807 let span = cast_expr.span;
808 let with_postfix = self.parse_dot_or_call_expr_with_(cast_expr, span)?;
809 let changed = addr_before != &*with_postfix as *const _ as usize;
811 // Check if an illegal postfix operator has been added after the cast.
812 // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator.
813 if !matches!(with_postfix.kind, ExprKind::Cast(_, _) | ExprKind::Type(_, _)) || changed {
815 "casts cannot be followed by {}",
816 match with_postfix.kind {
817 ExprKind::Index(_, _) => "indexing",
818 ExprKind::Try(_) => "`?`",
819 ExprKind::Field(_, _) => "a field access",
820 ExprKind::MethodCall(_, _, _) => "a method call",
821 ExprKind::Call(_, _) => "a function call",
822 ExprKind::Await(_) => "`.await`",
823 ExprKind::Err => return Ok(with_postfix),
824 _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"),
827 let mut err = self.struct_span_err(span, &msg);
828 // If type ascription is "likely an error", the user will already be getting a useful
829 // help message, and doesn't need a second.
830 if self.last_type_ascription.map_or(false, |last_ascription| last_ascription.1) {
831 self.maybe_annotate_with_ascription(&mut err, false);
833 let suggestions = vec![
834 (span.shrink_to_lo(), "(".to_string()),
835 (span.shrink_to_hi(), ")".to_string()),
837 err.multipart_suggestion(
838 "try surrounding the expression in parentheses",
840 Applicability::MachineApplicable,
848 fn parse_assoc_op_ascribe(&mut self, lhs: P<Expr>, lhs_span: Span) -> PResult<'a, P<Expr>> {
849 let maybe_path = self.could_ascription_be_path(&lhs.kind);
850 self.last_type_ascription = Some((self.prev_token.span, maybe_path));
851 let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
852 self.sess.gated_spans.gate(sym::type_ascription, lhs.span);
856 /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
857 fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
859 let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
860 let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
861 let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo);
862 let expr = self.parse_prefix_expr(None);
863 let (hi, expr) = self.interpolated_or_expr_span(expr)?;
864 let span = lo.to(hi);
865 if let Some(lt) = lifetime {
866 self.error_remove_borrow_lifetime(span, lt.ident.span);
868 Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
871 fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
872 self.struct_span_err(span, "borrow expressions cannot be annotated with lifetimes")
873 .span_label(lt_span, "annotated with lifetime here")
876 "remove the lifetime annotation",
878 Applicability::MachineApplicable,
883 /// Parse `mut?` or `raw [ const | mut ]`.
884 fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) {
885 if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) {
886 // `raw [ const | mut ]`.
887 let found_raw = self.eat_keyword(kw::Raw);
889 let mutability = self.parse_const_or_mut().unwrap();
890 self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span));
891 (ast::BorrowKind::Raw, mutability)
894 (ast::BorrowKind::Ref, self.parse_mutability())
898 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
899 fn parse_dot_or_call_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
900 let attrs = self.parse_or_use_outer_attributes(attrs)?;
901 self.collect_tokens_for_expr(attrs, |this, attrs| {
902 let base = this.parse_bottom_expr();
903 let (span, base) = this.interpolated_or_expr_span(base)?;
904 this.parse_dot_or_call_expr_with(base, span, attrs)
908 pub(super) fn parse_dot_or_call_expr_with(
912 mut attrs: Vec<ast::Attribute>,
913 ) -> PResult<'a, P<Expr>> {
914 // Stitch the list of outer attributes onto the return value.
915 // A little bit ugly, but the best way given the current code
917 self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| {
918 expr.map(|mut expr| {
919 attrs.extend::<Vec<_>>(expr.attrs.into());
920 expr.attrs = attrs.into();
926 fn parse_dot_or_call_expr_with_(&mut self, mut e: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
928 if self.eat(&token::Question) {
930 e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e), AttrVec::new());
933 if self.eat(&token::Dot) {
935 e = self.parse_dot_suffix_expr(lo, e)?;
938 if self.expr_is_complete(&e) {
941 e = match self.token.kind {
942 token::OpenDelim(token::Paren) => self.parse_fn_call_expr(lo, e),
943 token::OpenDelim(token::Bracket) => self.parse_index_expr(lo, e)?,
949 fn look_ahead_type_ascription_as_field(&mut self) -> bool {
950 self.look_ahead(1, |t| t.is_ident())
951 && self.look_ahead(2, |t| t == &token::Colon)
952 && self.look_ahead(3, |t| t.can_begin_expr())
955 fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
956 match self.token.uninterpolate().kind {
957 token::Ident(..) => self.parse_dot_suffix(base, lo),
958 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
959 Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix, None))
961 token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => {
962 Ok(self.parse_tuple_field_access_expr_float(lo, base, symbol, suffix))
965 self.error_unexpected_after_dot();
971 fn error_unexpected_after_dot(&self) {
972 // FIXME Could factor this out into non_fatal_unexpected or something.
973 let actual = pprust::token_to_string(&self.token);
974 self.struct_span_err(self.token.span, &format!("unexpected token: `{}`", actual)).emit();
977 // We need an identifier or integer, but the next token is a float.
978 // Break the float into components to extract the identifier or integer.
979 // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
980 // parts unless those parts are processed immediately. `TokenCursor` should either
981 // support pushing "future tokens" (would be also helpful to `break_and_eat`), or
982 // we should break everything including floats into more basic proc-macro style
983 // tokens in the lexer (probably preferable).
984 fn parse_tuple_field_access_expr_float(
989 suffix: Option<Symbol>,
992 enum FloatComponent {
996 use FloatComponent::*;
998 let float_str = float.as_str();
999 let mut components = Vec::new();
1000 let mut ident_like = String::new();
1001 for c in float_str.chars() {
1002 if c == '_' || c.is_ascii_alphanumeric() {
1004 } else if matches!(c, '.' | '+' | '-') {
1005 if !ident_like.is_empty() {
1006 components.push(IdentLike(mem::take(&mut ident_like)));
1008 components.push(Punct(c));
1010 panic!("unexpected character in a float token: {:?}", c)
1013 if !ident_like.is_empty() {
1014 components.push(IdentLike(ident_like));
1017 // With proc macros the span can refer to anything, the source may be too short,
1018 // or too long, or non-ASCII. It only makes sense to break our span into components
1019 // if its underlying text is identical to our float literal.
1020 let span = self.token.span;
1021 let can_take_span_apart =
1022 || self.span_to_snippet(span).as_deref() == Ok(float_str).as_deref();
1024 match &*components {
1027 self.parse_tuple_field_access_expr(lo, base, Symbol::intern(&i), suffix, None)
1030 [IdentLike(i), Punct('.')] => {
1031 let (ident_span, dot_span) = if can_take_span_apart() {
1032 let (span, ident_len) = (span.data(), BytePos::from_usize(i.len()));
1033 let ident_span = span.with_hi(span.lo + ident_len);
1034 let dot_span = span.with_lo(span.lo + ident_len);
1035 (ident_span, dot_span)
1039 assert!(suffix.is_none());
1040 let symbol = Symbol::intern(&i);
1041 self.token = Token::new(token::Ident(symbol, false), ident_span);
1042 let next_token = (Token::new(token::Dot, dot_span), self.token_spacing);
1043 self.parse_tuple_field_access_expr(lo, base, symbol, None, Some(next_token))
1046 [IdentLike(i1), Punct('.'), IdentLike(i2)] => {
1047 let (ident1_span, dot_span, ident2_span) = if can_take_span_apart() {
1048 let (span, ident1_len) = (span.data(), BytePos::from_usize(i1.len()));
1049 let ident1_span = span.with_hi(span.lo + ident1_len);
1051 .with_lo(span.lo + ident1_len)
1052 .with_hi(span.lo + ident1_len + BytePos(1));
1053 let ident2_span = self.token.span.with_lo(span.lo + ident1_len + BytePos(1));
1054 (ident1_span, dot_span, ident2_span)
1058 let symbol1 = Symbol::intern(&i1);
1059 self.token = Token::new(token::Ident(symbol1, false), ident1_span);
1060 // This needs to be `Spacing::Alone` to prevent regressions.
1061 // See issue #76399 and PR #76285 for more details
1062 let next_token1 = (Token::new(token::Dot, dot_span), Spacing::Alone);
1064 self.parse_tuple_field_access_expr(lo, base, symbol1, None, Some(next_token1));
1065 let symbol2 = Symbol::intern(&i2);
1066 let next_token2 = Token::new(token::Ident(symbol2, false), ident2_span);
1067 self.bump_with((next_token2, self.token_spacing)); // `.`
1068 self.parse_tuple_field_access_expr(lo, base1, symbol2, suffix, None)
1070 // 1e+ | 1e- (recovered)
1071 [IdentLike(_), Punct('+' | '-')] |
1073 [IdentLike(_), Punct('+' | '-'), IdentLike(_)] |
1075 [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-')] |
1077 [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-'), IdentLike(_)] => {
1078 // See the FIXME about `TokenCursor` above.
1079 self.error_unexpected_after_dot();
1082 _ => panic!("unexpected components in a float token: {:?}", components),
1086 fn parse_tuple_field_access_expr(
1091 suffix: Option<Symbol>,
1092 next_token: Option<(Token, Spacing)>,
1095 Some(next_token) => self.bump_with(next_token),
1096 None => self.bump(),
1098 let span = self.prev_token.span;
1099 let field = ExprKind::Field(base, Ident::new(field, span));
1100 self.expect_no_suffix(span, "a tuple index", suffix);
1101 self.mk_expr(lo.to(span), field, AttrVec::new())
1104 /// Parse a function call expression, `expr(...)`.
1105 fn parse_fn_call_expr(&mut self, lo: Span, fun: P<Expr>) -> P<Expr> {
1106 let snapshot = if self.token.kind == token::OpenDelim(token::Paren)
1107 && self.look_ahead_type_ascription_as_field()
1109 Some((self.clone(), fun.kind.clone()))
1113 let open_paren = self.token.span;
1115 let mut seq = self.parse_paren_expr_seq().map(|args| {
1116 self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args), AttrVec::new())
1119 self.maybe_recover_struct_lit_bad_delims(lo, open_paren, &mut seq, snapshot)
1123 self.recover_seq_parse_error(token::Paren, lo, seq)
1126 /// If we encounter a parser state that looks like the user has written a `struct` literal with
1127 /// parentheses instead of braces, recover the parser state and provide suggestions.
1128 #[instrument(skip(self, seq, snapshot), level = "trace")]
1129 fn maybe_recover_struct_lit_bad_delims(
1133 seq: &mut PResult<'a, P<Expr>>,
1134 snapshot: Option<(Self, ExprKind)>,
1135 ) -> Option<P<Expr>> {
1136 match (seq.as_mut(), snapshot) {
1137 (Err(err), Some((mut snapshot, ExprKind::Path(None, path)))) => {
1138 let name = pprust::path_to_string(&path);
1139 snapshot.bump(); // `(`
1140 match snapshot.parse_struct_fields(path, false, token::Paren) {
1141 Ok((fields, ..)) if snapshot.eat(&token::CloseDelim(token::Paren)) => {
1142 // We are certain we have `Enum::Foo(a: 3, b: 4)`, suggest
1143 // `Enum::Foo { a: 3, b: 4 }` or `Enum::Foo(3, 4)`.
1145 let close_paren = self.prev_token.span;
1146 let span = lo.to(self.prev_token.span);
1147 if !fields.is_empty() {
1148 let replacement_err = self.struct_span_err(
1150 "invalid `struct` delimiters or `fn` call arguments",
1152 mem::replace(err, replacement_err).cancel();
1154 err.multipart_suggestion(
1155 &format!("if `{}` is a struct, use braces as delimiters", name),
1157 (open_paren, " { ".to_string()),
1158 (close_paren, " }".to_string()),
1160 Applicability::MaybeIncorrect,
1162 err.multipart_suggestion(
1163 &format!("if `{}` is a function, use the arguments directly", name),
1166 .map(|field| (field.span.until(field.expr.span), String::new()))
1168 Applicability::MaybeIncorrect,
1174 return Some(self.mk_expr_err(span));
1187 /// Parse an indexing expression `expr[...]`.
1188 fn parse_index_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
1190 let index = self.parse_expr()?;
1191 self.expect(&token::CloseDelim(token::Bracket))?;
1192 Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_index(base, index), AttrVec::new()))
1195 /// Assuming we have just parsed `.`, continue parsing into an expression.
1196 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
1197 if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) {
1198 return Ok(self.mk_await_expr(self_arg, lo));
1201 let fn_span_lo = self.token.span;
1202 let mut segment = self.parse_path_segment(PathStyle::Expr, None)?;
1203 self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(token::Paren)]);
1204 self.check_turbofish_missing_angle_brackets(&mut segment);
1206 if self.check(&token::OpenDelim(token::Paren)) {
1207 // Method call `expr.f()`
1208 let mut args = self.parse_paren_expr_seq()?;
1209 args.insert(0, self_arg);
1211 let fn_span = fn_span_lo.to(self.prev_token.span);
1212 let span = lo.to(self.prev_token.span);
1213 Ok(self.mk_expr(span, ExprKind::MethodCall(segment, args, fn_span), AttrVec::new()))
1215 // Field access `expr.f`
1216 if let Some(args) = segment.args {
1217 self.struct_span_err(
1219 "field expressions cannot have generic arguments",
1224 let span = lo.to(self.prev_token.span);
1225 Ok(self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), AttrVec::new()))
1229 /// At the bottom (top?) of the precedence hierarchy,
1230 /// Parses things like parenthesized exprs, macros, `return`, etc.
1232 /// N.B., this does not parse outer attributes, and is private because it only works
1233 /// correctly if called from `parse_dot_or_call_expr()`.
1234 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1235 maybe_recover_from_interpolated_ty_qpath!(self, true);
1236 maybe_whole_expr!(self);
1238 // Outer attributes are already parsed and will be
1239 // added to the return value after the fact.
1241 // Therefore, prevent sub-parser from parsing
1242 // attributes by giving them an empty "already-parsed" list.
1243 let attrs = AttrVec::new();
1245 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
1246 let lo = self.token.span;
1247 if let token::Literal(_) = self.token.kind {
1248 // This match arm is a special-case of the `_` match arm below and
1249 // could be removed without changing functionality, but it's faster
1250 // to have it here, especially for programs with large constants.
1251 self.parse_lit_expr(attrs)
1252 } else if self.check(&token::OpenDelim(token::Paren)) {
1253 self.parse_tuple_parens_expr(attrs)
1254 } else if self.check(&token::OpenDelim(token::Brace)) {
1255 self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs)
1256 } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) {
1257 self.parse_closure_expr(attrs).map_err(|mut err| {
1258 // If the input is something like `if a { 1 } else { 2 } | if a { 3 } else { 4 }`
1259 // then suggest parens around the lhs.
1260 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&lo) {
1261 self.sess.expr_parentheses_needed(&mut err, *sp);
1265 } else if self.check(&token::OpenDelim(token::Bracket)) {
1266 self.parse_array_or_repeat_expr(attrs, token::Bracket)
1267 } else if self.check_path() {
1268 self.parse_path_start_expr(attrs)
1269 } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
1270 self.parse_closure_expr(attrs)
1271 } else if self.eat_keyword(kw::If) {
1272 self.parse_if_expr(attrs)
1273 } else if self.check_keyword(kw::For) {
1274 if self.choose_generics_over_qpath(1) {
1275 // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery,
1276 // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns.
1277 // When `for <Foo as Bar>::Proj in $expr $block` is wanted,
1278 // you can disambiguate in favor of a pattern with `(...)`.
1279 self.recover_quantified_closure_expr(attrs)
1281 assert!(self.eat_keyword(kw::For));
1282 self.parse_for_expr(None, self.prev_token.span, attrs)
1284 } else if self.eat_keyword(kw::While) {
1285 self.parse_while_expr(None, self.prev_token.span, attrs)
1286 } else if let Some(label) = self.eat_label() {
1287 self.parse_labeled_expr(label, attrs, true)
1288 } else if self.eat_keyword(kw::Loop) {
1289 let sp = self.prev_token.span;
1290 self.parse_loop_expr(None, self.prev_token.span, attrs).map_err(|mut err| {
1291 err.span_label(sp, "while parsing this `loop` expression");
1294 } else if self.eat_keyword(kw::Continue) {
1295 let kind = ExprKind::Continue(self.eat_label());
1296 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1297 } else if self.eat_keyword(kw::Match) {
1298 let match_sp = self.prev_token.span;
1299 self.parse_match_expr(attrs).map_err(|mut err| {
1300 err.span_label(match_sp, "while parsing this `match` expression");
1303 } else if self.eat_keyword(kw::Unsafe) {
1304 let sp = self.prev_token.span;
1305 self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs)
1306 .map_err(|mut err| {
1307 err.span_label(sp, "while parsing this `unsafe` expression");
1310 } else if self.check_inline_const(0) {
1311 self.parse_const_block(lo.to(self.token.span), false)
1312 } else if self.is_do_catch_block() {
1313 self.recover_do_catch(attrs)
1314 } else if self.is_try_block() {
1315 self.expect_keyword(kw::Try)?;
1316 self.parse_try_block(lo, attrs)
1317 } else if self.eat_keyword(kw::Return) {
1318 self.parse_return_expr(attrs)
1319 } else if self.eat_keyword(kw::Break) {
1320 self.parse_break_expr(attrs)
1321 } else if self.eat_keyword(kw::Yield) {
1322 self.parse_yield_expr(attrs)
1323 } else if self.eat_keyword(kw::Let) {
1324 self.parse_let_expr(attrs)
1325 } else if self.eat_keyword(kw::Underscore) {
1326 Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore, attrs))
1327 } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1328 // Don't complain about bare semicolons after unclosed braces
1329 // recovery in order to keep the error count down. Fixing the
1330 // delimiters will possibly also fix the bare semicolon found in
1331 // expression context. For example, silence the following error:
1333 // error: expected expression, found `;`
1337 // | ^ expected expression
1339 Ok(self.mk_expr_err(self.token.span))
1340 } else if self.token.uninterpolated_span().rust_2018() {
1341 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1342 if self.check_keyword(kw::Async) {
1343 if self.is_async_block() {
1344 // Check for `async {` and `async move {`.
1345 self.parse_async_block(attrs)
1347 self.parse_closure_expr(attrs)
1349 } else if self.eat_keyword(kw::Await) {
1350 self.recover_incorrect_await_syntax(lo, self.prev_token.span, attrs)
1352 self.parse_lit_expr(attrs)
1355 self.parse_lit_expr(attrs)
1359 fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1360 let lo = self.token.span;
1361 match self.parse_opt_lit() {
1363 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs);
1364 self.maybe_recover_from_bad_qpath(expr, true)
1366 None => self.try_macro_suggestion(),
1370 fn parse_tuple_parens_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1371 let lo = self.token.span;
1372 self.expect(&token::OpenDelim(token::Paren))?;
1373 let (es, trailing_comma) = match self.parse_seq_to_end(
1374 &token::CloseDelim(token::Paren),
1375 SeqSep::trailing_allowed(token::Comma),
1376 |p| p.parse_expr_catch_underscore(),
1379 Err(err) => return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err))),
1381 let kind = if es.len() == 1 && !trailing_comma {
1382 // `(e)` is parenthesized `e`.
1383 ExprKind::Paren(es.into_iter().next().unwrap())
1385 // `(e,)` is a tuple with only one field, `e`.
1388 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1389 self.maybe_recover_from_bad_qpath(expr, true)
1392 fn parse_array_or_repeat_expr(
1395 close_delim: token::DelimToken,
1396 ) -> PResult<'a, P<Expr>> {
1397 let lo = self.token.span;
1398 self.bump(); // `[` or other open delim
1400 let close = &token::CloseDelim(close_delim);
1401 let kind = if self.eat(close) {
1403 ExprKind::Array(Vec::new())
1406 let first_expr = self.parse_expr()?;
1407 if self.eat(&token::Semi) {
1408 // Repeating array syntax: `[ 0; 512 ]`
1409 let count = self.parse_anon_const_expr()?;
1410 self.expect(close)?;
1411 ExprKind::Repeat(first_expr, count)
1412 } else if self.eat(&token::Comma) {
1413 // Vector with two or more elements.
1414 let sep = SeqSep::trailing_allowed(token::Comma);
1415 let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1416 let mut exprs = vec![first_expr];
1417 exprs.extend(remaining_exprs);
1418 ExprKind::Array(exprs)
1420 // Vector with one element
1421 self.expect(close)?;
1422 ExprKind::Array(vec![first_expr])
1425 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1426 self.maybe_recover_from_bad_qpath(expr, true)
1429 fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1430 let (qself, path) = if self.eat_lt() {
1431 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
1434 (None, self.parse_path(PathStyle::Expr)?)
1438 // `!`, as an operator, is prefix, so we know this isn't that.
1439 let (hi, kind) = if self.eat(&token::Not) {
1440 // MACRO INVOCATION expression
1441 if qself.is_some() {
1442 self.struct_span_err(path.span, "macros cannot use qualified paths").emit();
1446 args: self.parse_mac_args()?,
1447 prior_type_ascription: self.last_type_ascription,
1449 (self.prev_token.span, ExprKind::MacCall(mac))
1450 } else if self.check(&token::OpenDelim(token::Brace)) {
1451 if let Some(expr) = self.maybe_parse_struct_expr(qself.as_ref(), &path, &attrs) {
1452 if qself.is_some() {
1453 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
1457 (path.span, ExprKind::Path(qself, path))
1460 (path.span, ExprKind::Path(qself, path))
1463 let expr = self.mk_expr(lo.to(hi), kind, attrs);
1464 self.maybe_recover_from_bad_qpath(expr, true)
1467 /// Parse `'label: $expr`. The label is already parsed.
1468 fn parse_labeled_expr(
1472 mut consume_colon: bool,
1473 ) -> PResult<'a, P<Expr>> {
1474 let lo = label.ident.span;
1475 let label = Some(label);
1476 let ate_colon = self.eat(&token::Colon);
1477 let expr = if self.eat_keyword(kw::While) {
1478 self.parse_while_expr(label, lo, attrs)
1479 } else if self.eat_keyword(kw::For) {
1480 self.parse_for_expr(label, lo, attrs)
1481 } else if self.eat_keyword(kw::Loop) {
1482 self.parse_loop_expr(label, lo, attrs)
1483 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1484 self.parse_block_expr(label, lo, BlockCheckMode::Default, attrs)
1485 } else if !ate_colon && (self.check(&TokenKind::Comma) || self.check(&TokenKind::Gt)) {
1486 // We're probably inside of a `Path<'a>` that needs a turbofish
1487 let msg = "expected `while`, `for`, `loop` or `{` after a label";
1488 self.struct_span_err(self.token.span, msg).span_label(self.token.span, msg).emit();
1489 consume_colon = false;
1490 Ok(self.mk_expr_err(lo))
1492 let msg = "expected `while`, `for`, `loop` or `{` after a label";
1493 self.struct_span_err(self.token.span, msg).span_label(self.token.span, msg).emit();
1494 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1498 if !ate_colon && consume_colon {
1499 self.error_labeled_expr_must_be_followed_by_colon(lo, expr.span);
1505 fn error_labeled_expr_must_be_followed_by_colon(&self, lo: Span, span: Span) {
1506 self.struct_span_err(span, "labeled expression must be followed by `:`")
1507 .span_label(lo, "the label")
1508 .span_suggestion_short(
1510 "add `:` after the label",
1512 Applicability::MachineApplicable,
1514 .note("labels are used before loops and blocks, allowing e.g., `break 'label` to them")
1518 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1519 fn recover_do_catch(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1520 let lo = self.token.span;
1522 self.bump(); // `do`
1523 self.bump(); // `catch`
1525 let span_dc = lo.to(self.prev_token.span);
1526 self.struct_span_err(span_dc, "found removed `do catch` syntax")
1529 "replace with the new syntax",
1531 Applicability::MachineApplicable,
1533 .note("following RFC #2388, the new non-placeholder syntax is `try`")
1536 self.parse_try_block(lo, attrs)
1539 /// Parse an expression if the token can begin one.
1540 fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1541 Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1544 /// Parse `"return" expr?`.
1545 fn parse_return_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1546 let lo = self.prev_token.span;
1547 let kind = ExprKind::Ret(self.parse_expr_opt()?);
1548 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1549 self.maybe_recover_from_bad_qpath(expr, true)
1552 /// Parse `"break" (('label (:? expr)?) | expr?)` with `"break"` token already eaten.
1553 /// If the label is followed immediately by a `:` token, the label and `:` are
1554 /// parsed as part of the expression (i.e. a labeled loop). The language team has
1555 /// decided in #87026 to require parentheses as a visual aid to avoid confusion if
1556 /// the break expression of an unlabeled break is a labeled loop (as in
1557 /// `break 'lbl: loop {}`); a labeled break with an unlabeled loop as its value
1558 /// expression only gets a warning for compatibility reasons; and a labeled break
1559 /// with a labeled loop does not even get a warning because there is no ambiguity.
1560 fn parse_break_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1561 let lo = self.prev_token.span;
1562 let mut label = self.eat_label();
1563 let kind = if label.is_some() && self.token == token::Colon {
1564 // The value expression can be a labeled loop, see issue #86948, e.g.:
1565 // `loop { break 'label: loop { break 'label 42; }; }`
1566 let lexpr = self.parse_labeled_expr(label.take().unwrap(), AttrVec::new(), true)?;
1567 self.struct_span_err(
1569 "parentheses are required around this expression to avoid confusion with a labeled break expression",
1571 .multipart_suggestion(
1572 "wrap the expression in parentheses",
1574 (lexpr.span.shrink_to_lo(), "(".to_string()),
1575 (lexpr.span.shrink_to_hi(), ")".to_string()),
1577 Applicability::MachineApplicable,
1581 } else if self.token != token::OpenDelim(token::Brace)
1582 || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1584 let expr = self.parse_expr_opt()?;
1585 if let Some(ref expr) = expr {
1589 ExprKind::While(_, _, None)
1590 | ExprKind::ForLoop(_, _, _, None)
1591 | ExprKind::Loop(_, None)
1592 | ExprKind::Block(_, None)
1595 self.sess.buffer_lint_with_diagnostic(
1596 BREAK_WITH_LABEL_AND_LOOP,
1599 "this labeled break expression is easy to confuse with an unlabeled break with a labeled value expression",
1600 BuiltinLintDiagnostics::BreakWithLabelAndLoop(expr.span),
1608 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind), attrs);
1609 self.maybe_recover_from_bad_qpath(expr, true)
1612 /// Parse `"yield" expr?`.
1613 fn parse_yield_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1614 let lo = self.prev_token.span;
1615 let kind = ExprKind::Yield(self.parse_expr_opt()?);
1616 let span = lo.to(self.prev_token.span);
1617 self.sess.gated_spans.gate(sym::generators, span);
1618 let expr = self.mk_expr(span, kind, attrs);
1619 self.maybe_recover_from_bad_qpath(expr, true)
1622 /// Returns a string literal if the next token is a string literal.
1623 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1624 /// and returns `None` if the next token is not literal at all.
1625 pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
1626 match self.parse_opt_lit() {
1627 Some(lit) => match lit.kind {
1628 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1630 symbol: lit.token.symbol,
1631 suffix: lit.token.suffix,
1635 _ => Err(Some(lit)),
1641 pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> {
1642 self.parse_opt_lit().ok_or_else(|| {
1643 if let token::Interpolated(inner) = &self.token.kind {
1644 let expr = match inner.as_ref() {
1645 token::NtExpr(expr) => Some(expr),
1646 token::NtLiteral(expr) => Some(expr),
1649 if let Some(expr) = expr {
1650 if matches!(expr.kind, ExprKind::Err) {
1653 .struct_span_err(self.token.span, &"invalid interpolated expression");
1654 err.downgrade_to_delayed_bug();
1659 let msg = format!("unexpected token: {}", super::token_descr(&self.token));
1660 self.struct_span_err(self.token.span, &msg)
1664 /// Matches `lit = true | false | token_lit`.
1665 /// Returns `None` if the next token is not a literal.
1666 pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
1667 let mut recovered = None;
1668 if self.token == token::Dot {
1669 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1670 // dot would follow an optional literal, so we do this unconditionally.
1671 recovered = self.look_ahead(1, |next_token| {
1672 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1675 if self.token.span.hi() == next_token.span.lo() {
1676 let s = String::from("0.") + symbol.as_str();
1677 let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1678 return Some(Token::new(kind, self.token.span.to(next_token.span)));
1683 if let Some(token) = &recovered {
1685 self.error_float_lits_must_have_int_part(&token);
1689 let token = recovered.as_ref().unwrap_or(&self.token);
1690 match Lit::from_token(token) {
1695 Err(LitError::NotLiteral) => None,
1697 let span = token.span;
1698 let token::Literal(lit) = token.kind else {
1702 self.report_lit_error(err, lit, span);
1703 // Pack possible quotes and prefixes from the original literal into
1704 // the error literal's symbol so they can be pretty-printed faithfully.
1705 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1706 let symbol = Symbol::intern(&suffixless_lit.to_string());
1707 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1708 Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!()))
1713 fn error_float_lits_must_have_int_part(&self, token: &Token) {
1714 self.struct_span_err(token.span, "float literals must have an integer part")
1717 "must have an integer part",
1718 pprust::token_to_string(token).into(),
1719 Applicability::MachineApplicable,
1724 fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) {
1725 // Checks if `s` looks like i32 or u1234 etc.
1726 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1727 s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
1730 // Try to lowercase the prefix if it's a valid base prefix.
1731 fn fix_base_capitalisation(s: &str) -> Option<String> {
1732 if let Some(stripped) = s.strip_prefix('B') {
1733 Some(format!("0b{stripped}"))
1734 } else if let Some(stripped) = s.strip_prefix('O') {
1735 Some(format!("0o{stripped}"))
1736 } else if let Some(stripped) = s.strip_prefix('X') {
1737 Some(format!("0x{stripped}"))
1743 let token::Lit { kind, suffix, .. } = lit;
1745 // `NotLiteral` is not an error by itself, so we don't report
1746 // it and give the parser opportunity to try something else.
1747 LitError::NotLiteral => {}
1748 // `LexerError` *is* an error, but it was already reported
1749 // by lexer, so here we don't report it the second time.
1750 LitError::LexerError => {}
1751 LitError::InvalidSuffix => {
1752 self.expect_no_suffix(
1754 &format!("{} {} literal", kind.article(), kind.descr()),
1758 LitError::InvalidIntSuffix => {
1759 let suf = suffix.expect("suffix error with no suffix");
1760 let suf = suf.as_str();
1761 if looks_like_width_suffix(&['i', 'u'], &suf) {
1762 // If it looks like a width, try to be helpful.
1763 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
1764 self.struct_span_err(span, &msg)
1765 .help("valid widths are 8, 16, 32, 64 and 128")
1767 } else if let Some(fixed) = fix_base_capitalisation(suf) {
1768 let msg = "invalid base prefix for number literal";
1770 self.struct_span_err(span, &msg)
1771 .note("base prefixes (`0xff`, `0b1010`, `0o755`) are lowercase")
1774 "try making the prefix lowercase",
1776 Applicability::MaybeIncorrect,
1780 let msg = format!("invalid suffix `{}` for number literal", suf);
1781 self.struct_span_err(span, &msg)
1782 .span_label(span, format!("invalid suffix `{}`", suf))
1783 .help("the suffix must be one of the numeric types (`u32`, `isize`, `f32`, etc.)")
1787 LitError::InvalidFloatSuffix => {
1788 let suf = suffix.expect("suffix error with no suffix");
1789 let suf = suf.as_str();
1790 if looks_like_width_suffix(&['f'], suf) {
1791 // If it looks like a width, try to be helpful.
1792 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
1793 self.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit();
1795 let msg = format!("invalid suffix `{}` for float literal", suf);
1796 self.struct_span_err(span, &msg)
1797 .span_label(span, format!("invalid suffix `{}`", suf))
1798 .help("valid suffixes are `f32` and `f64`")
1802 LitError::NonDecimalFloat(base) => {
1803 let descr = match base {
1804 16 => "hexadecimal",
1807 _ => unreachable!(),
1809 self.struct_span_err(span, &format!("{} float literal is not supported", descr))
1810 .span_label(span, "not supported")
1813 LitError::IntTooLarge => {
1814 self.struct_span_err(span, "integer literal is too large").emit();
1819 pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) {
1820 if let Some(suf) = suffix {
1821 let mut err = if kind == "a tuple index"
1822 && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf)
1824 // #59553: warn instead of reject out of hand to allow the fix to percolate
1825 // through the ecosystem when people fix their macros
1829 .struct_span_warn(sp, &format!("suffixes on {} are invalid", kind));
1831 "`{}` is *temporarily* accepted on tuple index fields as it was \
1832 incorrectly accepted on stable for a few releases",
1836 "on proc macros, you'll want to use `syn::Index::from` or \
1837 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1838 to tuple field access",
1841 "see issue #60210 <https://github.com/rust-lang/rust/issues/60210> \
1842 for more information",
1846 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1849 err.span_label(sp, format!("invalid suffix `{}`", suf));
1854 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1855 /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
1856 pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1857 maybe_whole_expr!(self);
1859 let lo = self.token.span;
1860 let minus_present = self.eat(&token::BinOp(token::Minus));
1861 let lit = self.parse_lit()?;
1862 let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new());
1866 lo.to(self.prev_token.span),
1867 self.mk_unary(UnOp::Neg, expr),
1875 fn is_array_like_block(&mut self) -> bool {
1876 self.look_ahead(1, |t| matches!(t.kind, TokenKind::Ident(..) | TokenKind::Literal(_)))
1877 && self.look_ahead(2, |t| t == &token::Comma)
1878 && self.look_ahead(3, |t| t.can_begin_expr())
1881 /// Emits a suggestion if it looks like the user meant an array but
1882 /// accidentally used braces, causing the code to be interpreted as a block
1884 fn maybe_suggest_brackets_instead_of_braces(
1888 ) -> Option<P<Expr>> {
1889 let mut snapshot = self.clone();
1890 match snapshot.parse_array_or_repeat_expr(attrs, token::Brace) {
1892 let hi = snapshot.prev_token.span;
1893 self.struct_span_err(
1895 "this code is interpreted as a block expression, not an array",
1897 .multipart_suggestion(
1898 "try using [] instead of {}",
1899 vec![(lo, "[".to_owned()), (hi, "]".to_owned())],
1900 Applicability::MaybeIncorrect,
1902 .note("to define an array, one would use square brackets instead of curly braces")
1906 Some(self.mk_expr_err(arr.span))
1915 /// Parses a block or unsafe block.
1916 pub(super) fn parse_block_expr(
1918 opt_label: Option<Label>,
1920 blk_mode: BlockCheckMode,
1922 ) -> PResult<'a, P<Expr>> {
1923 if self.is_array_like_block() {
1924 if let Some(arr) = self.maybe_suggest_brackets_instead_of_braces(lo, attrs.clone()) {
1929 if let Some(label) = opt_label {
1930 self.sess.gated_spans.gate(sym::label_break_value, label.ident.span);
1933 if self.token.is_whole_block() {
1934 self.struct_span_err(self.token.span, "cannot use a `block` macro fragment here")
1935 .span_label(lo.to(self.token.span), "the `block` fragment is within this context")
1939 let (inner_attrs, blk) = self.parse_block_common(lo, blk_mode)?;
1940 attrs.extend(inner_attrs);
1941 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs))
1944 /// Recover on an explicitly quantified closure expression, e.g., `for<'a> |x: &'a u8| *x + 1`.
1945 fn recover_quantified_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1946 let lo = self.token.span;
1947 let _ = self.parse_late_bound_lifetime_defs()?;
1948 let span_for = lo.to(self.prev_token.span);
1949 let closure = self.parse_closure_expr(attrs)?;
1951 self.struct_span_err(span_for, "cannot introduce explicit parameters for a closure")
1952 .span_label(closure.span, "the parameters are attached to this closure")
1955 "remove the parameters",
1957 Applicability::MachineApplicable,
1961 Ok(self.mk_expr_err(lo.to(closure.span)))
1964 /// Parses a closure expression (e.g., `move |args| expr`).
1965 fn parse_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1966 let lo = self.token.span;
1969 if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
1971 let asyncness = if self.token.uninterpolated_span().rust_2018() {
1972 self.parse_asyncness()
1977 let capture_clause = self.parse_capture_clause()?;
1978 let decl = self.parse_fn_block_decl()?;
1979 let decl_hi = self.prev_token.span;
1980 let mut body = match decl.output {
1981 FnRetTy::Default(_) => {
1982 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
1983 self.parse_expr_res(restrictions, None)?
1986 // If an explicit return type is given, require a block to appear (RFC 968).
1987 let body_lo = self.token.span;
1988 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, AttrVec::new())?
1992 if let Async::Yes { span, .. } = asyncness {
1993 // Feature-gate `async ||` closures.
1994 self.sess.gated_spans.gate(sym::async_closure, span);
1997 if self.token.kind == TokenKind::Semi && self.token_cursor.frame.delim == DelimToken::Paren
1999 // It is likely that the closure body is a block but where the
2000 // braces have been removed. We will recover and eat the next
2001 // statements later in the parsing process.
2002 body = self.mk_expr_err(body.span);
2005 let body_span = body.span;
2007 let closure = self.mk_expr(
2009 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
2013 // Disable recovery for closure body
2015 ClosureSpans { whole_closure: closure.span, closing_pipe: decl_hi, body: body_span };
2016 self.current_closure = Some(spans);
2021 /// Parses an optional `move` prefix to a closure-like construct.
2022 fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> {
2023 if self.eat_keyword(kw::Move) {
2024 // Check for `move async` and recover
2025 if self.check_keyword(kw::Async) {
2026 let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
2027 Err(self.incorrect_move_async_order_found(move_async_span))
2029 Ok(CaptureBy::Value)
2036 /// Parses the `|arg, arg|` header of a closure.
2037 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
2038 let inputs = if self.eat(&token::OrOr) {
2041 self.expect(&token::BinOp(token::Or))?;
2043 .parse_seq_to_before_tokens(
2044 &[&token::BinOp(token::Or), &token::OrOr],
2045 SeqSep::trailing_allowed(token::Comma),
2046 TokenExpectType::NoExpect,
2047 |p| p.parse_fn_block_param(),
2054 self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes, RecoverReturnSign::Yes)?;
2056 Ok(P(FnDecl { inputs, output }))
2059 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
2060 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
2061 let lo = self.token.span;
2062 let attrs = self.parse_outer_attributes()?;
2063 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2064 let pat = this.parse_pat_no_top_alt(PARAM_EXPECTED)?;
2065 let ty = if this.eat(&token::Colon) {
2068 this.mk_ty(this.prev_token.span, TyKind::Infer)
2073 attrs: attrs.into(),
2076 span: lo.to(this.token.span),
2078 is_placeholder: false,
2080 TrailingToken::MaybeComma,
2085 /// Parses an `if` expression (`if` token already eaten).
2086 fn parse_if_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
2087 let lo = self.prev_token.span;
2088 let cond = self.parse_cond_expr()?;
2090 let missing_then_block_binop_span = || {
2092 ExprKind::Binary(Spanned { span: binop_span, .. }, _, ref right)
2093 if let ExprKind::Block(..) = right.kind => Some(binop_span),
2098 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
2099 // verify that the last statement is either an implicit return (no `;`) or an explicit
2100 // return. This won't catch blocks with an explicit `return`, but that would be caught by
2101 // the dead code lint.
2102 let thn = if self.token.is_keyword(kw::Else) || !cond.returns() {
2103 if let Some(binop_span) = missing_then_block_binop_span() {
2104 self.error_missing_if_then_block(lo, None, Some(binop_span)).emit();
2105 self.mk_block_err(cond.span)
2107 self.error_missing_if_cond(lo, cond.span)
2110 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
2111 let not_block = self.token != token::OpenDelim(token::Brace);
2112 let block = self.parse_block().map_err(|err| {
2114 self.error_missing_if_then_block(lo, Some(err), missing_then_block_binop_span())
2119 self.error_on_if_block_attrs(lo, false, block.span, &attrs);
2122 let els = if self.eat_keyword(kw::Else) { Some(self.parse_else_expr()?) } else { None };
2123 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els), attrs))
2126 fn error_missing_if_then_block(
2129 err: Option<DiagnosticBuilder<'a, ErrorGuaranteed>>,
2130 binop_span: Option<Span>,
2131 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2132 let msg = "this `if` expression has a condition, but no block";
2134 let mut err = if let Some(mut err) = err {
2135 err.span_label(if_span, msg);
2138 self.struct_span_err(if_span, msg)
2141 if let Some(binop_span) = binop_span {
2142 err.span_help(binop_span, "maybe you forgot the right operand of the condition?");
2148 fn error_missing_if_cond(&self, lo: Span, span: Span) -> P<ast::Block> {
2149 let sp = self.sess.source_map().next_point(lo);
2150 self.struct_span_err(sp, "missing condition for `if` expression")
2151 .span_label(sp, "expected if condition here")
2153 self.mk_block_err(span)
2156 /// Parses the condition of a `if` or `while` expression.
2157 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
2158 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
2160 if let ExprKind::Let(..) = cond.kind {
2161 // Remove the last feature gating of a `let` expression since it's stable.
2162 self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2168 /// Parses a `let $pat = $expr` pseudo-expression.
2169 /// The `let` token has already been eaten.
2170 fn parse_let_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
2171 let lo = self.prev_token.span;
2172 let pat = self.parse_pat_allow_top_alt(
2176 CommaRecoveryMode::LikelyTuple,
2178 self.expect(&token::Eq)?;
2179 let expr = self.with_res(self.restrictions | Restrictions::NO_STRUCT_LITERAL, |this| {
2180 this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
2182 let span = lo.to(expr.span);
2183 self.sess.gated_spans.gate(sym::let_chains, span);
2184 Ok(self.mk_expr(span, ExprKind::Let(pat, expr, span), attrs))
2187 /// Parses an `else { ... }` expression (`else` token already eaten).
2188 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
2189 let ctx_span = self.prev_token.span; // `else`
2190 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
2191 let expr = if self.eat_keyword(kw::If) {
2192 self.parse_if_expr(AttrVec::new())?
2194 let blk = self.parse_block()?;
2195 self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new())
2197 self.error_on_if_block_attrs(ctx_span, true, expr.span, &attrs);
2201 fn error_on_if_block_attrs(
2206 attrs: &[ast::Attribute],
2208 let (span, last) = match attrs {
2210 [x0 @ xn] | [x0, .., xn] => (x0.span.to(xn.span), xn.span),
2212 let ctx = if is_ctx_else { "else" } else { "if" };
2213 self.struct_span_err(last, "outer attributes are not allowed on `if` and `else` branches")
2214 .span_label(branch_span, "the attributes are attached to this branch")
2215 .span_label(ctx_span, format!("the branch belongs to this `{}`", ctx))
2218 "remove the attributes",
2220 Applicability::MachineApplicable,
2225 /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
2228 opt_label: Option<Label>,
2231 ) -> PResult<'a, P<Expr>> {
2232 // Record whether we are about to parse `for (`.
2233 // This is used below for recovery in case of `for ( $stuff ) $block`
2234 // in which case we will suggest `for $stuff $block`.
2235 let begin_paren = match self.token.kind {
2236 token::OpenDelim(token::Paren) => Some(self.token.span),
2240 let pat = self.parse_pat_allow_top_alt(
2244 CommaRecoveryMode::LikelyTuple,
2246 if !self.eat_keyword(kw::In) {
2247 self.error_missing_in_for_loop();
2249 self.check_for_for_in_in_typo(self.prev_token.span);
2250 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
2252 let pat = self.recover_parens_around_for_head(pat, begin_paren);
2254 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
2255 attrs.extend(iattrs);
2257 let kind = ExprKind::ForLoop(pat, expr, loop_block, opt_label);
2258 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
2261 fn error_missing_in_for_loop(&mut self) {
2262 let (span, msg, sugg) = if self.token.is_ident_named(sym::of) {
2263 // Possibly using JS syntax (#75311).
2264 let span = self.token.span;
2266 (span, "try using `in` here instead", "in")
2268 (self.prev_token.span.between(self.token.span), "try adding `in` here", " in ")
2270 self.struct_span_err(span, "missing `in` in `for` loop")
2271 .span_suggestion_short(
2275 // Has been misleading, at least in the past (closed Issue #48492).
2276 Applicability::MaybeIncorrect,
2281 /// Parses a `while` or `while let` expression (`while` token already eaten).
2282 fn parse_while_expr(
2284 opt_label: Option<Label>,
2287 ) -> PResult<'a, P<Expr>> {
2288 let cond = self.parse_cond_expr().map_err(|mut err| {
2289 err.span_label(lo, "while parsing the condition of this `while` expression");
2292 let (iattrs, body) = self.parse_inner_attrs_and_block().map_err(|mut err| {
2293 err.span_label(lo, "while parsing the body of this `while` expression");
2294 err.span_label(cond.span, "this `while` condition successfully parsed");
2297 attrs.extend(iattrs);
2298 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::While(cond, body, opt_label), attrs))
2301 /// Parses `loop { ... }` (`loop` token already eaten).
2304 opt_label: Option<Label>,
2307 ) -> PResult<'a, P<Expr>> {
2308 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2309 attrs.extend(iattrs);
2310 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::Loop(body, opt_label), attrs))
2313 crate fn eat_label(&mut self) -> Option<Label> {
2314 self.token.lifetime().map(|ident| {
2320 /// Parses a `match ... { ... }` expression (`match` token already eaten).
2321 fn parse_match_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2322 let match_span = self.prev_token.span;
2323 let lo = self.prev_token.span;
2324 let scrutinee = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
2325 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
2326 if self.token == token::Semi {
2327 e.span_suggestion_short(
2329 "try removing this `match`",
2331 Applicability::MaybeIncorrect, // speculative
2334 if self.maybe_recover_unexpected_block_label() {
2341 attrs.extend(self.parse_inner_attributes()?);
2343 let mut arms: Vec<Arm> = Vec::new();
2344 while self.token != token::CloseDelim(token::Brace) {
2345 match self.parse_arm() {
2346 Ok(arm) => arms.push(arm),
2348 // Recover by skipping to the end of the block.
2350 self.recover_stmt();
2351 let span = lo.to(self.token.span);
2352 if self.token == token::CloseDelim(token::Brace) {
2355 return Ok(self.mk_expr(span, ExprKind::Match(scrutinee, arms), attrs));
2359 let hi = self.token.span;
2361 Ok(self.mk_expr(lo.to(hi), ExprKind::Match(scrutinee, arms), attrs))
2364 /// Attempt to recover from match arm body with statements and no surrounding braces.
2365 fn parse_arm_body_missing_braces(
2367 first_expr: &P<Expr>,
2369 ) -> Option<P<Expr>> {
2370 if self.token.kind != token::Semi {
2373 let start_snapshot = self.clone();
2374 let semi_sp = self.token.span;
2377 vec![self.mk_stmt(first_expr.span, ast::StmtKind::Expr(first_expr.clone()))];
2378 let err = |this: &mut Parser<'_>, stmts: Vec<ast::Stmt>| {
2379 let span = stmts[0].span.to(stmts[stmts.len() - 1].span);
2380 let mut err = this.struct_span_err(span, "`match` arm body without braces");
2381 let (these, s, are) =
2382 if stmts.len() > 1 { ("these", "s", "are") } else { ("this", "", "is") };
2386 "{these} statement{s} {are} not surrounded by a body",
2392 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2393 if stmts.len() > 1 {
2394 err.multipart_suggestion(
2395 &format!("surround the statement{} with a body", s),
2397 (span.shrink_to_lo(), "{ ".to_string()),
2398 (span.shrink_to_hi(), " }".to_string()),
2400 Applicability::MachineApplicable,
2403 err.span_suggestion(
2405 "use a comma to end a `match` arm expression",
2407 Applicability::MachineApplicable,
2411 this.mk_expr_err(span)
2413 // We might have either a `,` -> `;` typo, or a block without braces. We need
2414 // a more subtle parsing strategy.
2416 if self.token.kind == token::CloseDelim(token::Brace) {
2417 // We have reached the closing brace of the `match` expression.
2418 return Some(err(self, stmts));
2420 if self.token.kind == token::Comma {
2421 *self = start_snapshot;
2424 let pre_pat_snapshot = self.clone();
2425 match self.parse_pat_no_top_alt(None) {
2427 if self.token.kind == token::FatArrow {
2429 *self = pre_pat_snapshot;
2430 return Some(err(self, stmts));
2438 *self = pre_pat_snapshot;
2439 match self.parse_stmt_without_recovery(true, ForceCollect::No) {
2440 // Consume statements for as long as possible.
2445 *self = start_snapshot;
2448 // We couldn't parse either yet another statement missing it's
2449 // enclosing block nor the next arm's pattern or closing brace.
2452 *self = start_snapshot;
2460 pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
2461 fn check_let_expr(expr: &Expr) -> (bool, bool) {
2463 ExprKind::Binary(_, ref lhs, ref rhs) => {
2464 let lhs_rslt = check_let_expr(lhs);
2465 let rhs_rslt = check_let_expr(rhs);
2466 (lhs_rslt.0 || rhs_rslt.0, false)
2468 ExprKind::Let(..) => (true, true),
2472 let attrs = self.parse_outer_attributes()?;
2473 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2474 let lo = this.token.span;
2475 let pat = this.parse_pat_allow_top_alt(
2479 CommaRecoveryMode::EitherTupleOrPipe,
2481 let guard = if this.eat_keyword(kw::If) {
2482 let if_span = this.prev_token.span;
2483 let cond = this.parse_expr()?;
2484 let (has_let_expr, does_not_have_bin_op) = check_let_expr(&cond);
2486 if does_not_have_bin_op {
2487 // Remove the last feature gating of a `let` expression since it's stable.
2488 this.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2490 let span = if_span.to(cond.span);
2491 this.sess.gated_spans.gate(sym::if_let_guard, span);
2497 let arrow_span = this.token.span;
2498 if let Err(mut err) = this.expect(&token::FatArrow) {
2499 // We might have a `=>` -> `=` or `->` typo (issue #89396).
2500 if TokenKind::FatArrow
2502 .map_or(false, |similar_tokens| similar_tokens.contains(&this.token.kind))
2504 err.span_suggestion(
2506 "try using a fat arrow here",
2508 Applicability::MaybeIncorrect,
2516 let arm_start_span = this.token.span;
2518 let expr = this.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| {
2519 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2523 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
2524 && this.token != token::CloseDelim(token::Brace);
2526 let hi = this.prev_token.span;
2529 let sm = this.sess.source_map();
2530 if let Some(body) = this.parse_arm_body_missing_braces(&expr, arrow_span) {
2531 let span = body.span;
2534 attrs: attrs.into(),
2540 is_placeholder: false,
2542 TrailingToken::None,
2545 this.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]).map_err(
2547 match (sm.span_to_lines(expr.span), sm.span_to_lines(arm_start_span)) {
2548 (Ok(ref expr_lines), Ok(ref arm_start_lines))
2549 if arm_start_lines.lines[0].end_col
2550 == expr_lines.lines[0].end_col
2551 && expr_lines.lines.len() == 2
2552 && this.token == token::FatArrow =>
2554 // We check whether there's any trailing code in the parse span,
2555 // if there isn't, we very likely have the following:
2558 // | -- - missing comma
2562 // | - ^^ self.token.span
2564 // | parsed until here as `"y" & X`
2565 err.span_suggestion_short(
2566 arm_start_span.shrink_to_hi(),
2567 "missing a comma here to end this `match` arm",
2569 Applicability::MachineApplicable,
2575 "while parsing the `match` arm starting here",
2583 this.eat(&token::Comma);
2588 attrs: attrs.into(),
2594 is_placeholder: false,
2596 TrailingToken::None,
2601 /// Parses a `try {...}` expression (`try` token already eaten).
2602 fn parse_try_block(&mut self, span_lo: Span, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2603 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2604 attrs.extend(iattrs);
2605 if self.eat_keyword(kw::Catch) {
2606 let mut error = self.struct_span_err(
2607 self.prev_token.span,
2608 "keyword `catch` cannot follow a `try` block",
2610 error.help("try using `match` on the result of the `try` block instead");
2614 let span = span_lo.to(body.span);
2615 self.sess.gated_spans.gate(sym::try_blocks, span);
2616 Ok(self.mk_expr(span, ExprKind::TryBlock(body), attrs))
2620 fn is_do_catch_block(&self) -> bool {
2621 self.token.is_keyword(kw::Do)
2622 && self.is_keyword_ahead(1, &[kw::Catch])
2623 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2624 && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
2627 fn is_try_block(&self) -> bool {
2628 self.token.is_keyword(kw::Try)
2629 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2630 && self.token.uninterpolated_span().rust_2018()
2633 /// Parses an `async move? {...}` expression.
2634 fn parse_async_block(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2635 let lo = self.token.span;
2636 self.expect_keyword(kw::Async)?;
2637 let capture_clause = self.parse_capture_clause()?;
2638 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2639 attrs.extend(iattrs);
2640 let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);
2641 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
2644 fn is_async_block(&self) -> bool {
2645 self.token.is_keyword(kw::Async)
2648 self.is_keyword_ahead(1, &[kw::Move])
2649 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2652 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2656 fn is_certainly_not_a_block(&self) -> bool {
2657 self.look_ahead(1, |t| t.is_ident())
2659 // `{ ident, ` cannot start a block.
2660 self.look_ahead(2, |t| t == &token::Comma)
2661 || self.look_ahead(2, |t| t == &token::Colon)
2663 // `{ ident: token, ` cannot start a block.
2664 self.look_ahead(4, |t| t == &token::Comma) ||
2665 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
2666 self.look_ahead(3, |t| !t.can_begin_type())
2671 fn maybe_parse_struct_expr(
2673 qself: Option<&ast::QSelf>,
2676 ) -> Option<PResult<'a, P<Expr>>> {
2677 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2678 if struct_allowed || self.is_certainly_not_a_block() {
2679 if let Err(err) = self.expect(&token::OpenDelim(token::Brace)) {
2680 return Some(Err(err));
2682 let expr = self.parse_struct_expr(qself.cloned(), path.clone(), attrs.clone(), true);
2683 if let (Ok(expr), false) = (&expr, struct_allowed) {
2684 // This is a struct literal, but we don't can't accept them here.
2685 self.error_struct_lit_not_allowed_here(path.span, expr.span);
2692 fn error_struct_lit_not_allowed_here(&self, lo: Span, sp: Span) {
2693 self.struct_span_err(sp, "struct literals are not allowed here")
2694 .multipart_suggestion(
2695 "surround the struct literal with parentheses",
2696 vec![(lo.shrink_to_lo(), "(".to_string()), (sp.shrink_to_hi(), ")".to_string())],
2697 Applicability::MachineApplicable,
2702 pub(super) fn parse_struct_fields(
2706 close_delim: token::DelimToken,
2707 ) -> PResult<'a, (Vec<ExprField>, ast::StructRest, bool)> {
2708 let mut fields = Vec::new();
2709 let mut base = ast::StructRest::None;
2710 let mut recover_async = false;
2712 let mut async_block_err = |e: &mut Diagnostic, span: Span| {
2713 recover_async = true;
2714 e.span_label(span, "`async` blocks are only allowed in Rust 2018 or later");
2715 e.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
2716 e.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
2719 while self.token != token::CloseDelim(close_delim) {
2720 if self.eat(&token::DotDot) {
2721 let exp_span = self.prev_token.span;
2722 // We permit `.. }` on the left-hand side of a destructuring assignment.
2723 if self.check(&token::CloseDelim(close_delim)) {
2724 base = ast::StructRest::Rest(self.prev_token.span.shrink_to_hi());
2727 match self.parse_expr() {
2728 Ok(e) => base = ast::StructRest::Base(e),
2729 Err(mut e) if recover => {
2731 self.recover_stmt();
2733 Err(e) => return Err(e),
2735 self.recover_struct_comma_after_dotdot(exp_span);
2739 let recovery_field = self.find_struct_error_after_field_looking_code();
2740 let parsed_field = match self.parse_expr_field() {
2743 if pth == kw::Async {
2744 async_block_err(&mut e, pth.span);
2746 e.span_label(pth.span, "while parsing this struct");
2750 // If the next token is a comma, then try to parse
2751 // what comes next as additional fields, rather than
2752 // bailing out until next `}`.
2753 if self.token != token::Comma {
2754 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2755 if self.token != token::Comma {
2763 match self.expect_one_of(&[token::Comma], &[token::CloseDelim(close_delim)]) {
2765 if let Some(f) = parsed_field.or(recovery_field) {
2766 // Only include the field if there's no parse error for the field name.
2771 if pth == kw::Async {
2772 async_block_err(&mut e, pth.span);
2774 e.span_label(pth.span, "while parsing this struct");
2775 if let Some(f) = recovery_field {
2778 self.prev_token.span.shrink_to_hi(),
2779 "try adding a comma",
2781 Applicability::MachineApplicable,
2789 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2790 self.eat(&token::Comma);
2794 Ok((fields, base, recover_async))
2797 /// Precondition: already parsed the '{'.
2798 pub(super) fn parse_struct_expr(
2800 qself: Option<ast::QSelf>,
2804 ) -> PResult<'a, P<Expr>> {
2806 let (fields, base, recover_async) =
2807 self.parse_struct_fields(pth.clone(), recover, token::Brace)?;
2808 let span = lo.to(self.token.span);
2809 self.expect(&token::CloseDelim(token::Brace))?;
2810 let expr = if recover_async {
2813 ExprKind::Struct(P(ast::StructExpr { qself, path: pth, fields, rest: base }))
2815 Ok(self.mk_expr(span, expr, attrs))
2818 /// Use in case of error after field-looking code: `S { foo: () with a }`.
2819 fn find_struct_error_after_field_looking_code(&self) -> Option<ExprField> {
2820 match self.token.ident() {
2821 Some((ident, is_raw))
2822 if (is_raw || !ident.is_reserved())
2823 && self.look_ahead(1, |t| *t == token::Colon) =>
2825 Some(ast::ExprField {
2827 span: self.token.span,
2828 expr: self.mk_expr_err(self.token.span),
2829 is_shorthand: false,
2830 attrs: AttrVec::new(),
2832 is_placeholder: false,
2839 fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
2840 if self.token != token::Comma {
2843 self.struct_span_err(
2844 span.to(self.prev_token.span),
2845 "cannot use a comma after the base struct",
2847 .span_suggestion_short(
2849 "remove this comma",
2851 Applicability::MachineApplicable,
2853 .note("the base struct must always be the last field")
2855 self.recover_stmt();
2858 /// Parses `ident (COLON expr)?`.
2859 fn parse_expr_field(&mut self) -> PResult<'a, ExprField> {
2860 let attrs = self.parse_outer_attributes()?;
2861 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2862 let lo = this.token.span;
2864 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2865 let is_shorthand = !this.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
2866 let (ident, expr) = if is_shorthand {
2867 // Mimic `x: x` for the `x` field shorthand.
2868 let ident = this.parse_ident_common(false)?;
2869 let path = ast::Path::from_ident(ident);
2870 (ident, this.mk_expr(ident.span, ExprKind::Path(None, path), AttrVec::new()))
2872 let ident = this.parse_field_name()?;
2873 this.error_on_eq_field_init(ident);
2875 (ident, this.parse_expr()?)
2881 span: lo.to(expr.span),
2884 attrs: attrs.into(),
2886 is_placeholder: false,
2888 TrailingToken::MaybeComma,
2893 /// Check for `=`. This means the source incorrectly attempts to
2894 /// initialize a field with an eq rather than a colon.
2895 fn error_on_eq_field_init(&self, field_name: Ident) {
2896 if self.token != token::Eq {
2900 self.struct_span_err(self.token.span, "expected `:`, found `=`")
2902 field_name.span.shrink_to_hi().to(self.token.span),
2903 "replace equals symbol with a colon",
2905 Applicability::MachineApplicable,
2910 fn err_dotdotdot_syntax(&self, span: Span) {
2911 self.struct_span_err(span, "unexpected token: `...`")
2914 "use `..` for an exclusive range",
2916 Applicability::MaybeIncorrect,
2920 "or `..=` for an inclusive range",
2922 Applicability::MaybeIncorrect,
2927 fn err_larrow_operator(&self, span: Span) {
2928 self.struct_span_err(span, "unexpected token: `<-`")
2931 "if you meant to write a comparison against a negative value, add a \
2932 space in between `<` and `-`",
2934 Applicability::MaybeIncorrect,
2939 fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2940 ExprKind::AssignOp(binop, lhs, rhs)
2945 start: Option<P<Expr>>,
2946 end: Option<P<Expr>>,
2947 limits: RangeLimits,
2949 if end.is_none() && limits == RangeLimits::Closed {
2950 self.inclusive_range_with_incorrect_end(self.prev_token.span);
2953 ExprKind::Range(start, end, limits)
2957 fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
2958 ExprKind::Unary(unop, expr)
2961 fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2962 ExprKind::Binary(binop, lhs, rhs)
2965 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
2966 ExprKind::Index(expr, idx)
2969 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
2970 ExprKind::Call(f, args)
2973 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> P<Expr> {
2974 let span = lo.to(self.prev_token.span);
2975 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), AttrVec::new());
2976 self.recover_from_await_method_call();
2980 crate fn mk_expr(&self, span: Span, kind: ExprKind, attrs: AttrVec) -> P<Expr> {
2981 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None })
2984 pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
2985 self.mk_expr(span, ExprKind::Err, AttrVec::new())
2988 /// Create expression span ensuring the span of the parent node
2989 /// is larger than the span of lhs and rhs, including the attributes.
2990 fn mk_expr_sp(&self, lhs: &P<Expr>, lhs_span: Span, rhs_span: Span) -> Span {
2993 .find(|a| a.style == AttrStyle::Outer)
2994 .map_or(lhs_span, |a| a.span)
2998 fn collect_tokens_for_expr(
3001 f: impl FnOnce(&mut Self, Vec<ast::Attribute>) -> PResult<'a, P<Expr>>,
3002 ) -> PResult<'a, P<Expr>> {
3003 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
3004 let res = f(this, attrs)?;
3005 let trailing = if this.restrictions.contains(Restrictions::STMT_EXPR)
3006 && this.token.kind == token::Semi
3010 // FIXME - pass this through from the place where we know
3011 // we need a comma, rather than assuming that `#[attr] expr,`
3012 // always captures a trailing comma
3013 TrailingToken::MaybeComma