1 use super::pat::{GateOr, PARAM_EXPECTED};
2 use super::ty::{AllowPlus, RecoverQPath};
3 use super::{BlockMode, Parser, PathStyle, Restrictions, TokenType};
4 use super::{SemiColonMode, SeqSep, TokenExpectType};
5 use crate::maybe_recover_from_interpolated_ty_qpath;
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, Field, 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::source_map::{self, Span, Spanned};
19 use rustc_span::symbol::{kw, sym, Ident, Symbol};
20 use rustc_span::{BytePos, Pos};
23 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
24 /// dropped into the token stream, which happens while parsing the result of
25 /// macro expansion). Placement of these is not as complex as I feared it would
26 /// be. The important thing is to make sure that lookahead doesn't balk at
27 /// `token::Interpolated` tokens.
28 macro_rules! maybe_whole_expr {
30 if let token::Interpolated(nt) = &$p.token.kind {
32 token::NtExpr(e) | token::NtLiteral(e) => {
37 token::NtPath(path) => {
38 let path = path.clone();
42 ExprKind::Path(None, path),
46 token::NtBlock(block) => {
47 let block = block.clone();
51 ExprKind::Block(block, None),
62 pub(super) enum LhsExpr {
64 AttributesParsed(AttrVec),
65 AlreadyParsed(P<Expr>),
68 impl From<Option<AttrVec>> for LhsExpr {
69 /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
70 /// and `None` into `LhsExpr::NotYetParsed`.
72 /// This conversion does not allocate.
73 fn from(o: Option<AttrVec>) -> Self {
74 if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed }
78 impl From<P<Expr>> for LhsExpr {
79 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
81 /// This conversion does not allocate.
82 fn from(expr: P<Expr>) -> Self {
83 LhsExpr::AlreadyParsed(expr)
88 /// Parses an expression.
90 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
91 self.parse_expr_res(Restrictions::empty(), None)
94 pub(super) fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> {
95 self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
98 fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P<Expr>> {
99 match self.parse_expr() {
100 Ok(expr) => Ok(expr),
101 Err(mut err) => match self.token.ident() {
102 Some((Ident { name: kw::Underscore, .. }, false))
103 if self.look_ahead(1, |t| t == &token::Comma) =>
105 // Special-case handling of `foo(_, _, _)`
108 Ok(self.mk_expr(self.prev_token.span, ExprKind::Err, AttrVec::new()))
115 /// Parses a sequence of expressions delimited by parentheses.
116 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
117 self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r)
120 /// Parses an expression, subject to the given restrictions.
122 pub(super) fn parse_expr_res(
125 already_parsed_attrs: Option<AttrVec>,
126 ) -> PResult<'a, P<Expr>> {
127 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
130 /// Parses an associative expression.
132 /// This parses an expression accounting for associativity and precedence of the operators in
135 fn parse_assoc_expr(&mut self, already_parsed_attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> {
136 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
139 /// Parses an associative expression with operators of at least `min_prec` precedence.
140 pub(super) fn parse_assoc_expr_with(
144 ) -> PResult<'a, P<Expr>> {
145 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
148 let attrs = match lhs {
149 LhsExpr::AttributesParsed(attrs) => Some(attrs),
152 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
153 return self.parse_prefix_range_expr(attrs);
155 self.parse_prefix_expr(attrs)?
158 let last_type_ascription_set = self.last_type_ascription.is_some();
160 if !self.should_continue_as_assoc_expr(&lhs) {
161 self.last_type_ascription = None;
165 self.expected_tokens.push(TokenType::Operator);
166 while let Some(op) = self.check_assoc_op() {
167 // Adjust the span for interpolated LHS to point to the `$lhs` token
168 // and not to what it refers to.
169 let lhs_span = match self.prev_token.kind {
170 TokenKind::Interpolated(..) => self.prev_token.span,
174 let cur_op_span = self.token.span;
175 let restrictions = if op.node.is_assign_like() {
176 self.restrictions & Restrictions::NO_STRUCT_LITERAL
180 let prec = op.node.precedence();
184 // Check for deprecated `...` syntax
185 if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq {
186 self.err_dotdotdot_syntax(self.token.span);
189 if self.token == token::LArrow {
190 self.err_larrow_operator(self.token.span);
194 if op.node.is_comparison() {
195 if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
200 if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual)
201 && self.token.kind == token::Eq
202 && self.prev_token.span.hi() == self.token.span.lo()
204 // Look for JS' `===` and `!==` and recover 😇
205 let sp = op.span.to(self.token.span);
206 let sugg = match op.node {
207 AssocOp::Equal => "==",
208 AssocOp::NotEqual => "!=",
211 self.struct_span_err(sp, &format!("invalid comparison operator `{}=`", sugg))
212 .span_suggestion_short(
214 &format!("`{s}=` is not a valid comparison operator, use `{s}`", s = sugg),
216 Applicability::MachineApplicable,
224 if op == AssocOp::As {
225 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
227 } else if op == AssocOp::Colon {
228 lhs = self.parse_assoc_op_ascribe(lhs, lhs_span)?;
230 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
231 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
232 // generalise it to the Fixity::None code.
233 lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?;
237 let fixity = op.fixity();
238 let prec_adjustment = match fixity {
241 // We currently have no non-associative operators that are not handled above by
242 // the special cases. The code is here only for future convenience.
245 let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
246 this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
249 let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span);
262 | AssocOp::ShiftRight
268 | AssocOp::GreaterEqual => {
269 let ast_op = op.to_ast_binop().unwrap();
270 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
271 self.mk_expr(span, binary, AttrVec::new())
274 self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span), AttrVec::new())
276 AssocOp::AssignOp(k) => {
278 token::Plus => BinOpKind::Add,
279 token::Minus => BinOpKind::Sub,
280 token::Star => BinOpKind::Mul,
281 token::Slash => BinOpKind::Div,
282 token::Percent => BinOpKind::Rem,
283 token::Caret => BinOpKind::BitXor,
284 token::And => BinOpKind::BitAnd,
285 token::Or => BinOpKind::BitOr,
286 token::Shl => BinOpKind::Shl,
287 token::Shr => BinOpKind::Shr,
289 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
290 self.mk_expr(span, aopexpr, AttrVec::new())
292 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
293 self.span_bug(span, "AssocOp should have been handled by special case")
297 if let Fixity::None = fixity {
301 if last_type_ascription_set {
302 self.last_type_ascription = None;
307 fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
308 match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) {
309 // Semi-statement forms are odd:
310 // See https://github.com/rust-lang/rust/issues/29071
311 (true, None) => false,
312 (false, _) => true, // Continue parsing the expression.
313 // An exhaustive check is done in the following block, but these are checked first
314 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
315 // want to keep their span info to improve diagnostics in these cases in a later stage.
316 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
317 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
318 (true, Some(AssocOp::Add)) // `{ 42 } + 42
319 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
320 // `if x { a } else { b } && if y { c } else { d }`
321 if !self.look_ahead(1, |t| t.is_used_keyword()) => {
322 // These cases are ambiguous and can't be identified in the parser alone.
323 let sp = self.sess.source_map().start_point(self.token.span);
324 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
327 (true, Some(AssocOp::LAnd)) => {
328 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`. Separated from the
329 // above due to #74233.
330 // These cases are ambiguous and can't be identified in the parser alone.
331 let sp = self.sess.source_map().start_point(self.token.span);
332 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
335 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => false,
337 self.error_found_expr_would_be_stmt(lhs);
343 /// We've found an expression that would be parsed as a statement,
344 /// but the next token implies this should be parsed as an expression.
345 /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
346 fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
347 let mut err = self.struct_span_err(
349 &format!("expected expression, found `{}`", pprust::token_to_string(&self.token),),
351 err.span_label(self.token.span, "expected expression");
352 self.sess.expr_parentheses_needed(&mut err, lhs.span, Some(pprust::expr_to_string(&lhs)));
356 /// Possibly translate the current token to an associative operator.
357 /// The method does not advance the current token.
359 /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
360 fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
361 let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
362 // When parsing const expressions, stop parsing when encountering `>`.
367 | AssocOp::GreaterEqual
368 | AssocOp::AssignOp(token::BinOpToken::Shr),
371 ) if self.restrictions.contains(Restrictions::CONST_EXPR) => {
374 (Some(op), _) => (op, self.token.span),
375 (None, Some((Ident { name: sym::and, span }, false))) => {
376 self.error_bad_logical_op("and", "&&", "conjunction");
377 (AssocOp::LAnd, span)
379 (None, Some((Ident { name: sym::or, span }, false))) => {
380 self.error_bad_logical_op("or", "||", "disjunction");
385 Some(source_map::respan(span, op))
388 /// Error on `and` and `or` suggesting `&&` and `||` respectively.
389 fn error_bad_logical_op(&self, bad: &str, good: &str, english: &str) {
390 self.struct_span_err(self.token.span, &format!("`{}` is not a logical operator", bad))
391 .span_suggestion_short(
393 &format!("use `{}` to perform logical {}", good, english),
395 Applicability::MachineApplicable,
397 .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators")
401 /// Checks if this expression is a successfully parsed statement.
402 fn expr_is_complete(&self, e: &Expr) -> bool {
403 self.restrictions.contains(Restrictions::STMT_EXPR)
404 && !classify::expr_requires_semi_to_be_stmt(e)
407 /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
408 /// The other two variants are handled in `parse_prefix_range_expr` below.
415 ) -> PResult<'a, P<Expr>> {
416 let rhs = if self.is_at_start_of_range_notation_rhs() {
417 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
421 let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
422 let span = self.mk_expr_sp(&lhs, lhs.span, rhs_span);
424 if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed };
425 Ok(self.mk_expr(span, self.mk_range(Some(lhs), rhs, limits)?, AttrVec::new()))
428 fn is_at_start_of_range_notation_rhs(&self) -> bool {
429 if self.token.can_begin_expr() {
430 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
431 if self.token == token::OpenDelim(token::Brace) {
432 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
440 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
441 fn parse_prefix_range_expr(&mut self, attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> {
442 // Check for deprecated `...` syntax.
443 if self.token == token::DotDotDot {
444 self.err_dotdotdot_syntax(self.token.span);
448 [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
449 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
453 let limits = match self.token.kind {
454 token::DotDot => RangeLimits::HalfOpen,
455 _ => RangeLimits::Closed,
457 let op = AssocOp::from_token(&self.token);
458 let attrs = self.parse_or_use_outer_attributes(attrs)?;
459 let lo = self.token.span;
461 let (span, opt_end) = if self.is_at_start_of_range_notation_rhs() {
462 // RHS must be parsed with more associativity than the dots.
463 self.parse_assoc_expr_with(op.unwrap().precedence() + 1, LhsExpr::NotYetParsed)
464 .map(|x| (lo.to(x.span), Some(x)))?
468 Ok(self.mk_expr(span, self.mk_range(None, opt_end, limits)?, attrs))
471 /// Parses a prefix-unary-operator expr.
472 fn parse_prefix_expr(&mut self, attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> {
473 let attrs = self.parse_or_use_outer_attributes(attrs)?;
474 self.maybe_collect_tokens(super::attr::maybe_needs_tokens(&attrs), |this| {
475 let lo = this.token.span;
476 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
477 let (hi, ex) = match this.token.uninterpolate().kind {
478 token::Not => this.parse_unary_expr(lo, UnOp::Not), // `!expr`
479 token::Tilde => this.recover_tilde_expr(lo), // `~expr`
480 token::BinOp(token::Minus) => this.parse_unary_expr(lo, UnOp::Neg), // `-expr`
481 token::BinOp(token::Star) => this.parse_unary_expr(lo, UnOp::Deref), // `*expr`
482 token::BinOp(token::And) | token::AndAnd => this.parse_borrow_expr(lo),
483 token::Ident(..) if this.token.is_keyword(kw::Box) => this.parse_box_expr(lo),
484 token::Ident(..) if this.is_mistaken_not_ident_negation() => {
485 this.recover_not_expr(lo)
487 _ => return this.parse_dot_or_call_expr(Some(attrs)),
489 Ok(this.mk_expr(lo.to(hi), ex, attrs))
493 fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P<Expr>)> {
495 let expr = self.parse_prefix_expr(None);
496 let (span, expr) = self.interpolated_or_expr_span(expr)?;
497 Ok((lo.to(span), expr))
500 fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
501 let (span, expr) = self.parse_prefix_expr_common(lo)?;
502 Ok((span, self.mk_unary(op, expr)))
505 // Recover on `!` suggesting for bitwise negation instead.
506 fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
507 self.struct_span_err(lo, "`~` cannot be used as a unary operator")
508 .span_suggestion_short(
510 "use `!` to perform bitwise not",
512 Applicability::MachineApplicable,
516 self.parse_unary_expr(lo, UnOp::Not)
519 /// Parse `box expr`.
520 fn parse_box_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
521 let (span, expr) = self.parse_prefix_expr_common(lo)?;
522 self.sess.gated_spans.gate(sym::box_syntax, span);
523 Ok((span, ExprKind::Box(expr)))
526 fn is_mistaken_not_ident_negation(&self) -> bool {
527 let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
528 // These tokens can start an expression after `!`, but
529 // can't continue an expression after an ident
530 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
531 token::Literal(..) | token::Pound => true,
532 _ => t.is_whole_expr(),
534 self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
537 /// Recover on `not expr` in favor of `!expr`.
538 fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
540 let not_token = self.look_ahead(1, |t| t.clone());
541 self.struct_span_err(
543 &format!("unexpected {} after identifier", super::token_descr(¬_token)),
545 .span_suggestion_short(
546 // Span the `not` plus trailing whitespace to avoid
547 // trailing whitespace after the `!` in our suggestion
548 self.sess.source_map().span_until_non_whitespace(lo.to(not_token.span)),
549 "use `!` to perform logical negation",
551 Applicability::MachineApplicable,
556 self.parse_unary_expr(lo, UnOp::Not)
559 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
560 fn interpolated_or_expr_span(
562 expr: PResult<'a, P<Expr>>,
563 ) -> PResult<'a, (Span, P<Expr>)> {
566 match self.prev_token.kind {
567 TokenKind::Interpolated(..) => self.prev_token.span,
575 fn parse_assoc_op_cast(
579 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind,
580 ) -> PResult<'a, P<Expr>> {
581 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
583 this.mk_expr_sp(&lhs, lhs_span, rhs.span),
589 // Save the state of the parser before parsing type normally, in case there is a
590 // LessThan comparison after this cast.
591 let parser_snapshot_before_type = self.clone();
592 let cast_expr = match self.parse_ty_no_plus() {
593 Ok(rhs) => mk_expr(self, rhs),
594 Err(mut type_err) => {
595 // Rewind to before attempting to parse the type with generics, to recover
596 // from situations like `x as usize < y` in which we first tried to parse
597 // `usize < y` as a type with generic arguments.
598 let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
600 match self.parse_path(PathStyle::Expr) {
602 let (op_noun, op_verb) = match self.token.kind {
603 token::Lt => ("comparison", "comparing"),
604 token::BinOp(token::Shl) => ("shift", "shifting"),
606 // We can end up here even without `<` being the next token, for
607 // example because `parse_ty_no_plus` returns `Err` on keywords,
608 // but `parse_path` returns `Ok` on them due to error recovery.
609 // Return original error and parser state.
610 *self = parser_snapshot_after_type;
611 return Err(type_err);
615 // Successfully parsed the type path leaving a `<` yet to parse.
618 // Report non-fatal diagnostics, keep `x as usize` as an expression
619 // in AST and continue parsing.
621 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
622 pprust::path_to_string(&path),
625 let span_after_type = parser_snapshot_after_type.token.span;
626 let expr = mk_expr(self, self.mk_ty(path.span, TyKind::Path(None, path)));
629 .span_to_snippet(expr.span)
630 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
632 self.struct_span_err(self.token.span, &msg)
634 self.look_ahead(1, |t| t.span).to(span_after_type),
635 "interpreted as generic arguments",
637 .span_label(self.token.span, format!("not interpreted as {}", op_noun))
640 &format!("try {} the cast value", op_verb),
641 format!("({})", expr_str),
642 Applicability::MachineApplicable,
648 Err(mut path_err) => {
649 // Couldn't parse as a path, return original error and parser state.
651 *self = parser_snapshot_after_type;
652 return Err(type_err);
658 self.parse_and_disallow_postfix_after_cast(cast_expr)
661 /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
662 /// then emits an error and returns the newly parsed tree.
663 /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
664 fn parse_and_disallow_postfix_after_cast(
667 ) -> PResult<'a, P<Expr>> {
668 // Save the memory location of expr before parsing any following postfix operators.
669 // This will be compared with the memory location of the output expression.
670 // If they different we can assume we parsed another expression because the existing expression is not reallocated.
671 let addr_before = &*cast_expr as *const _ as usize;
672 let span = cast_expr.span;
673 let with_postfix = self.parse_dot_or_call_expr_with_(cast_expr, span)?;
674 let changed = addr_before != &*with_postfix as *const _ as usize;
676 // Check if an illegal postfix operator has been added after the cast.
677 // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator.
678 if !matches!(with_postfix.kind, ExprKind::Cast(_, _) | ExprKind::Type(_, _)) || changed {
680 "casts cannot be followed by {}",
681 match with_postfix.kind {
682 ExprKind::Index(_, _) => "indexing",
683 ExprKind::Try(_) => "?",
684 ExprKind::Field(_, _) => "a field access",
685 ExprKind::MethodCall(_, _, _) => "a method call",
686 ExprKind::Call(_, _) => "a function call",
687 ExprKind::Await(_) => "`.await`",
688 ExprKind::Err => return Ok(with_postfix),
689 _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"),
692 let mut err = self.struct_span_err(span, &msg);
693 // If type ascription is "likely an error", the user will already be getting a useful
694 // help message, and doesn't need a second.
695 if self.last_type_ascription.map_or(false, |last_ascription| last_ascription.1) {
696 self.maybe_annotate_with_ascription(&mut err, false);
698 let suggestions = vec![
699 (span.shrink_to_lo(), "(".to_string()),
700 (span.shrink_to_hi(), ")".to_string()),
702 err.multipart_suggestion(
703 "try surrounding the expression in parentheses",
705 Applicability::MachineApplicable,
713 fn parse_assoc_op_ascribe(&mut self, lhs: P<Expr>, lhs_span: Span) -> PResult<'a, P<Expr>> {
714 let maybe_path = self.could_ascription_be_path(&lhs.kind);
715 self.last_type_ascription = Some((self.prev_token.span, maybe_path));
716 let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
717 self.sess.gated_spans.gate(sym::type_ascription, lhs.span);
721 /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
722 fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
724 let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
725 let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
726 let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo);
727 let expr = self.parse_prefix_expr(None);
728 let (hi, expr) = self.interpolated_or_expr_span(expr)?;
729 let span = lo.to(hi);
730 if let Some(lt) = lifetime {
731 self.error_remove_borrow_lifetime(span, lt.ident.span);
733 Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
736 fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
737 self.struct_span_err(span, "borrow expressions cannot be annotated with lifetimes")
738 .span_label(lt_span, "annotated with lifetime here")
741 "remove the lifetime annotation",
743 Applicability::MachineApplicable,
748 /// Parse `mut?` or `raw [ const | mut ]`.
749 fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) {
750 if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) {
751 // `raw [ const | mut ]`.
752 let found_raw = self.eat_keyword(kw::Raw);
754 let mutability = self.parse_const_or_mut().unwrap();
755 self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span));
756 (ast::BorrowKind::Raw, mutability)
759 (ast::BorrowKind::Ref, self.parse_mutability())
763 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
764 fn parse_dot_or_call_expr(&mut self, attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> {
765 let attrs = self.parse_or_use_outer_attributes(attrs)?;
766 let base = self.parse_bottom_expr();
767 let (span, base) = self.interpolated_or_expr_span(base)?;
768 self.parse_dot_or_call_expr_with(base, span, attrs)
771 pub(super) fn parse_dot_or_call_expr_with(
776 ) -> PResult<'a, P<Expr>> {
777 // Stitch the list of outer attributes onto the return value.
778 // A little bit ugly, but the best way given the current code
780 self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| {
781 expr.map(|mut expr| {
782 attrs.extend::<Vec<_>>(expr.attrs.into());
789 fn parse_dot_or_call_expr_with_(&mut self, mut e: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
791 if self.eat(&token::Question) {
793 e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e), AttrVec::new());
796 if self.eat(&token::Dot) {
798 e = self.parse_dot_suffix_expr(lo, e)?;
801 if self.expr_is_complete(&e) {
804 e = match self.token.kind {
805 token::OpenDelim(token::Paren) => self.parse_fn_call_expr(lo, e),
806 token::OpenDelim(token::Bracket) => self.parse_index_expr(lo, e)?,
812 fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
813 match self.token.uninterpolate().kind {
814 token::Ident(..) => self.parse_dot_suffix(base, lo),
815 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
816 Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix, None))
818 token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => {
819 Ok(self.parse_tuple_field_access_expr_float(lo, base, symbol, suffix))
822 self.error_unexpected_after_dot();
828 fn error_unexpected_after_dot(&self) {
829 // FIXME Could factor this out into non_fatal_unexpected or something.
830 let actual = pprust::token_to_string(&self.token);
831 self.struct_span_err(self.token.span, &format!("unexpected token: `{}`", actual)).emit();
834 // We need an identifier or integer, but the next token is a float.
835 // Break the float into components to extract the identifier or integer.
836 // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
837 // parts unless those parts are processed immediately. `TokenCursor` should either
838 // support pushing "future tokens" (would be also helpful to `break_and_eat`), or
839 // we should break everything including floats into more basic proc-macro style
840 // tokens in the lexer (probably preferable).
841 fn parse_tuple_field_access_expr_float(
846 suffix: Option<Symbol>,
849 enum FloatComponent {
853 use FloatComponent::*;
855 let float_str = float.as_str();
856 let mut components = Vec::new();
857 let mut ident_like = String::new();
858 for c in float_str.chars() {
859 if c == '_' || c.is_ascii_alphanumeric() {
861 } else if matches!(c, '.' | '+' | '-') {
862 if !ident_like.is_empty() {
863 components.push(IdentLike(mem::take(&mut ident_like)));
865 components.push(Punct(c));
867 panic!("unexpected character in a float token: {:?}", c)
870 if !ident_like.is_empty() {
871 components.push(IdentLike(ident_like));
874 // With proc macros the span can refer to anything, the source may be too short,
875 // or too long, or non-ASCII. It only makes sense to break our span into components
876 // if its underlying text is identical to our float literal.
877 let span = self.token.span;
878 let can_take_span_apart =
879 || self.span_to_snippet(span).as_deref() == Ok(float_str).as_deref();
884 self.parse_tuple_field_access_expr(lo, base, Symbol::intern(&i), suffix, None)
887 [IdentLike(i), Punct('.')] => {
888 let (ident_span, dot_span) = if can_take_span_apart() {
889 let (span, ident_len) = (span.data(), BytePos::from_usize(i.len()));
890 let ident_span = span.with_hi(span.lo + ident_len);
891 let dot_span = span.with_lo(span.lo + ident_len);
892 (ident_span, dot_span)
896 assert!(suffix.is_none());
897 let symbol = Symbol::intern(&i);
898 self.token = Token::new(token::Ident(symbol, false), ident_span);
899 let next_token = (Token::new(token::Dot, dot_span), self.token_spacing);
900 self.parse_tuple_field_access_expr(lo, base, symbol, None, Some(next_token))
903 [IdentLike(i1), Punct('.'), IdentLike(i2)] => {
904 let (ident1_span, dot_span, ident2_span) = if can_take_span_apart() {
905 let (span, ident1_len) = (span.data(), BytePos::from_usize(i1.len()));
906 let ident1_span = span.with_hi(span.lo + ident1_len);
908 .with_lo(span.lo + ident1_len)
909 .with_hi(span.lo + ident1_len + BytePos(1));
910 let ident2_span = self.token.span.with_lo(span.lo + ident1_len + BytePos(1));
911 (ident1_span, dot_span, ident2_span)
915 let symbol1 = Symbol::intern(&i1);
916 self.token = Token::new(token::Ident(symbol1, false), ident1_span);
917 // This needs to be `Spacing::Alone` to prevent regressions.
918 // See issue #76399 and PR #76285 for more details
919 let next_token1 = (Token::new(token::Dot, dot_span), Spacing::Alone);
921 self.parse_tuple_field_access_expr(lo, base, symbol1, None, Some(next_token1));
922 let symbol2 = Symbol::intern(&i2);
923 let next_token2 = Token::new(token::Ident(symbol2, false), ident2_span);
924 self.bump_with((next_token2, self.token_spacing)); // `.`
925 self.parse_tuple_field_access_expr(lo, base1, symbol2, suffix, None)
927 // 1e+ | 1e- (recovered)
928 [IdentLike(_), Punct('+' | '-')] |
930 [IdentLike(_), Punct('+' | '-'), IdentLike(_)] |
932 [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-'), IdentLike(_)] => {
933 // See the FIXME about `TokenCursor` above.
934 self.error_unexpected_after_dot();
937 _ => panic!("unexpected components in a float token: {:?}", components),
941 fn parse_tuple_field_access_expr(
946 suffix: Option<Symbol>,
947 next_token: Option<(Token, Spacing)>,
950 Some(next_token) => self.bump_with(next_token),
953 let span = self.prev_token.span;
954 let field = ExprKind::Field(base, Ident::new(field, span));
955 self.expect_no_suffix(span, "a tuple index", suffix);
956 self.mk_expr(lo.to(span), field, AttrVec::new())
959 /// Parse a function call expression, `expr(...)`.
960 fn parse_fn_call_expr(&mut self, lo: Span, fun: P<Expr>) -> P<Expr> {
961 let seq = self.parse_paren_expr_seq().map(|args| {
962 self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args), AttrVec::new())
964 self.recover_seq_parse_error(token::Paren, lo, seq)
967 /// Parse an indexing expression `expr[...]`.
968 fn parse_index_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
970 let index = self.parse_expr()?;
971 self.expect(&token::CloseDelim(token::Bracket))?;
972 Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_index(base, index), AttrVec::new()))
975 /// Assuming we have just parsed `.`, continue parsing into an expression.
976 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
977 if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) {
978 return self.mk_await_expr(self_arg, lo);
981 let fn_span_lo = self.token.span;
982 let mut segment = self.parse_path_segment(PathStyle::Expr)?;
983 self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(token::Paren)]);
984 self.check_turbofish_missing_angle_brackets(&mut segment);
986 if self.check(&token::OpenDelim(token::Paren)) {
987 // Method call `expr.f()`
988 let mut args = self.parse_paren_expr_seq()?;
989 args.insert(0, self_arg);
991 let fn_span = fn_span_lo.to(self.prev_token.span);
992 let span = lo.to(self.prev_token.span);
993 Ok(self.mk_expr(span, ExprKind::MethodCall(segment, args, fn_span), AttrVec::new()))
995 // Field access `expr.f`
996 if let Some(args) = segment.args {
997 self.struct_span_err(
999 "field expressions cannot have generic arguments",
1004 let span = lo.to(self.prev_token.span);
1005 Ok(self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), AttrVec::new()))
1009 /// At the bottom (top?) of the precedence hierarchy,
1010 /// Parses things like parenthesized exprs, macros, `return`, etc.
1012 /// N.B., this does not parse outer attributes, and is private because it only works
1013 /// correctly if called from `parse_dot_or_call_expr()`.
1014 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1015 maybe_recover_from_interpolated_ty_qpath!(self, true);
1016 maybe_whole_expr!(self);
1018 // Outer attributes are already parsed and will be
1019 // added to the return value after the fact.
1021 // Therefore, prevent sub-parser from parsing
1022 // attributes by giving them a empty "already-parsed" list.
1023 let attrs = AttrVec::new();
1025 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
1026 let lo = self.token.span;
1027 if let token::Literal(_) = self.token.kind {
1028 // This match arm is a special-case of the `_` match arm below and
1029 // could be removed without changing functionality, but it's faster
1030 // to have it here, especially for programs with large constants.
1031 self.parse_lit_expr(attrs)
1032 } else if self.check(&token::OpenDelim(token::Paren)) {
1033 self.parse_tuple_parens_expr(attrs)
1034 } else if self.check(&token::OpenDelim(token::Brace)) {
1035 self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs)
1036 } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) {
1037 self.parse_closure_expr(attrs)
1038 } else if self.check(&token::OpenDelim(token::Bracket)) {
1039 self.parse_array_or_repeat_expr(attrs)
1040 } else if self.eat_lt() {
1041 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
1042 Ok(self.mk_expr(lo.to(path.span), ExprKind::Path(Some(qself), path), attrs))
1043 } else if self.check_path() {
1044 self.parse_path_start_expr(attrs)
1045 } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
1046 self.parse_closure_expr(attrs)
1047 } else if self.eat_keyword(kw::If) {
1048 self.parse_if_expr(attrs)
1049 } else if self.check_keyword(kw::For) {
1050 if self.choose_generics_over_qpath(1) {
1051 // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery,
1052 // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns.
1053 // When `for <Foo as Bar>::Proj in $expr $block` is wanted,
1054 // you can disambiguate in favor of a pattern with `(...)`.
1055 self.recover_quantified_closure_expr(attrs)
1057 assert!(self.eat_keyword(kw::For));
1058 self.parse_for_expr(None, self.prev_token.span, attrs)
1060 } else if self.eat_keyword(kw::While) {
1061 self.parse_while_expr(None, self.prev_token.span, attrs)
1062 } else if let Some(label) = self.eat_label() {
1063 self.parse_labeled_expr(label, attrs)
1064 } else if self.eat_keyword(kw::Loop) {
1065 self.parse_loop_expr(None, self.prev_token.span, attrs)
1066 } else if self.eat_keyword(kw::Continue) {
1067 let kind = ExprKind::Continue(self.eat_label());
1068 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1069 } else if self.eat_keyword(kw::Match) {
1070 let match_sp = self.prev_token.span;
1071 self.parse_match_expr(attrs).map_err(|mut err| {
1072 err.span_label(match_sp, "while parsing this match expression");
1075 } else if self.eat_keyword(kw::Unsafe) {
1076 self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs)
1077 } else if self.check_inline_const(0) {
1078 self.parse_const_block(lo.to(self.token.span))
1079 } else if self.is_do_catch_block() {
1080 self.recover_do_catch(attrs)
1081 } else if self.is_try_block() {
1082 self.expect_keyword(kw::Try)?;
1083 self.parse_try_block(lo, attrs)
1084 } else if self.eat_keyword(kw::Return) {
1085 self.parse_return_expr(attrs)
1086 } else if self.eat_keyword(kw::Break) {
1087 self.parse_break_expr(attrs)
1088 } else if self.eat_keyword(kw::Yield) {
1089 self.parse_yield_expr(attrs)
1090 } else if self.eat_keyword(kw::Let) {
1091 self.parse_let_expr(attrs)
1092 } else if self.eat_keyword(kw::Underscore) {
1093 self.sess.gated_spans.gate(sym::destructuring_assignment, self.prev_token.span);
1094 Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore, attrs))
1095 } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1096 // Don't complain about bare semicolons after unclosed braces
1097 // recovery in order to keep the error count down. Fixing the
1098 // delimiters will possibly also fix the bare semicolon found in
1099 // expression context. For example, silence the following error:
1101 // error: expected expression, found `;`
1105 // | ^ expected expression
1107 Ok(self.mk_expr_err(self.token.span))
1108 } else if self.token.uninterpolated_span().rust_2018() {
1109 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1110 if self.check_keyword(kw::Async) {
1111 if self.is_async_block() {
1112 // Check for `async {` and `async move {`.
1113 self.parse_async_block(attrs)
1115 self.parse_closure_expr(attrs)
1117 } else if self.eat_keyword(kw::Await) {
1118 self.recover_incorrect_await_syntax(lo, self.prev_token.span, attrs)
1120 self.parse_lit_expr(attrs)
1123 self.parse_lit_expr(attrs)
1127 fn maybe_collect_tokens(
1130 f: impl FnOnce(&mut Self) -> PResult<'a, P<Expr>>,
1131 ) -> PResult<'a, P<Expr>> {
1133 let (mut expr, tokens) = self.collect_tokens(f)?;
1134 expr.tokens = tokens;
1141 fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1142 let lo = self.token.span;
1143 match self.parse_opt_lit() {
1145 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs);
1146 self.maybe_recover_from_bad_qpath(expr, true)
1148 None => self.try_macro_suggestion(),
1152 fn parse_tuple_parens_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1153 let lo = self.token.span;
1154 self.expect(&token::OpenDelim(token::Paren))?;
1155 attrs.extend(self.parse_inner_attributes()?); // `(#![foo] a, b, ...)` is OK.
1156 let (es, trailing_comma) = match self.parse_seq_to_end(
1157 &token::CloseDelim(token::Paren),
1158 SeqSep::trailing_allowed(token::Comma),
1159 |p| p.parse_expr_catch_underscore(),
1162 Err(err) => return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err))),
1164 let kind = if es.len() == 1 && !trailing_comma {
1165 // `(e)` is parenthesized `e`.
1166 ExprKind::Paren(es.into_iter().next().unwrap())
1168 // `(e,)` is a tuple with only one field, `e`.
1171 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1172 self.maybe_recover_from_bad_qpath(expr, true)
1175 fn parse_array_or_repeat_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1176 let lo = self.token.span;
1179 attrs.extend(self.parse_inner_attributes()?);
1181 let close = &token::CloseDelim(token::Bracket);
1182 let kind = if self.eat(close) {
1184 ExprKind::Array(Vec::new())
1187 let first_expr = self.parse_expr()?;
1188 if self.eat(&token::Semi) {
1189 // Repeating array syntax: `[ 0; 512 ]`
1190 let count = self.parse_anon_const_expr()?;
1191 self.expect(close)?;
1192 ExprKind::Repeat(first_expr, count)
1193 } else if self.eat(&token::Comma) {
1194 // Vector with two or more elements.
1195 let sep = SeqSep::trailing_allowed(token::Comma);
1196 let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1197 let mut exprs = vec![first_expr];
1198 exprs.extend(remaining_exprs);
1199 ExprKind::Array(exprs)
1201 // Vector with one element
1202 self.expect(close)?;
1203 ExprKind::Array(vec![first_expr])
1206 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1207 self.maybe_recover_from_bad_qpath(expr, true)
1210 fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1211 let path = self.parse_path(PathStyle::Expr)?;
1214 // `!`, as an operator, is prefix, so we know this isn't that.
1215 let (hi, kind) = if self.eat(&token::Not) {
1216 // MACRO INVOCATION expression
1219 args: self.parse_mac_args()?,
1220 prior_type_ascription: self.last_type_ascription,
1222 (self.prev_token.span, ExprKind::MacCall(mac))
1223 } else if self.check(&token::OpenDelim(token::Brace)) {
1224 if let Some(expr) = self.maybe_parse_struct_expr(&path, &attrs) {
1227 (path.span, ExprKind::Path(None, path))
1230 (path.span, ExprKind::Path(None, path))
1233 let expr = self.mk_expr(lo.to(hi), kind, attrs);
1234 self.maybe_recover_from_bad_qpath(expr, true)
1237 /// Parse `'label: $expr`. The label is already parsed.
1238 fn parse_labeled_expr(&mut self, label: Label, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1239 let lo = label.ident.span;
1240 let label = Some(label);
1241 let ate_colon = self.eat(&token::Colon);
1242 let expr = if self.eat_keyword(kw::While) {
1243 self.parse_while_expr(label, lo, attrs)
1244 } else if self.eat_keyword(kw::For) {
1245 self.parse_for_expr(label, lo, attrs)
1246 } else if self.eat_keyword(kw::Loop) {
1247 self.parse_loop_expr(label, lo, attrs)
1248 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1249 self.parse_block_expr(label, lo, BlockCheckMode::Default, attrs)
1251 let msg = "expected `while`, `for`, `loop` or `{` after a label";
1252 self.struct_span_err(self.token.span, msg).span_label(self.token.span, msg).emit();
1253 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1258 self.error_labeled_expr_must_be_followed_by_colon(lo, expr.span);
1264 fn error_labeled_expr_must_be_followed_by_colon(&self, lo: Span, span: Span) {
1265 self.struct_span_err(span, "labeled expression must be followed by `:`")
1266 .span_label(lo, "the label")
1267 .span_suggestion_short(
1269 "add `:` after the label",
1271 Applicability::MachineApplicable,
1273 .note("labels are used before loops and blocks, allowing e.g., `break 'label` to them")
1277 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1278 fn recover_do_catch(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1279 let lo = self.token.span;
1281 self.bump(); // `do`
1282 self.bump(); // `catch`
1284 let span_dc = lo.to(self.prev_token.span);
1285 self.struct_span_err(span_dc, "found removed `do catch` syntax")
1288 "replace with the new syntax",
1290 Applicability::MachineApplicable,
1292 .note("following RFC #2388, the new non-placeholder syntax is `try`")
1295 self.parse_try_block(lo, attrs)
1298 /// Parse an expression if the token can begin one.
1299 fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1300 Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1303 /// Parse `"return" expr?`.
1304 fn parse_return_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1305 let lo = self.prev_token.span;
1306 let kind = ExprKind::Ret(self.parse_expr_opt()?);
1307 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1308 self.maybe_recover_from_bad_qpath(expr, true)
1311 /// Parse `"('label ":")? break expr?`.
1312 fn parse_break_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1313 let lo = self.prev_token.span;
1314 let label = self.eat_label();
1315 let kind = if self.token != token::OpenDelim(token::Brace)
1316 || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1318 self.parse_expr_opt()?
1322 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind), attrs);
1323 self.maybe_recover_from_bad_qpath(expr, true)
1326 /// Parse `"yield" expr?`.
1327 fn parse_yield_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1328 let lo = self.prev_token.span;
1329 let kind = ExprKind::Yield(self.parse_expr_opt()?);
1330 let span = lo.to(self.prev_token.span);
1331 self.sess.gated_spans.gate(sym::generators, span);
1332 let expr = self.mk_expr(span, kind, attrs);
1333 self.maybe_recover_from_bad_qpath(expr, true)
1336 /// Returns a string literal if the next token is a string literal.
1337 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1338 /// and returns `None` if the next token is not literal at all.
1339 pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
1340 match self.parse_opt_lit() {
1341 Some(lit) => match lit.kind {
1342 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1344 symbol: lit.token.symbol,
1345 suffix: lit.token.suffix,
1349 _ => Err(Some(lit)),
1355 pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> {
1356 self.parse_opt_lit().ok_or_else(|| {
1357 let msg = format!("unexpected token: {}", super::token_descr(&self.token));
1358 self.struct_span_err(self.token.span, &msg)
1362 /// Matches `lit = true | false | token_lit`.
1363 /// Returns `None` if the next token is not a literal.
1364 pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
1365 let mut recovered = None;
1366 if self.token == token::Dot {
1367 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1368 // dot would follow an optional literal, so we do this unconditionally.
1369 recovered = self.look_ahead(1, |next_token| {
1370 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1373 if self.token.span.hi() == next_token.span.lo() {
1374 let s = String::from("0.") + &symbol.as_str();
1375 let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1376 return Some(Token::new(kind, self.token.span.to(next_token.span)));
1381 if let Some(token) = &recovered {
1383 self.error_float_lits_must_have_int_part(&token);
1387 let token = recovered.as_ref().unwrap_or(&self.token);
1388 match Lit::from_token(token) {
1393 Err(LitError::NotLiteral) => None,
1395 let span = token.span;
1396 let lit = match token.kind {
1397 token::Literal(lit) => lit,
1398 _ => unreachable!(),
1401 self.report_lit_error(err, lit, span);
1402 // Pack possible quotes and prefixes from the original literal into
1403 // the error literal's symbol so they can be pretty-printed faithfully.
1404 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1405 let symbol = Symbol::intern(&suffixless_lit.to_string());
1406 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1407 Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!()))
1412 fn error_float_lits_must_have_int_part(&self, token: &Token) {
1413 self.struct_span_err(token.span, "float literals must have an integer part")
1416 "must have an integer part",
1417 pprust::token_to_string(token),
1418 Applicability::MachineApplicable,
1423 fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) {
1424 // Checks if `s` looks like i32 or u1234 etc.
1425 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1426 s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
1429 let token::Lit { kind, suffix, .. } = lit;
1431 // `NotLiteral` is not an error by itself, so we don't report
1432 // it and give the parser opportunity to try something else.
1433 LitError::NotLiteral => {}
1434 // `LexerError` *is* an error, but it was already reported
1435 // by lexer, so here we don't report it the second time.
1436 LitError::LexerError => {}
1437 LitError::InvalidSuffix => {
1438 self.expect_no_suffix(
1440 &format!("{} {} literal", kind.article(), kind.descr()),
1444 LitError::InvalidIntSuffix => {
1445 let suf = suffix.expect("suffix error with no suffix").as_str();
1446 if looks_like_width_suffix(&['i', 'u'], &suf) {
1447 // If it looks like a width, try to be helpful.
1448 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
1449 self.struct_span_err(span, &msg)
1450 .help("valid widths are 8, 16, 32, 64 and 128")
1453 let msg = format!("invalid suffix `{}` for integer literal", suf);
1454 self.struct_span_err(span, &msg)
1455 .span_label(span, format!("invalid suffix `{}`", suf))
1456 .help("the suffix must be one of the integral types (`u32`, `isize`, etc)")
1460 LitError::InvalidFloatSuffix => {
1461 let suf = suffix.expect("suffix error with no suffix").as_str();
1462 if looks_like_width_suffix(&['f'], &suf) {
1463 // If it looks like a width, try to be helpful.
1464 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
1465 self.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit();
1467 let msg = format!("invalid suffix `{}` for float literal", suf);
1468 self.struct_span_err(span, &msg)
1469 .span_label(span, format!("invalid suffix `{}`", suf))
1470 .help("valid suffixes are `f32` and `f64`")
1474 LitError::NonDecimalFloat(base) => {
1475 let descr = match base {
1476 16 => "hexadecimal",
1479 _ => unreachable!(),
1481 self.struct_span_err(span, &format!("{} float literal is not supported", descr))
1482 .span_label(span, "not supported")
1485 LitError::IntTooLarge => {
1486 self.struct_span_err(span, "integer literal is too large").emit();
1491 pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) {
1492 if let Some(suf) = suffix {
1493 let mut err = if kind == "a tuple index"
1494 && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf)
1496 // #59553: warn instead of reject out of hand to allow the fix to percolate
1497 // through the ecosystem when people fix their macros
1501 .struct_span_warn(sp, &format!("suffixes on {} are invalid", kind));
1503 "`{}` is *temporarily* accepted on tuple index fields as it was \
1504 incorrectly accepted on stable for a few releases",
1508 "on proc macros, you'll want to use `syn::Index::from` or \
1509 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1510 to tuple field access",
1513 "see issue #60210 <https://github.com/rust-lang/rust/issues/60210> \
1514 for more information",
1518 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1520 err.span_label(sp, format!("invalid suffix `{}`", suf));
1525 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1526 /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
1527 pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1528 maybe_whole_expr!(self);
1530 let lo = self.token.span;
1531 let minus_present = self.eat(&token::BinOp(token::Minus));
1532 let lit = self.parse_lit()?;
1533 let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new());
1537 lo.to(self.prev_token.span),
1538 self.mk_unary(UnOp::Neg, expr),
1546 /// Parses a block or unsafe block.
1547 pub(super) fn parse_block_expr(
1549 opt_label: Option<Label>,
1551 blk_mode: BlockCheckMode,
1553 ) -> PResult<'a, P<Expr>> {
1554 if let Some(label) = opt_label {
1555 self.sess.gated_spans.gate(sym::label_break_value, label.ident.span);
1558 if self.token.is_whole_block() {
1559 self.struct_span_err(self.token.span, "cannot use a `block` macro fragment here")
1560 .span_label(lo.to(self.token.span), "the `block` fragment is within this context")
1564 let (inner_attrs, blk) = self.parse_block_common(lo, blk_mode)?;
1565 attrs.extend(inner_attrs);
1566 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs))
1569 /// Recover on an explicitly quantified closure expression, e.g., `for<'a> |x: &'a u8| *x + 1`.
1570 fn recover_quantified_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1571 let lo = self.token.span;
1572 let _ = self.parse_late_bound_lifetime_defs()?;
1573 let span_for = lo.to(self.prev_token.span);
1574 let closure = self.parse_closure_expr(attrs)?;
1576 self.struct_span_err(span_for, "cannot introduce explicit parameters for a closure")
1577 .span_label(closure.span, "the parameters are attached to this closure")
1580 "remove the parameters",
1582 Applicability::MachineApplicable,
1586 Ok(self.mk_expr_err(lo.to(closure.span)))
1589 /// Parses a closure expression (e.g., `move |args| expr`).
1590 fn parse_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1591 let lo = self.token.span;
1594 if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
1596 let asyncness = if self.token.uninterpolated_span().rust_2018() {
1597 self.parse_asyncness()
1601 if let Async::Yes { span, .. } = asyncness {
1602 // Feature-gate `async ||` closures.
1603 self.sess.gated_spans.gate(sym::async_closure, span);
1606 let capture_clause = self.parse_capture_clause();
1607 let decl = self.parse_fn_block_decl()?;
1608 let decl_hi = self.prev_token.span;
1609 let body = match decl.output {
1610 FnRetTy::Default(_) => {
1611 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
1612 self.parse_expr_res(restrictions, None)?
1615 // If an explicit return type is given, require a block to appear (RFC 968).
1616 let body_lo = self.token.span;
1617 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, AttrVec::new())?
1623 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
1628 /// Parses an optional `move` prefix to a closure-like construct.
1629 fn parse_capture_clause(&mut self) -> CaptureBy {
1630 if self.eat_keyword(kw::Move) { CaptureBy::Value } else { CaptureBy::Ref }
1633 /// Parses the `|arg, arg|` header of a closure.
1634 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
1635 let inputs = if self.eat(&token::OrOr) {
1638 self.expect(&token::BinOp(token::Or))?;
1640 .parse_seq_to_before_tokens(
1641 &[&token::BinOp(token::Or), &token::OrOr],
1642 SeqSep::trailing_allowed(token::Comma),
1643 TokenExpectType::NoExpect,
1644 |p| p.parse_fn_block_param(),
1650 let output = self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes)?;
1652 Ok(P(FnDecl { inputs, output }))
1655 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1656 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
1657 let lo = self.token.span;
1658 let attrs = self.parse_outer_attributes()?;
1659 let pat = self.parse_pat(PARAM_EXPECTED)?;
1660 let ty = if self.eat(&token::Colon) {
1663 self.mk_ty(self.prev_token.span, TyKind::Infer)
1666 attrs: attrs.into(),
1669 span: lo.to(self.token.span),
1671 is_placeholder: false,
1675 /// Parses an `if` expression (`if` token already eaten).
1676 fn parse_if_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1677 let lo = self.prev_token.span;
1678 let cond = self.parse_cond_expr()?;
1680 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1681 // verify that the last statement is either an implicit return (no `;`) or an explicit
1682 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1683 // the dead code lint.
1684 let thn = if self.eat_keyword(kw::Else) || !cond.returns() {
1685 self.error_missing_if_cond(lo, cond.span)
1687 let attrs = self.parse_outer_attributes()?; // For recovery.
1688 let not_block = self.token != token::OpenDelim(token::Brace);
1689 let block = self.parse_block().map_err(|mut err| {
1691 err.span_label(lo, "this `if` expression has a condition, but no block");
1692 if let ExprKind::Binary(_, _, ref right) = cond.kind {
1693 if let ExprKind::Block(_, _) = right.kind {
1694 err.help("maybe you forgot the right operand of the condition?");
1700 self.error_on_if_block_attrs(lo, false, block.span, &attrs);
1703 let els = if self.eat_keyword(kw::Else) { Some(self.parse_else_expr()?) } else { None };
1704 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els), attrs))
1707 fn error_missing_if_cond(&self, lo: Span, span: Span) -> P<ast::Block> {
1708 let sp = self.sess.source_map().next_point(lo);
1709 self.struct_span_err(sp, "missing condition for `if` expression")
1710 .span_label(sp, "expected if condition here")
1712 self.mk_block_err(span)
1715 /// Parses the condition of a `if` or `while` expression.
1716 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
1717 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1719 if let ExprKind::Let(..) = cond.kind {
1720 // Remove the last feature gating of a `let` expression since it's stable.
1721 self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
1727 /// Parses a `let $pat = $expr` pseudo-expression.
1728 /// The `let` token has already been eaten.
1729 fn parse_let_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1730 let lo = self.prev_token.span;
1731 let pat = self.parse_top_pat(GateOr::No)?;
1732 self.expect(&token::Eq)?;
1733 let expr = self.with_res(self.restrictions | Restrictions::NO_STRUCT_LITERAL, |this| {
1734 this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
1736 let span = lo.to(expr.span);
1737 self.sess.gated_spans.gate(sym::let_chains, span);
1738 Ok(self.mk_expr(span, ExprKind::Let(pat, expr), attrs))
1741 /// Parses an `else { ... }` expression (`else` token already eaten).
1742 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
1743 let ctx_span = self.prev_token.span; // `else`
1744 let attrs = self.parse_outer_attributes()?; // For recovery.
1745 let expr = if self.eat_keyword(kw::If) {
1746 self.parse_if_expr(AttrVec::new())?
1748 let blk = self.parse_block()?;
1749 self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new())
1751 self.error_on_if_block_attrs(ctx_span, true, expr.span, &attrs);
1755 fn error_on_if_block_attrs(
1760 attrs: &[ast::Attribute],
1762 let (span, last) = match attrs {
1764 [x0 @ xn] | [x0, .., xn] => (x0.span.to(xn.span), xn.span),
1766 let ctx = if is_ctx_else { "else" } else { "if" };
1767 self.struct_span_err(last, "outer attributes are not allowed on `if` and `else` branches")
1768 .span_label(branch_span, "the attributes are attached to this branch")
1769 .span_label(ctx_span, format!("the branch belongs to this `{}`", ctx))
1772 "remove the attributes",
1774 Applicability::MachineApplicable,
1779 /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
1782 opt_label: Option<Label>,
1785 ) -> PResult<'a, P<Expr>> {
1786 // Record whether we are about to parse `for (`.
1787 // This is used below for recovery in case of `for ( $stuff ) $block`
1788 // in which case we will suggest `for $stuff $block`.
1789 let begin_paren = match self.token.kind {
1790 token::OpenDelim(token::Paren) => Some(self.token.span),
1794 let pat = self.parse_top_pat(GateOr::Yes)?;
1795 if !self.eat_keyword(kw::In) {
1796 self.error_missing_in_for_loop();
1798 self.check_for_for_in_in_typo(self.prev_token.span);
1799 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1801 let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
1803 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
1804 attrs.extend(iattrs);
1806 let kind = ExprKind::ForLoop(pat, expr, loop_block, opt_label);
1807 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1810 fn error_missing_in_for_loop(&mut self) {
1811 let (span, msg, sugg) = if self.token.is_ident_named(sym::of) {
1812 // Possibly using JS syntax (#75311).
1813 let span = self.token.span;
1815 (span, "try using `in` here instead", "in")
1817 (self.prev_token.span.between(self.token.span), "try adding `in` here", " in ")
1819 self.struct_span_err(span, "missing `in` in `for` loop")
1820 .span_suggestion_short(
1824 // Has been misleading, at least in the past (closed Issue #48492).
1825 Applicability::MaybeIncorrect,
1830 /// Parses a `while` or `while let` expression (`while` token already eaten).
1831 fn parse_while_expr(
1833 opt_label: Option<Label>,
1836 ) -> PResult<'a, P<Expr>> {
1837 let cond = self.parse_cond_expr()?;
1838 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1839 attrs.extend(iattrs);
1840 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::While(cond, body, opt_label), attrs))
1843 /// Parses `loop { ... }` (`loop` token already eaten).
1846 opt_label: Option<Label>,
1849 ) -> PResult<'a, P<Expr>> {
1850 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1851 attrs.extend(iattrs);
1852 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::Loop(body, opt_label), attrs))
1855 fn eat_label(&mut self) -> Option<Label> {
1856 self.token.lifetime().map(|ident| {
1862 /// Parses a `match ... { ... }` expression (`match` token already eaten).
1863 fn parse_match_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1864 let match_span = self.prev_token.span;
1865 let lo = self.prev_token.span;
1866 let scrutinee = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1867 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
1868 if self.token == token::Semi {
1869 e.span_suggestion_short(
1871 "try removing this `match`",
1873 Applicability::MaybeIncorrect, // speculative
1878 attrs.extend(self.parse_inner_attributes()?);
1880 let mut arms: Vec<Arm> = Vec::new();
1881 while self.token != token::CloseDelim(token::Brace) {
1882 match self.parse_arm() {
1883 Ok(arm) => arms.push(arm),
1885 // Recover by skipping to the end of the block.
1887 self.recover_stmt();
1888 let span = lo.to(self.token.span);
1889 if self.token == token::CloseDelim(token::Brace) {
1892 return Ok(self.mk_expr(span, ExprKind::Match(scrutinee, arms), attrs));
1896 let hi = self.token.span;
1898 Ok(self.mk_expr(lo.to(hi), ExprKind::Match(scrutinee, arms), attrs))
1901 pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
1902 let attrs = self.parse_outer_attributes()?;
1903 let lo = self.token.span;
1904 let pat = self.parse_top_pat(GateOr::No)?;
1905 let guard = if self.eat_keyword(kw::If) {
1906 let if_span = self.prev_token.span;
1907 let cond = self.parse_expr()?;
1908 if let ExprKind::Let(..) = cond.kind {
1909 // Remove the last feature gating of a `let` expression since it's stable.
1910 self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
1911 let span = if_span.to(cond.span);
1912 self.sess.gated_spans.gate(sym::if_let_guard, span);
1918 let arrow_span = self.token.span;
1919 self.expect(&token::FatArrow)?;
1920 let arm_start_span = self.token.span;
1922 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| {
1923 err.span_label(arrow_span, "while parsing the `match` arm starting here");
1927 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
1928 && self.token != token::CloseDelim(token::Brace);
1930 let hi = self.prev_token.span;
1933 let sm = self.sess.source_map();
1934 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]).map_err(
1936 match (sm.span_to_lines(expr.span), sm.span_to_lines(arm_start_span)) {
1937 (Ok(ref expr_lines), Ok(ref arm_start_lines))
1938 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
1939 && expr_lines.lines.len() == 2
1940 && self.token == token::FatArrow =>
1942 // We check whether there's any trailing code in the parse span,
1943 // if there isn't, we very likely have the following:
1946 // | -- - missing comma
1950 // | - ^^ self.token.span
1952 // | parsed until here as `"y" & X`
1953 err.span_suggestion_short(
1954 arm_start_span.shrink_to_hi(),
1955 "missing a comma here to end this `match` arm",
1957 Applicability::MachineApplicable,
1963 "while parsing the `match` arm starting here",
1971 self.eat(&token::Comma);
1981 is_placeholder: false,
1985 /// Parses a `try {...}` expression (`try` token already eaten).
1986 fn parse_try_block(&mut self, span_lo: Span, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1987 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1988 attrs.extend(iattrs);
1989 if self.eat_keyword(kw::Catch) {
1990 let mut error = self.struct_span_err(
1991 self.prev_token.span,
1992 "keyword `catch` cannot follow a `try` block",
1994 error.help("try using `match` on the result of the `try` block instead");
1998 let span = span_lo.to(body.span);
1999 self.sess.gated_spans.gate(sym::try_blocks, span);
2000 Ok(self.mk_expr(span, ExprKind::TryBlock(body), attrs))
2004 fn is_do_catch_block(&self) -> bool {
2005 self.token.is_keyword(kw::Do)
2006 && self.is_keyword_ahead(1, &[kw::Catch])
2007 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2008 && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
2011 fn is_try_block(&self) -> bool {
2012 self.token.is_keyword(kw::Try)
2013 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2014 && self.token.uninterpolated_span().rust_2018()
2017 /// Parses an `async move? {...}` expression.
2018 fn parse_async_block(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2019 let lo = self.token.span;
2020 self.expect_keyword(kw::Async)?;
2021 let capture_clause = self.parse_capture_clause();
2022 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2023 attrs.extend(iattrs);
2024 let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);
2025 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
2028 fn is_async_block(&self) -> bool {
2029 self.token.is_keyword(kw::Async)
2032 self.is_keyword_ahead(1, &[kw::Move])
2033 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2036 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2040 fn is_certainly_not_a_block(&self) -> bool {
2041 self.look_ahead(1, |t| t.is_ident())
2043 // `{ ident, ` cannot start a block.
2044 self.look_ahead(2, |t| t == &token::Comma)
2045 || self.look_ahead(2, |t| t == &token::Colon)
2047 // `{ ident: token, ` cannot start a block.
2048 self.look_ahead(4, |t| t == &token::Comma) ||
2049 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
2050 self.look_ahead(3, |t| !t.can_begin_type())
2055 fn maybe_parse_struct_expr(
2059 ) -> Option<PResult<'a, P<Expr>>> {
2060 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2061 if struct_allowed || self.is_certainly_not_a_block() {
2062 if let Err(err) = self.expect(&token::OpenDelim(token::Brace)) {
2063 return Some(Err(err));
2065 let expr = self.parse_struct_expr(path.clone(), attrs.clone(), true);
2066 if let (Ok(expr), false) = (&expr, struct_allowed) {
2067 // This is a struct literal, but we don't can't accept them here.
2068 self.error_struct_lit_not_allowed_here(path.span, expr.span);
2075 fn error_struct_lit_not_allowed_here(&self, lo: Span, sp: Span) {
2076 self.struct_span_err(sp, "struct literals are not allowed here")
2077 .multipart_suggestion(
2078 "surround the struct literal with parentheses",
2079 vec![(lo.shrink_to_lo(), "(".to_string()), (sp.shrink_to_hi(), ")".to_string())],
2080 Applicability::MachineApplicable,
2085 /// Precondition: already parsed the '{'.
2086 pub(super) fn parse_struct_expr(
2091 ) -> PResult<'a, P<Expr>> {
2092 let mut fields = Vec::new();
2093 let mut base = ast::StructRest::None;
2094 let mut recover_async = false;
2096 attrs.extend(self.parse_inner_attributes()?);
2098 let mut async_block_err = |e: &mut DiagnosticBuilder<'_>, span: Span| {
2099 recover_async = true;
2100 e.span_label(span, "`async` blocks are only allowed in the 2018 edition");
2101 e.help("set `edition = \"2018\"` in `Cargo.toml`");
2102 e.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
2105 while self.token != token::CloseDelim(token::Brace) {
2106 if self.eat(&token::DotDot) {
2107 let exp_span = self.prev_token.span;
2108 // We permit `.. }` on the left-hand side of a destructuring assignment.
2109 if self.check(&token::CloseDelim(token::Brace)) {
2110 self.sess.gated_spans.gate(sym::destructuring_assignment, self.prev_token.span);
2111 base = ast::StructRest::Rest(self.prev_token.span.shrink_to_hi());
2114 match self.parse_expr() {
2115 Ok(e) => base = ast::StructRest::Base(e),
2116 Err(mut e) if recover => {
2118 self.recover_stmt();
2120 Err(e) => return Err(e),
2122 self.recover_struct_comma_after_dotdot(exp_span);
2126 let recovery_field = self.find_struct_error_after_field_looking_code();
2127 let parsed_field = match self.parse_field() {
2130 if pth == kw::Async {
2131 async_block_err(&mut e, pth.span);
2133 e.span_label(pth.span, "while parsing this struct");
2137 // If the next token is a comma, then try to parse
2138 // what comes next as additional fields, rather than
2139 // bailing out until next `}`.
2140 if self.token != token::Comma {
2141 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2142 if self.token != token::Comma {
2150 match self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]) {
2152 if let Some(f) = parsed_field.or(recovery_field) {
2153 // Only include the field if there's no parse error for the field name.
2158 if pth == kw::Async {
2159 async_block_err(&mut e, pth.span);
2161 e.span_label(pth.span, "while parsing this struct");
2162 if let Some(f) = recovery_field {
2165 self.prev_token.span.shrink_to_hi(),
2166 "try adding a comma",
2168 Applicability::MachineApplicable,
2176 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2177 self.eat(&token::Comma);
2182 let span = pth.span.to(self.token.span);
2183 self.expect(&token::CloseDelim(token::Brace))?;
2184 let expr = if recover_async { ExprKind::Err } else { ExprKind::Struct(pth, fields, base) };
2185 Ok(self.mk_expr(span, expr, attrs))
2188 /// Use in case of error after field-looking code: `S { foo: () with a }`.
2189 fn find_struct_error_after_field_looking_code(&self) -> Option<Field> {
2190 match self.token.ident() {
2191 Some((ident, is_raw))
2192 if (is_raw || !ident.is_reserved())
2193 && self.look_ahead(1, |t| *t == token::Colon) =>
2197 span: self.token.span,
2198 expr: self.mk_expr_err(self.token.span),
2199 is_shorthand: false,
2200 attrs: AttrVec::new(),
2202 is_placeholder: false,
2209 fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
2210 if self.token != token::Comma {
2213 self.struct_span_err(
2214 span.to(self.prev_token.span),
2215 "cannot use a comma after the base struct",
2217 .span_suggestion_short(
2219 "remove this comma",
2221 Applicability::MachineApplicable,
2223 .note("the base struct must always be the last field")
2225 self.recover_stmt();
2228 /// Parses `ident (COLON expr)?`.
2229 fn parse_field(&mut self) -> PResult<'a, Field> {
2230 let attrs = self.parse_outer_attributes()?.into();
2231 let lo = self.token.span;
2233 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2234 let is_shorthand = !self.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
2235 let (ident, expr) = if is_shorthand {
2236 // Mimic `x: x` for the `x` field shorthand.
2237 let ident = self.parse_ident_common(false)?;
2238 let path = ast::Path::from_ident(ident);
2239 (ident, self.mk_expr(ident.span, ExprKind::Path(None, path), AttrVec::new()))
2241 let ident = self.parse_field_name()?;
2242 self.error_on_eq_field_init(ident);
2244 (ident, self.parse_expr()?)
2248 span: lo.to(expr.span),
2253 is_placeholder: false,
2257 /// Check for `=`. This means the source incorrectly attempts to
2258 /// initialize a field with an eq rather than a colon.
2259 fn error_on_eq_field_init(&self, field_name: Ident) {
2260 if self.token != token::Eq {
2264 self.struct_span_err(self.token.span, "expected `:`, found `=`")
2266 field_name.span.shrink_to_hi().to(self.token.span),
2267 "replace equals symbol with a colon",
2269 Applicability::MachineApplicable,
2274 fn err_dotdotdot_syntax(&self, span: Span) {
2275 self.struct_span_err(span, "unexpected token: `...`")
2278 "use `..` for an exclusive range",
2280 Applicability::MaybeIncorrect,
2284 "or `..=` for an inclusive range",
2286 Applicability::MaybeIncorrect,
2291 fn err_larrow_operator(&self, span: Span) {
2292 self.struct_span_err(span, "unexpected token: `<-`")
2295 "if you meant to write a comparison against a negative value, add a \
2296 space in between `<` and `-`",
2298 Applicability::MaybeIncorrect,
2303 fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2304 ExprKind::AssignOp(binop, lhs, rhs)
2309 start: Option<P<Expr>>,
2310 end: Option<P<Expr>>,
2311 limits: RangeLimits,
2312 ) -> PResult<'a, ExprKind> {
2313 if end.is_none() && limits == RangeLimits::Closed {
2314 self.error_inclusive_range_with_no_end(self.prev_token.span);
2317 Ok(ExprKind::Range(start, end, limits))
2321 fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
2322 ExprKind::Unary(unop, expr)
2325 fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2326 ExprKind::Binary(binop, lhs, rhs)
2329 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
2330 ExprKind::Index(expr, idx)
2333 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
2334 ExprKind::Call(f, args)
2337 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2338 let span = lo.to(self.prev_token.span);
2339 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), AttrVec::new());
2340 self.recover_from_await_method_call();
2344 crate fn mk_expr(&self, span: Span, kind: ExprKind, attrs: AttrVec) -> P<Expr> {
2345 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None })
2348 pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
2349 self.mk_expr(span, ExprKind::Err, AttrVec::new())
2352 /// Create expression span ensuring the span of the parent node
2353 /// is larger than the span of lhs and rhs, including the attributes.
2354 fn mk_expr_sp(&self, lhs: &P<Expr>, lhs_span: Span, rhs_span: Span) -> Span {
2357 .find(|a| a.style == AttrStyle::Outer)
2358 .map_or(lhs_span, |a| a.span)