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::util::classify;
10 use rustc_ast::util::literal::LitError;
11 use rustc_ast::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity};
12 use rustc_ast::{self as ast, AttrStyle, AttrVec, CaptureBy, Field, Lit, UnOp, DUMMY_NODE_ID};
13 use rustc_ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty, TyKind};
14 use rustc_ast::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits};
15 use rustc_ast_pretty::pprust;
16 use rustc_errors::{Applicability, DiagnosticBuilder, PResult};
17 use rustc_span::source_map::{self, Span, Spanned};
18 use rustc_span::symbol::{kw, sym, Ident, Symbol};
22 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
23 /// dropped into the token stream, which happens while parsing the result of
24 /// macro expansion). Placement of these is not as complex as I feared it would
25 /// be. The important thing is to make sure that lookahead doesn't balk at
26 /// `token::Interpolated` tokens.
27 macro_rules! maybe_whole_expr {
29 if let token::Interpolated(nt) = &$p.token.kind {
31 token::NtExpr(e) | token::NtLiteral(e) => {
36 token::NtPath(path) => {
37 let path = path.clone();
41 ExprKind::Path(None, path),
45 token::NtBlock(block) => {
46 let block = block.clone();
50 ExprKind::Block(block, None),
61 pub(super) enum LhsExpr {
63 AttributesParsed(AttrVec),
64 AlreadyParsed(P<Expr>),
67 impl From<Option<AttrVec>> for LhsExpr {
68 /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
69 /// and `None` into `LhsExpr::NotYetParsed`.
71 /// This conversion does not allocate.
72 fn from(o: Option<AttrVec>) -> Self {
73 if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed }
77 impl From<P<Expr>> for LhsExpr {
78 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
80 /// This conversion does not allocate.
81 fn from(expr: P<Expr>) -> Self {
82 LhsExpr::AlreadyParsed(expr)
87 /// Parses an expression.
89 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
90 self.parse_expr_res(Restrictions::empty(), None)
93 pub(super) fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> {
94 self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
97 fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P<Expr>> {
98 match self.parse_expr() {
100 Err(mut err) => match self.token.ident() {
101 Some((Ident { name: kw::Underscore, .. }, false))
102 if self.look_ahead(1, |t| t == &token::Comma) =>
104 // Special-case handling of `foo(_, _, _)`
107 Ok(self.mk_expr(self.prev_token.span, ExprKind::Err, AttrVec::new()))
114 /// Parses a sequence of expressions delimited by parentheses.
115 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
116 self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r)
119 /// Parses an expression, subject to the given restrictions.
121 pub(super) fn parse_expr_res(
124 already_parsed_attrs: Option<AttrVec>,
125 ) -> PResult<'a, P<Expr>> {
126 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
129 /// Parses an associative expression.
131 /// This parses an expression accounting for associativity and precedence of the operators in
134 fn parse_assoc_expr(&mut self, already_parsed_attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> {
135 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
138 /// Parses an associative expression with operators of at least `min_prec` precedence.
139 pub(super) fn parse_assoc_expr_with(
143 ) -> PResult<'a, P<Expr>> {
144 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
147 let attrs = match lhs {
148 LhsExpr::AttributesParsed(attrs) => Some(attrs),
151 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
152 return self.parse_prefix_range_expr(attrs);
154 self.parse_prefix_expr(attrs)?
157 let last_type_ascription_set = self.last_type_ascription.is_some();
159 if !self.should_continue_as_assoc_expr(&lhs) {
160 self.last_type_ascription = None;
164 self.expected_tokens.push(TokenType::Operator);
165 while let Some(op) = self.check_assoc_op() {
166 // Adjust the span for interpolated LHS to point to the `$lhs` token
167 // and not to what it refers to.
168 let lhs_span = match self.prev_token.kind {
169 TokenKind::Interpolated(..) => self.prev_token.span,
173 let cur_op_span = self.token.span;
174 let restrictions = if op.node.is_assign_like() {
175 self.restrictions & Restrictions::NO_STRUCT_LITERAL
179 let prec = op.node.precedence();
183 // Check for deprecated `...` syntax
184 if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq {
185 self.err_dotdotdot_syntax(self.token.span);
188 if self.token == token::LArrow {
189 self.err_larrow_operator(self.token.span);
193 if op.node.is_comparison() {
194 if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
199 if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual)
200 && self.token.kind == token::Eq
201 && self.prev_token.span.hi() == self.token.span.lo()
203 // Look for JS' `===` and `!==` and recover 😇
204 let sp = op.span.to(self.token.span);
205 let sugg = match op.node {
206 AssocOp::Equal => "==",
207 AssocOp::NotEqual => "!=",
210 self.struct_span_err(sp, &format!("invalid comparison operator `{}=`", sugg))
211 .span_suggestion_short(
213 &format!("`{s}=` is not a valid comparison operator, use `{s}`", s = sugg),
215 Applicability::MachineApplicable,
223 if op == AssocOp::As {
224 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
226 } else if op == AssocOp::Colon {
227 lhs = self.parse_assoc_op_ascribe(lhs, lhs_span)?;
229 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
230 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
231 // generalise it to the Fixity::None code.
232 lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?;
236 let fixity = op.fixity();
237 let prec_adjustment = match fixity {
240 // We currently have no non-associative operators that are not handled above by
241 // the special cases. The code is here only for future convenience.
244 let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
245 this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
248 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
249 // including the attributes.
251 lhs.attrs.iter().find(|a| a.style == AttrStyle::Outer).map_or(lhs_span, |a| a.span);
252 let span = lhs_span.to(rhs.span);
265 | AssocOp::ShiftRight
271 | AssocOp::GreaterEqual => {
272 let ast_op = op.to_ast_binop().unwrap();
273 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
274 self.mk_expr(span, binary, AttrVec::new())
277 self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span), AttrVec::new())
279 AssocOp::AssignOp(k) => {
281 token::Plus => BinOpKind::Add,
282 token::Minus => BinOpKind::Sub,
283 token::Star => BinOpKind::Mul,
284 token::Slash => BinOpKind::Div,
285 token::Percent => BinOpKind::Rem,
286 token::Caret => BinOpKind::BitXor,
287 token::And => BinOpKind::BitAnd,
288 token::Or => BinOpKind::BitOr,
289 token::Shl => BinOpKind::Shl,
290 token::Shr => BinOpKind::Shr,
292 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
293 self.mk_expr(span, aopexpr, AttrVec::new())
295 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
296 self.span_bug(span, "AssocOp should have been handled by special case")
300 if let Fixity::None = fixity {
304 if last_type_ascription_set {
305 self.last_type_ascription = None;
310 fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
311 match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) {
312 // Semi-statement forms are odd:
313 // See https://github.com/rust-lang/rust/issues/29071
314 (true, None) => false,
315 (false, _) => true, // Continue parsing the expression.
316 // An exhaustive check is done in the following block, but these are checked first
317 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
318 // want to keep their span info to improve diagnostics in these cases in a later stage.
319 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
320 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
321 (true, Some(AssocOp::Add)) // `{ 42 } + 42
322 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
323 // `if x { a } else { b } && if y { c } else { d }`
324 if !self.look_ahead(1, |t| t.is_used_keyword()) => {
325 // These cases are ambiguous and can't be identified in the parser alone.
326 let sp = self.sess.source_map().start_point(self.token.span);
327 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
330 (true, Some(AssocOp::LAnd)) => {
331 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`. Separated from the
332 // above due to #74233.
333 // These cases are ambiguous and can't be identified in the parser alone.
334 let sp = self.sess.source_map().start_point(self.token.span);
335 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
338 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => false,
340 self.error_found_expr_would_be_stmt(lhs);
346 /// We've found an expression that would be parsed as a statement,
347 /// but the next token implies this should be parsed as an expression.
348 /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
349 fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
350 let mut err = self.struct_span_err(
352 &format!("expected expression, found `{}`", pprust::token_to_string(&self.token),),
354 err.span_label(self.token.span, "expected expression");
355 self.sess.expr_parentheses_needed(&mut err, lhs.span, Some(pprust::expr_to_string(&lhs)));
359 /// Possibly translate the current token to an associative operator.
360 /// The method does not advance the current token.
362 /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
363 fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
364 let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
365 (Some(op), _) => (op, self.token.span),
366 (None, Some((Ident { name: sym::and, span }, false))) => {
367 self.error_bad_logical_op("and", "&&", "conjunction");
368 (AssocOp::LAnd, span)
370 (None, Some((Ident { name: sym::or, span }, false))) => {
371 self.error_bad_logical_op("or", "||", "disjunction");
376 Some(source_map::respan(span, op))
379 /// Error on `and` and `or` suggesting `&&` and `||` respectively.
380 fn error_bad_logical_op(&self, bad: &str, good: &str, english: &str) {
381 self.struct_span_err(self.token.span, &format!("`{}` is not a logical operator", bad))
382 .span_suggestion_short(
384 &format!("use `{}` to perform logical {}", good, english),
386 Applicability::MachineApplicable,
388 .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators")
392 /// Checks if this expression is a successfully parsed statement.
393 fn expr_is_complete(&self, e: &Expr) -> bool {
394 self.restrictions.contains(Restrictions::STMT_EXPR)
395 && !classify::expr_requires_semi_to_be_stmt(e)
398 /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
399 /// The other two variants are handled in `parse_prefix_range_expr` below.
406 ) -> PResult<'a, P<Expr>> {
407 let rhs = if self.is_at_start_of_range_notation_rhs() {
408 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
412 let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
413 let span = lhs.span.to(rhs_span);
415 if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed };
416 Ok(self.mk_expr(span, self.mk_range(Some(lhs), rhs, limits)?, AttrVec::new()))
419 fn is_at_start_of_range_notation_rhs(&self) -> bool {
420 if self.token.can_begin_expr() {
421 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
422 if self.token == token::OpenDelim(token::Brace) {
423 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
431 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
432 fn parse_prefix_range_expr(&mut self, attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> {
433 // Check for deprecated `...` syntax.
434 if self.token == token::DotDotDot {
435 self.err_dotdotdot_syntax(self.token.span);
439 [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
440 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
444 let limits = match self.token.kind {
445 token::DotDot => RangeLimits::HalfOpen,
446 _ => RangeLimits::Closed,
448 let op = AssocOp::from_token(&self.token);
449 let attrs = self.parse_or_use_outer_attributes(attrs)?;
450 let lo = self.token.span;
452 let (span, opt_end) = if self.is_at_start_of_range_notation_rhs() {
453 // RHS must be parsed with more associativity than the dots.
454 self.parse_assoc_expr_with(op.unwrap().precedence() + 1, LhsExpr::NotYetParsed)
455 .map(|x| (lo.to(x.span), Some(x)))?
459 Ok(self.mk_expr(span, self.mk_range(None, opt_end, limits)?, attrs))
462 /// Parses a prefix-unary-operator expr.
463 fn parse_prefix_expr(&mut self, attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> {
464 let attrs = self.parse_or_use_outer_attributes(attrs)?;
465 self.maybe_collect_tokens(!attrs.is_empty(), |this| {
466 let lo = this.token.span;
467 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
468 let (hi, ex) = match this.token.uninterpolate().kind {
469 token::Not => this.parse_unary_expr(lo, UnOp::Not), // `!expr`
470 token::Tilde => this.recover_tilde_expr(lo), // `~expr`
471 token::BinOp(token::Minus) => this.parse_unary_expr(lo, UnOp::Neg), // `-expr`
472 token::BinOp(token::Star) => this.parse_unary_expr(lo, UnOp::Deref), // `*expr`
473 token::BinOp(token::And) | token::AndAnd => this.parse_borrow_expr(lo),
474 token::Ident(..) if this.token.is_keyword(kw::Box) => this.parse_box_expr(lo),
475 token::Ident(..) if this.is_mistaken_not_ident_negation() => {
476 this.recover_not_expr(lo)
478 _ => return this.parse_dot_or_call_expr(Some(attrs)),
480 Ok(this.mk_expr(lo.to(hi), ex, attrs))
484 fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P<Expr>)> {
486 let expr = self.parse_prefix_expr(None);
487 let (span, expr) = self.interpolated_or_expr_span(expr)?;
488 Ok((lo.to(span), expr))
491 fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
492 let (span, expr) = self.parse_prefix_expr_common(lo)?;
493 Ok((span, self.mk_unary(op, expr)))
496 // Recover on `!` suggesting for bitwise negation instead.
497 fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
498 self.struct_span_err(lo, "`~` cannot be used as a unary operator")
499 .span_suggestion_short(
501 "use `!` to perform bitwise not",
503 Applicability::MachineApplicable,
507 self.parse_unary_expr(lo, UnOp::Not)
510 /// Parse `box expr`.
511 fn parse_box_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
512 let (span, expr) = self.parse_prefix_expr_common(lo)?;
513 self.sess.gated_spans.gate(sym::box_syntax, span);
514 Ok((span, ExprKind::Box(expr)))
517 fn is_mistaken_not_ident_negation(&self) -> bool {
518 let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
519 // These tokens can start an expression after `!`, but
520 // can't continue an expression after an ident
521 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
522 token::Literal(..) | token::Pound => true,
523 _ => t.is_whole_expr(),
525 self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
528 /// Recover on `not expr` in favor of `!expr`.
529 fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
531 let not_token = self.look_ahead(1, |t| t.clone());
532 self.struct_span_err(
534 &format!("unexpected {} after identifier", super::token_descr(¬_token)),
536 .span_suggestion_short(
537 // Span the `not` plus trailing whitespace to avoid
538 // trailing whitespace after the `!` in our suggestion
539 self.sess.source_map().span_until_non_whitespace(lo.to(not_token.span)),
540 "use `!` to perform logical negation",
542 Applicability::MachineApplicable,
547 self.parse_unary_expr(lo, UnOp::Not)
550 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
551 fn interpolated_or_expr_span(
553 expr: PResult<'a, P<Expr>>,
554 ) -> PResult<'a, (Span, P<Expr>)> {
557 match self.prev_token.kind {
558 TokenKind::Interpolated(..) => self.prev_token.span,
566 fn parse_assoc_op_cast(
570 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind,
571 ) -> PResult<'a, P<Expr>> {
572 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
573 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), AttrVec::new())
576 // Save the state of the parser before parsing type normally, in case there is a
577 // LessThan comparison after this cast.
578 let parser_snapshot_before_type = self.clone();
579 let cast_expr = match self.parse_ty_no_plus() {
580 Ok(rhs) => mk_expr(self, rhs),
581 Err(mut type_err) => {
582 // Rewind to before attempting to parse the type with generics, to recover
583 // from situations like `x as usize < y` in which we first tried to parse
584 // `usize < y` as a type with generic arguments.
585 let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
587 match self.parse_path(PathStyle::Expr) {
589 let (op_noun, op_verb) = match self.token.kind {
590 token::Lt => ("comparison", "comparing"),
591 token::BinOp(token::Shl) => ("shift", "shifting"),
593 // We can end up here even without `<` being the next token, for
594 // example because `parse_ty_no_plus` returns `Err` on keywords,
595 // but `parse_path` returns `Ok` on them due to error recovery.
596 // Return original error and parser state.
597 *self = parser_snapshot_after_type;
598 return Err(type_err);
602 // Successfully parsed the type path leaving a `<` yet to parse.
605 // Report non-fatal diagnostics, keep `x as usize` as an expression
606 // in AST and continue parsing.
608 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
609 pprust::path_to_string(&path),
612 let span_after_type = parser_snapshot_after_type.token.span;
613 let expr = mk_expr(self, self.mk_ty(path.span, TyKind::Path(None, path)));
616 .span_to_snippet(expr.span)
617 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
619 self.struct_span_err(self.token.span, &msg)
621 self.look_ahead(1, |t| t.span).to(span_after_type),
622 "interpreted as generic arguments",
624 .span_label(self.token.span, format!("not interpreted as {}", op_noun))
627 &format!("try {} the cast value", op_verb),
628 format!("({})", expr_str),
629 Applicability::MachineApplicable,
635 Err(mut path_err) => {
636 // Couldn't parse as a path, return original error and parser state.
638 *self = parser_snapshot_after_type;
639 return Err(type_err);
645 self.parse_and_disallow_postfix_after_cast(cast_expr)
648 /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
649 /// then emits an error and returns the newly parsed tree.
650 /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
651 fn parse_and_disallow_postfix_after_cast(
654 ) -> PResult<'a, P<Expr>> {
655 // Save the memory location of expr before parsing any following postfix operators.
656 // This will be compared with the memory location of the output expression.
657 // If they different we can assume we parsed another expression because the existing expression is not reallocated.
658 let addr_before = &*cast_expr as *const _ as usize;
659 let span = cast_expr.span;
660 let with_postfix = self.parse_dot_or_call_expr_with_(cast_expr, span)?;
661 let changed = addr_before != &*with_postfix as *const _ as usize;
663 // Check if an illegal postfix operator has been added after the cast.
664 // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator.
665 if !matches!(with_postfix.kind, ExprKind::Cast(_, _) | ExprKind::Type(_, _)) || changed {
667 "casts cannot be followed by {}",
668 match with_postfix.kind {
669 ExprKind::Index(_, _) => "indexing",
670 ExprKind::Try(_) => "?",
671 ExprKind::Field(_, _) => "a field access",
672 ExprKind::MethodCall(_, _, _) => "a method call",
673 ExprKind::Call(_, _) => "a function call",
674 ExprKind::Await(_) => "`.await`",
675 ExprKind::Err => return Ok(with_postfix),
676 _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"),
679 let mut err = self.struct_span_err(span, &msg);
680 // If type ascription is "likely an error", the user will already be getting a useful
681 // help message, and doesn't need a second.
682 if self.last_type_ascription.map_or(false, |last_ascription| last_ascription.1) {
683 self.maybe_annotate_with_ascription(&mut err, false);
685 let suggestions = vec![
686 (span.shrink_to_lo(), "(".to_string()),
687 (span.shrink_to_hi(), ")".to_string()),
689 err.multipart_suggestion(
690 "try surrounding the expression in parentheses",
692 Applicability::MachineApplicable,
700 fn parse_assoc_op_ascribe(&mut self, lhs: P<Expr>, lhs_span: Span) -> PResult<'a, P<Expr>> {
701 let maybe_path = self.could_ascription_be_path(&lhs.kind);
702 self.last_type_ascription = Some((self.prev_token.span, maybe_path));
703 let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
704 self.sess.gated_spans.gate(sym::type_ascription, lhs.span);
708 /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
709 fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
711 let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
712 let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
713 let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo);
714 let expr = self.parse_prefix_expr(None);
715 let (hi, expr) = self.interpolated_or_expr_span(expr)?;
716 let span = lo.to(hi);
717 if let Some(lt) = lifetime {
718 self.error_remove_borrow_lifetime(span, lt.ident.span);
720 Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
723 fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
724 self.struct_span_err(span, "borrow expressions cannot be annotated with lifetimes")
725 .span_label(lt_span, "annotated with lifetime here")
728 "remove the lifetime annotation",
730 Applicability::MachineApplicable,
735 /// Parse `mut?` or `raw [ const | mut ]`.
736 fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) {
737 if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) {
738 // `raw [ const | mut ]`.
739 let found_raw = self.eat_keyword(kw::Raw);
741 let mutability = self.parse_const_or_mut().unwrap();
742 self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span));
743 (ast::BorrowKind::Raw, mutability)
746 (ast::BorrowKind::Ref, self.parse_mutability())
750 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
751 fn parse_dot_or_call_expr(&mut self, attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> {
752 let attrs = self.parse_or_use_outer_attributes(attrs)?;
753 let base = self.parse_bottom_expr();
754 let (span, base) = self.interpolated_or_expr_span(base)?;
755 self.parse_dot_or_call_expr_with(base, span, attrs)
758 pub(super) fn parse_dot_or_call_expr_with(
763 ) -> PResult<'a, P<Expr>> {
764 // Stitch the list of outer attributes onto the return value.
765 // A little bit ugly, but the best way given the current code
767 self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| {
768 expr.map(|mut expr| {
769 attrs.extend::<Vec<_>>(expr.attrs.into());
776 fn parse_dot_or_call_expr_with_(&mut self, mut e: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
778 if self.eat(&token::Question) {
780 e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e), AttrVec::new());
783 if self.eat(&token::Dot) {
785 e = self.parse_dot_suffix_expr(lo, e)?;
788 if self.expr_is_complete(&e) {
791 e = match self.token.kind {
792 token::OpenDelim(token::Paren) => self.parse_fn_call_expr(lo, e),
793 token::OpenDelim(token::Bracket) => self.parse_index_expr(lo, e)?,
799 fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
800 match self.token.uninterpolate().kind {
801 token::Ident(..) => self.parse_dot_suffix(base, lo),
802 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
803 Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix, None))
805 token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => {
806 Ok(self.parse_tuple_field_access_expr_float(lo, base, symbol, suffix))
809 self.error_unexpected_after_dot();
815 fn error_unexpected_after_dot(&self) {
816 // FIXME Could factor this out into non_fatal_unexpected or something.
817 let actual = pprust::token_to_string(&self.token);
818 self.struct_span_err(self.token.span, &format!("unexpected token: `{}`", actual)).emit();
821 // We need and identifier or integer, but the next token is a float.
822 // Break the float into components to extract the identifier or integer.
823 // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
824 // parts unless those parts are processed immediately. `TokenCursor` should either
825 // support pushing "future tokens" (would be also helpful to `break_and_eat`), or
826 // we should break everything including floats into more basic proc-macro style
827 // tokens in the lexer (probably preferable).
828 fn parse_tuple_field_access_expr_float(
833 suffix: Option<Symbol>,
836 enum FloatComponent {
840 use FloatComponent::*;
842 let mut components = Vec::new();
843 let mut ident_like = String::new();
844 for c in float.as_str().chars() {
845 if c == '_' || c.is_ascii_alphanumeric() {
847 } else if matches!(c, '.' | '+' | '-') {
848 if !ident_like.is_empty() {
849 components.push(IdentLike(mem::take(&mut ident_like)));
851 components.push(Punct(c));
853 panic!("unexpected character in a float token: {:?}", c)
856 if !ident_like.is_empty() {
857 components.push(IdentLike(ident_like));
860 // FIXME: Make the span more precise.
861 let span = self.token.span;
865 self.parse_tuple_field_access_expr(lo, base, Symbol::intern(&i), suffix, None)
868 [IdentLike(i), Punct('.')] => {
869 assert!(suffix.is_none());
870 let symbol = Symbol::intern(&i);
871 self.token = Token::new(token::Ident(symbol, false), span);
872 let next_token = Token::new(token::Dot, span);
873 self.parse_tuple_field_access_expr(lo, base, symbol, None, Some(next_token))
876 [IdentLike(i1), Punct('.'), IdentLike(i2)] => {
877 let symbol1 = Symbol::intern(&i1);
878 self.token = Token::new(token::Ident(symbol1, false), span);
879 let next_token1 = Token::new(token::Dot, span);
881 self.parse_tuple_field_access_expr(lo, base, symbol1, None, Some(next_token1));
882 let symbol2 = Symbol::intern(&i2);
883 let next_token2 = Token::new(token::Ident(symbol2, false), span);
884 self.bump_with(next_token2); // `.`
885 self.parse_tuple_field_access_expr(lo, base1, symbol2, suffix, None)
887 // 1e+ | 1e- (recovered)
888 [IdentLike(_), Punct('+' | '-')] |
890 [IdentLike(_), Punct('+' | '-'), IdentLike(_)] |
892 [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-'), IdentLike(_)] => {
893 // See the FIXME about `TokenCursor` above.
894 self.error_unexpected_after_dot();
897 _ => panic!("unexpected components in a float token: {:?}", components),
901 fn parse_tuple_field_access_expr(
906 suffix: Option<Symbol>,
907 next_token: Option<Token>,
910 Some(next_token) => self.bump_with(next_token),
913 let span = self.prev_token.span;
914 let field = ExprKind::Field(base, Ident::new(field, span));
915 self.expect_no_suffix(span, "a tuple index", suffix);
916 self.mk_expr(lo.to(span), field, AttrVec::new())
919 /// Parse a function call expression, `expr(...)`.
920 fn parse_fn_call_expr(&mut self, lo: Span, fun: P<Expr>) -> P<Expr> {
921 let seq = self.parse_paren_expr_seq().map(|args| {
922 self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args), AttrVec::new())
924 self.recover_seq_parse_error(token::Paren, lo, seq)
927 /// Parse an indexing expression `expr[...]`.
928 fn parse_index_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
930 let index = self.parse_expr()?;
931 self.expect(&token::CloseDelim(token::Bracket))?;
932 Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_index(base, index), AttrVec::new()))
935 /// Assuming we have just parsed `.`, continue parsing into an expression.
936 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
937 if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) {
938 return self.mk_await_expr(self_arg, lo);
941 let fn_span_lo = self.token.span;
942 let mut segment = self.parse_path_segment(PathStyle::Expr)?;
943 self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(token::Paren)]);
944 self.check_turbofish_missing_angle_brackets(&mut segment);
946 if self.check(&token::OpenDelim(token::Paren)) {
947 // Method call `expr.f()`
948 let mut args = self.parse_paren_expr_seq()?;
949 args.insert(0, self_arg);
951 let fn_span = fn_span_lo.to(self.prev_token.span);
952 let span = lo.to(self.prev_token.span);
953 Ok(self.mk_expr(span, ExprKind::MethodCall(segment, args, fn_span), AttrVec::new()))
955 // Field access `expr.f`
956 if let Some(args) = segment.args {
957 self.struct_span_err(
959 "field expressions cannot have generic arguments",
964 let span = lo.to(self.prev_token.span);
965 Ok(self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), AttrVec::new()))
969 /// At the bottom (top?) of the precedence hierarchy,
970 /// Parses things like parenthesized exprs, macros, `return`, etc.
972 /// N.B., this does not parse outer attributes, and is private because it only works
973 /// correctly if called from `parse_dot_or_call_expr()`.
974 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
975 maybe_recover_from_interpolated_ty_qpath!(self, true);
976 maybe_whole_expr!(self);
978 // Outer attributes are already parsed and will be
979 // added to the return value after the fact.
981 // Therefore, prevent sub-parser from parsing
982 // attributes by giving them a empty "already-parsed" list.
983 let attrs = AttrVec::new();
985 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
986 let lo = self.token.span;
987 if let token::Literal(_) = self.token.kind {
988 // This match arm is a special-case of the `_` match arm below and
989 // could be removed without changing functionality, but it's faster
990 // to have it here, especially for programs with large constants.
991 self.parse_lit_expr(attrs)
992 } else if self.check(&token::OpenDelim(token::Paren)) {
993 self.parse_tuple_parens_expr(attrs)
994 } else if self.check(&token::OpenDelim(token::Brace)) {
995 self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs)
996 } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) {
997 self.parse_closure_expr(attrs)
998 } else if self.check(&token::OpenDelim(token::Bracket)) {
999 self.parse_array_or_repeat_expr(attrs)
1000 } else if self.eat_lt() {
1001 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
1002 Ok(self.mk_expr(lo.to(path.span), ExprKind::Path(Some(qself), path), attrs))
1003 } else if self.check_path() {
1004 self.parse_path_start_expr(attrs)
1005 } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
1006 self.parse_closure_expr(attrs)
1007 } else if self.eat_keyword(kw::If) {
1008 self.parse_if_expr(attrs)
1009 } else if self.check_keyword(kw::For) {
1010 if self.choose_generics_over_qpath(1) {
1011 // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery,
1012 // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns.
1013 // When `for <Foo as Bar>::Proj in $expr $block` is wanted,
1014 // you can disambiguate in favor of a pattern with `(...)`.
1015 self.recover_quantified_closure_expr(attrs)
1017 assert!(self.eat_keyword(kw::For));
1018 self.parse_for_expr(None, self.prev_token.span, attrs)
1020 } else if self.eat_keyword(kw::While) {
1021 self.parse_while_expr(None, self.prev_token.span, attrs)
1022 } else if let Some(label) = self.eat_label() {
1023 self.parse_labeled_expr(label, attrs)
1024 } else if self.eat_keyword(kw::Loop) {
1025 self.parse_loop_expr(None, self.prev_token.span, attrs)
1026 } else if self.eat_keyword(kw::Continue) {
1027 let kind = ExprKind::Continue(self.eat_label());
1028 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1029 } else if self.eat_keyword(kw::Match) {
1030 let match_sp = self.prev_token.span;
1031 self.parse_match_expr(attrs).map_err(|mut err| {
1032 err.span_label(match_sp, "while parsing this match expression");
1035 } else if self.eat_keyword(kw::Unsafe) {
1036 self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs)
1037 } else if self.is_do_catch_block() {
1038 self.recover_do_catch(attrs)
1039 } else if self.is_try_block() {
1040 self.expect_keyword(kw::Try)?;
1041 self.parse_try_block(lo, attrs)
1042 } else if self.eat_keyword(kw::Return) {
1043 self.parse_return_expr(attrs)
1044 } else if self.eat_keyword(kw::Break) {
1045 self.parse_break_expr(attrs)
1046 } else if self.eat_keyword(kw::Yield) {
1047 self.parse_yield_expr(attrs)
1048 } else if self.eat_keyword(kw::Let) {
1049 self.parse_let_expr(attrs)
1050 } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1051 // Don't complain about bare semicolons after unclosed braces
1052 // recovery in order to keep the error count down. Fixing the
1053 // delimiters will possibly also fix the bare semicolon found in
1054 // expression context. For example, silence the following error:
1056 // error: expected expression, found `;`
1060 // | ^ expected expression
1062 Ok(self.mk_expr_err(self.token.span))
1063 } else if self.token.uninterpolated_span().rust_2018() {
1064 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1065 if self.check_keyword(kw::Async) {
1066 if self.is_async_block() {
1067 // Check for `async {` and `async move {`.
1068 self.parse_async_block(attrs)
1070 self.parse_closure_expr(attrs)
1072 } else if self.eat_keyword(kw::Await) {
1073 self.recover_incorrect_await_syntax(lo, self.prev_token.span, attrs)
1075 self.parse_lit_expr(attrs)
1078 self.parse_lit_expr(attrs)
1082 fn maybe_collect_tokens(
1084 has_outer_attrs: bool,
1085 f: impl FnOnce(&mut Self) -> PResult<'a, P<Expr>>,
1086 ) -> PResult<'a, P<Expr>> {
1087 if has_outer_attrs {
1088 let (mut expr, tokens) = self.collect_tokens(f)?;
1089 debug!("maybe_collect_tokens: Collected tokens for {:?} (tokens {:?}", expr, tokens);
1090 expr.tokens = Some(tokens);
1097 fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1098 let lo = self.token.span;
1099 match self.parse_opt_lit() {
1101 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs);
1102 self.maybe_recover_from_bad_qpath(expr, true)
1104 None => self.try_macro_suggestion(),
1108 fn parse_tuple_parens_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1109 let lo = self.token.span;
1110 self.expect(&token::OpenDelim(token::Paren))?;
1111 attrs.extend(self.parse_inner_attributes()?); // `(#![foo] a, b, ...)` is OK.
1112 let (es, trailing_comma) = match self.parse_seq_to_end(
1113 &token::CloseDelim(token::Paren),
1114 SeqSep::trailing_allowed(token::Comma),
1115 |p| p.parse_expr_catch_underscore(),
1118 Err(err) => return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err))),
1120 let kind = if es.len() == 1 && !trailing_comma {
1121 // `(e)` is parenthesized `e`.
1122 ExprKind::Paren(es.into_iter().next().unwrap())
1124 // `(e,)` is a tuple with only one field, `e`.
1127 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1128 self.maybe_recover_from_bad_qpath(expr, true)
1131 fn parse_array_or_repeat_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1132 let lo = self.token.span;
1135 attrs.extend(self.parse_inner_attributes()?);
1137 let close = &token::CloseDelim(token::Bracket);
1138 let kind = if self.eat(close) {
1140 ExprKind::Array(Vec::new())
1143 let first_expr = self.parse_expr()?;
1144 if self.eat(&token::Semi) {
1145 // Repeating array syntax: `[ 0; 512 ]`
1146 let count = self.parse_anon_const_expr()?;
1147 self.expect(close)?;
1148 ExprKind::Repeat(first_expr, count)
1149 } else if self.eat(&token::Comma) {
1150 // Vector with two or more elements.
1151 let sep = SeqSep::trailing_allowed(token::Comma);
1152 let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1153 let mut exprs = vec![first_expr];
1154 exprs.extend(remaining_exprs);
1155 ExprKind::Array(exprs)
1157 // Vector with one element
1158 self.expect(close)?;
1159 ExprKind::Array(vec![first_expr])
1162 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1163 self.maybe_recover_from_bad_qpath(expr, true)
1166 fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1167 let path = self.parse_path(PathStyle::Expr)?;
1170 // `!`, as an operator, is prefix, so we know this isn't that.
1171 let (hi, kind) = if self.eat(&token::Not) {
1172 // MACRO INVOCATION expression
1175 args: self.parse_mac_args()?,
1176 prior_type_ascription: self.last_type_ascription,
1178 (self.prev_token.span, ExprKind::MacCall(mac))
1179 } else if self.check(&token::OpenDelim(token::Brace)) {
1180 if let Some(expr) = self.maybe_parse_struct_expr(&path, &attrs) {
1183 (path.span, ExprKind::Path(None, path))
1186 (path.span, ExprKind::Path(None, path))
1189 let expr = self.mk_expr(lo.to(hi), kind, attrs);
1190 self.maybe_recover_from_bad_qpath(expr, true)
1193 /// Parse `'label: $expr`. The label is already parsed.
1194 fn parse_labeled_expr(&mut self, label: Label, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1195 let lo = label.ident.span;
1196 let label = Some(label);
1197 let ate_colon = self.eat(&token::Colon);
1198 let expr = if self.eat_keyword(kw::While) {
1199 self.parse_while_expr(label, lo, attrs)
1200 } else if self.eat_keyword(kw::For) {
1201 self.parse_for_expr(label, lo, attrs)
1202 } else if self.eat_keyword(kw::Loop) {
1203 self.parse_loop_expr(label, lo, attrs)
1204 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1205 self.parse_block_expr(label, lo, BlockCheckMode::Default, attrs)
1207 let msg = "expected `while`, `for`, `loop` or `{` after a label";
1208 self.struct_span_err(self.token.span, msg).span_label(self.token.span, msg).emit();
1209 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1214 self.error_labeled_expr_must_be_followed_by_colon(lo, expr.span);
1220 fn error_labeled_expr_must_be_followed_by_colon(&self, lo: Span, span: Span) {
1221 self.struct_span_err(span, "labeled expression must be followed by `:`")
1222 .span_label(lo, "the label")
1223 .span_suggestion_short(
1225 "add `:` after the label",
1227 Applicability::MachineApplicable,
1229 .note("labels are used before loops and blocks, allowing e.g., `break 'label` to them")
1233 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1234 fn recover_do_catch(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1235 let lo = self.token.span;
1237 self.bump(); // `do`
1238 self.bump(); // `catch`
1240 let span_dc = lo.to(self.prev_token.span);
1241 self.struct_span_err(span_dc, "found removed `do catch` syntax")
1244 "replace with the new syntax",
1246 Applicability::MachineApplicable,
1248 .note("following RFC #2388, the new non-placeholder syntax is `try`")
1251 self.parse_try_block(lo, attrs)
1254 /// Parse an expression if the token can begin one.
1255 fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1256 Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1259 /// Parse `"return" expr?`.
1260 fn parse_return_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1261 let lo = self.prev_token.span;
1262 let kind = ExprKind::Ret(self.parse_expr_opt()?);
1263 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1264 self.maybe_recover_from_bad_qpath(expr, true)
1267 /// Parse `"('label ":")? break expr?`.
1268 fn parse_break_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1269 let lo = self.prev_token.span;
1270 let label = self.eat_label();
1271 let kind = if self.token != token::OpenDelim(token::Brace)
1272 || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1274 self.parse_expr_opt()?
1278 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind), attrs);
1279 self.maybe_recover_from_bad_qpath(expr, true)
1282 /// Parse `"yield" expr?`.
1283 fn parse_yield_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1284 let lo = self.prev_token.span;
1285 let kind = ExprKind::Yield(self.parse_expr_opt()?);
1286 let span = lo.to(self.prev_token.span);
1287 self.sess.gated_spans.gate(sym::generators, span);
1288 let expr = self.mk_expr(span, kind, attrs);
1289 self.maybe_recover_from_bad_qpath(expr, true)
1292 /// Returns a string literal if the next token is a string literal.
1293 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1294 /// and returns `None` if the next token is not literal at all.
1295 pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
1296 match self.parse_opt_lit() {
1297 Some(lit) => match lit.kind {
1298 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1300 symbol: lit.token.symbol,
1301 suffix: lit.token.suffix,
1305 _ => Err(Some(lit)),
1311 pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> {
1312 self.parse_opt_lit().ok_or_else(|| {
1313 let msg = format!("unexpected token: {}", super::token_descr(&self.token));
1314 self.struct_span_err(self.token.span, &msg)
1318 /// Matches `lit = true | false | token_lit`.
1319 /// Returns `None` if the next token is not a literal.
1320 pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
1321 let mut recovered = None;
1322 if self.token == token::Dot {
1323 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1324 // dot would follow an optional literal, so we do this unconditionally.
1325 recovered = self.look_ahead(1, |next_token| {
1326 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1329 if self.token.span.hi() == next_token.span.lo() {
1330 let s = String::from("0.") + &symbol.as_str();
1331 let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1332 return Some(Token::new(kind, self.token.span.to(next_token.span)));
1337 if let Some(token) = &recovered {
1339 self.error_float_lits_must_have_int_part(&token);
1343 let token = recovered.as_ref().unwrap_or(&self.token);
1344 match Lit::from_token(token) {
1349 Err(LitError::NotLiteral) => None,
1351 let span = token.span;
1352 let lit = match token.kind {
1353 token::Literal(lit) => lit,
1354 _ => unreachable!(),
1357 self.report_lit_error(err, lit, span);
1358 // Pack possible quotes and prefixes from the original literal into
1359 // the error literal's symbol so they can be pretty-printed faithfully.
1360 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1361 let symbol = Symbol::intern(&suffixless_lit.to_string());
1362 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1363 Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!()))
1368 fn error_float_lits_must_have_int_part(&self, token: &Token) {
1369 self.struct_span_err(token.span, "float literals must have an integer part")
1372 "must have an integer part",
1373 pprust::token_to_string(token),
1374 Applicability::MachineApplicable,
1379 fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) {
1380 // Checks if `s` looks like i32 or u1234 etc.
1381 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1382 s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
1385 let token::Lit { kind, suffix, .. } = lit;
1387 // `NotLiteral` is not an error by itself, so we don't report
1388 // it and give the parser opportunity to try something else.
1389 LitError::NotLiteral => {}
1390 // `LexerError` *is* an error, but it was already reported
1391 // by lexer, so here we don't report it the second time.
1392 LitError::LexerError => {}
1393 LitError::InvalidSuffix => {
1394 self.expect_no_suffix(
1396 &format!("{} {} literal", kind.article(), kind.descr()),
1400 LitError::InvalidIntSuffix => {
1401 let suf = suffix.expect("suffix error with no suffix").as_str();
1402 if looks_like_width_suffix(&['i', 'u'], &suf) {
1403 // If it looks like a width, try to be helpful.
1404 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
1405 self.struct_span_err(span, &msg)
1406 .help("valid widths are 8, 16, 32, 64 and 128")
1409 let msg = format!("invalid suffix `{}` for integer literal", suf);
1410 self.struct_span_err(span, &msg)
1411 .span_label(span, format!("invalid suffix `{}`", suf))
1412 .help("the suffix must be one of the integral types (`u32`, `isize`, etc)")
1416 LitError::InvalidFloatSuffix => {
1417 let suf = suffix.expect("suffix error with no suffix").as_str();
1418 if looks_like_width_suffix(&['f'], &suf) {
1419 // If it looks like a width, try to be helpful.
1420 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
1421 self.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit();
1423 let msg = format!("invalid suffix `{}` for float literal", suf);
1424 self.struct_span_err(span, &msg)
1425 .span_label(span, format!("invalid suffix `{}`", suf))
1426 .help("valid suffixes are `f32` and `f64`")
1430 LitError::NonDecimalFloat(base) => {
1431 let descr = match base {
1432 16 => "hexadecimal",
1435 _ => unreachable!(),
1437 self.struct_span_err(span, &format!("{} float literal is not supported", descr))
1438 .span_label(span, "not supported")
1441 LitError::IntTooLarge => {
1442 self.struct_span_err(span, "integer literal is too large").emit();
1447 pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) {
1448 if let Some(suf) = suffix {
1449 let mut err = if kind == "a tuple index"
1450 && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf)
1452 // #59553: warn instead of reject out of hand to allow the fix to percolate
1453 // through the ecosystem when people fix their macros
1457 .struct_span_warn(sp, &format!("suffixes on {} are invalid", kind));
1459 "`{}` is *temporarily* accepted on tuple index fields as it was \
1460 incorrectly accepted on stable for a few releases",
1464 "on proc macros, you'll want to use `syn::Index::from` or \
1465 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1466 to tuple field access",
1469 "see issue #60210 <https://github.com/rust-lang/rust/issues/60210> \
1470 for more information",
1474 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1476 err.span_label(sp, format!("invalid suffix `{}`", suf));
1481 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1482 /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
1483 pub(super) fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1484 maybe_whole_expr!(self);
1486 let lo = self.token.span;
1487 let minus_present = self.eat(&token::BinOp(token::Minus));
1488 let lit = self.parse_lit()?;
1489 let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new());
1493 lo.to(self.prev_token.span),
1494 self.mk_unary(UnOp::Neg, expr),
1502 /// Parses a block or unsafe block.
1503 pub(super) fn parse_block_expr(
1505 opt_label: Option<Label>,
1507 blk_mode: BlockCheckMode,
1509 ) -> PResult<'a, P<Expr>> {
1510 if let Some(label) = opt_label {
1511 self.sess.gated_spans.gate(sym::label_break_value, label.ident.span);
1514 if self.token.is_whole_block() {
1515 self.struct_span_err(self.token.span, "cannot use a `block` macro fragment here")
1516 .span_label(lo.to(self.token.span), "the `block` fragment is within this context")
1520 let (inner_attrs, blk) = self.parse_block_common(lo, blk_mode)?;
1521 attrs.extend(inner_attrs);
1522 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs))
1525 /// Recover on an explicitly quantified closure expression, e.g., `for<'a> |x: &'a u8| *x + 1`.
1526 fn recover_quantified_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1527 let lo = self.token.span;
1528 let _ = self.parse_late_bound_lifetime_defs()?;
1529 let span_for = lo.to(self.prev_token.span);
1530 let closure = self.parse_closure_expr(attrs)?;
1532 self.struct_span_err(span_for, "cannot introduce explicit parameters for a closure")
1533 .span_label(closure.span, "the parameters are attached to this closure")
1536 "remove the parameters",
1538 Applicability::MachineApplicable,
1542 Ok(self.mk_expr_err(lo.to(closure.span)))
1545 /// Parses a closure expression (e.g., `move |args| expr`).
1546 fn parse_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1547 let lo = self.token.span;
1550 if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
1552 let asyncness = if self.token.uninterpolated_span().rust_2018() {
1553 self.parse_asyncness()
1557 if let Async::Yes { span, .. } = asyncness {
1558 // Feature-gate `async ||` closures.
1559 self.sess.gated_spans.gate(sym::async_closure, span);
1562 let capture_clause = self.parse_capture_clause();
1563 let decl = self.parse_fn_block_decl()?;
1564 let decl_hi = self.prev_token.span;
1565 let body = match decl.output {
1566 FnRetTy::Default(_) => {
1567 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
1568 self.parse_expr_res(restrictions, None)?
1571 // If an explicit return type is given, require a block to appear (RFC 968).
1572 let body_lo = self.token.span;
1573 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, AttrVec::new())?
1579 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
1584 /// Parses an optional `move` prefix to a closure-like construct.
1585 fn parse_capture_clause(&mut self) -> CaptureBy {
1586 if self.eat_keyword(kw::Move) { CaptureBy::Value } else { CaptureBy::Ref }
1589 /// Parses the `|arg, arg|` header of a closure.
1590 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
1591 let inputs = if self.eat(&token::OrOr) {
1594 self.expect(&token::BinOp(token::Or))?;
1596 .parse_seq_to_before_tokens(
1597 &[&token::BinOp(token::Or), &token::OrOr],
1598 SeqSep::trailing_allowed(token::Comma),
1599 TokenExpectType::NoExpect,
1600 |p| p.parse_fn_block_param(),
1606 let output = self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes)?;
1608 Ok(P(FnDecl { inputs, output }))
1611 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1612 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
1613 let lo = self.token.span;
1614 let attrs = self.parse_outer_attributes()?;
1615 let pat = self.parse_pat(PARAM_EXPECTED)?;
1616 let ty = if self.eat(&token::Colon) {
1619 self.mk_ty(self.prev_token.span, TyKind::Infer)
1622 attrs: attrs.into(),
1625 span: lo.to(self.token.span),
1627 is_placeholder: false,
1631 /// Parses an `if` expression (`if` token already eaten).
1632 fn parse_if_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1633 let lo = self.prev_token.span;
1634 let cond = self.parse_cond_expr()?;
1636 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1637 // verify that the last statement is either an implicit return (no `;`) or an explicit
1638 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1639 // the dead code lint.
1640 let thn = if self.eat_keyword(kw::Else) || !cond.returns() {
1641 self.error_missing_if_cond(lo, cond.span)
1643 let attrs = self.parse_outer_attributes()?; // For recovery.
1644 let not_block = self.token != token::OpenDelim(token::Brace);
1645 let block = self.parse_block().map_err(|mut err| {
1647 err.span_label(lo, "this `if` expression has a condition, but no block");
1648 if let ExprKind::Binary(_, _, ref right) = cond.kind {
1649 if let ExprKind::Block(_, _) = right.kind {
1650 err.help("maybe you forgot the right operand of the condition?");
1656 self.error_on_if_block_attrs(lo, false, block.span, &attrs);
1659 let els = if self.eat_keyword(kw::Else) { Some(self.parse_else_expr()?) } else { None };
1660 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els), attrs))
1663 fn error_missing_if_cond(&self, lo: Span, span: Span) -> P<ast::Block> {
1664 let sp = self.sess.source_map().next_point(lo);
1665 self.struct_span_err(sp, "missing condition for `if` expression")
1666 .span_label(sp, "expected if condition here")
1668 self.mk_block_err(span)
1671 /// Parses the condition of a `if` or `while` expression.
1672 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
1673 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1675 if let ExprKind::Let(..) = cond.kind {
1676 // Remove the last feature gating of a `let` expression since it's stable.
1677 self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
1683 /// Parses a `let $pat = $expr` pseudo-expression.
1684 /// The `let` token has already been eaten.
1685 fn parse_let_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1686 let lo = self.prev_token.span;
1687 let pat = self.parse_top_pat(GateOr::No)?;
1688 self.expect(&token::Eq)?;
1689 let expr = self.with_res(Restrictions::NO_STRUCT_LITERAL, |this| {
1690 this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
1692 let span = lo.to(expr.span);
1693 self.sess.gated_spans.gate(sym::let_chains, span);
1694 Ok(self.mk_expr(span, ExprKind::Let(pat, expr), attrs))
1697 /// Parses an `else { ... }` expression (`else` token already eaten).
1698 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
1699 let ctx_span = self.prev_token.span; // `else`
1700 let attrs = self.parse_outer_attributes()?; // For recovery.
1701 let expr = if self.eat_keyword(kw::If) {
1702 self.parse_if_expr(AttrVec::new())?
1704 let blk = self.parse_block()?;
1705 self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new())
1707 self.error_on_if_block_attrs(ctx_span, true, expr.span, &attrs);
1711 fn error_on_if_block_attrs(
1716 attrs: &[ast::Attribute],
1718 let (span, last) = match attrs {
1720 [x0 @ xn] | [x0, .., xn] => (x0.span.to(xn.span), xn.span),
1722 let ctx = if is_ctx_else { "else" } else { "if" };
1723 self.struct_span_err(last, "outer attributes are not allowed on `if` and `else` branches")
1724 .span_label(branch_span, "the attributes are attached to this branch")
1725 .span_label(ctx_span, format!("the branch belongs to this `{}`", ctx))
1728 "remove the attributes",
1730 Applicability::MachineApplicable,
1735 /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
1738 opt_label: Option<Label>,
1741 ) -> PResult<'a, P<Expr>> {
1742 // Record whether we are about to parse `for (`.
1743 // This is used below for recovery in case of `for ( $stuff ) $block`
1744 // in which case we will suggest `for $stuff $block`.
1745 let begin_paren = match self.token.kind {
1746 token::OpenDelim(token::Paren) => Some(self.token.span),
1750 let pat = self.parse_top_pat(GateOr::Yes)?;
1751 if !self.eat_keyword(kw::In) {
1752 self.error_missing_in_for_loop();
1754 self.check_for_for_in_in_typo(self.prev_token.span);
1755 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1757 let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
1759 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
1760 attrs.extend(iattrs);
1762 let kind = ExprKind::ForLoop(pat, expr, loop_block, opt_label);
1763 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1766 fn error_missing_in_for_loop(&mut self) {
1767 let (span, msg, sugg) = if self.token.is_ident_named(sym::of) {
1768 // Possibly using JS syntax (#75311).
1769 let span = self.token.span;
1771 (span, "try using `in` here instead", "in")
1773 (self.prev_token.span.between(self.token.span), "try adding `in` here", " in ")
1775 self.struct_span_err(span, "missing `in` in `for` loop")
1776 .span_suggestion_short(
1780 // Has been misleading, at least in the past (closed Issue #48492).
1781 Applicability::MaybeIncorrect,
1786 /// Parses a `while` or `while let` expression (`while` token already eaten).
1787 fn parse_while_expr(
1789 opt_label: Option<Label>,
1792 ) -> PResult<'a, P<Expr>> {
1793 let cond = self.parse_cond_expr()?;
1794 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1795 attrs.extend(iattrs);
1796 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::While(cond, body, opt_label), attrs))
1799 /// Parses `loop { ... }` (`loop` token already eaten).
1802 opt_label: Option<Label>,
1805 ) -> PResult<'a, P<Expr>> {
1806 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1807 attrs.extend(iattrs);
1808 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::Loop(body, opt_label), attrs))
1811 fn eat_label(&mut self) -> Option<Label> {
1812 self.token.lifetime().map(|ident| {
1818 /// Parses a `match ... { ... }` expression (`match` token already eaten).
1819 fn parse_match_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1820 let match_span = self.prev_token.span;
1821 let lo = self.prev_token.span;
1822 let scrutinee = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1823 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
1824 if self.token == token::Semi {
1825 e.span_suggestion_short(
1827 "try removing this `match`",
1829 Applicability::MaybeIncorrect, // speculative
1834 attrs.extend(self.parse_inner_attributes()?);
1836 let mut arms: Vec<Arm> = Vec::new();
1837 while self.token != token::CloseDelim(token::Brace) {
1838 match self.parse_arm() {
1839 Ok(arm) => arms.push(arm),
1841 // Recover by skipping to the end of the block.
1843 self.recover_stmt();
1844 let span = lo.to(self.token.span);
1845 if self.token == token::CloseDelim(token::Brace) {
1848 return Ok(self.mk_expr(span, ExprKind::Match(scrutinee, arms), attrs));
1852 let hi = self.token.span;
1854 Ok(self.mk_expr(lo.to(hi), ExprKind::Match(scrutinee, arms), attrs))
1857 pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
1858 let attrs = self.parse_outer_attributes()?;
1859 let lo = self.token.span;
1860 let pat = self.parse_top_pat(GateOr::No)?;
1861 let guard = if self.eat_keyword(kw::If) { Some(self.parse_expr()?) } else { None };
1862 let arrow_span = self.token.span;
1863 self.expect(&token::FatArrow)?;
1864 let arm_start_span = self.token.span;
1866 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| {
1867 err.span_label(arrow_span, "while parsing the `match` arm starting here");
1871 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
1872 && self.token != token::CloseDelim(token::Brace);
1874 let hi = self.prev_token.span;
1877 let sm = self.sess.source_map();
1878 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]).map_err(
1880 match (sm.span_to_lines(expr.span), sm.span_to_lines(arm_start_span)) {
1881 (Ok(ref expr_lines), Ok(ref arm_start_lines))
1882 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
1883 && expr_lines.lines.len() == 2
1884 && self.token == token::FatArrow =>
1886 // We check whether there's any trailing code in the parse span,
1887 // if there isn't, we very likely have the following:
1890 // | -- - missing comma
1894 // | - ^^ self.token.span
1896 // | parsed until here as `"y" & X`
1897 err.span_suggestion_short(
1898 arm_start_span.shrink_to_hi(),
1899 "missing a comma here to end this `match` arm",
1901 Applicability::MachineApplicable,
1907 "while parsing the `match` arm starting here",
1915 self.eat(&token::Comma);
1925 is_placeholder: false,
1929 /// Parses a `try {...}` expression (`try` token already eaten).
1930 fn parse_try_block(&mut self, span_lo: Span, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1931 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1932 attrs.extend(iattrs);
1933 if self.eat_keyword(kw::Catch) {
1934 let mut error = self.struct_span_err(
1935 self.prev_token.span,
1936 "keyword `catch` cannot follow a `try` block",
1938 error.help("try using `match` on the result of the `try` block instead");
1942 let span = span_lo.to(body.span);
1943 self.sess.gated_spans.gate(sym::try_blocks, span);
1944 Ok(self.mk_expr(span, ExprKind::TryBlock(body), attrs))
1948 fn is_do_catch_block(&self) -> bool {
1949 self.token.is_keyword(kw::Do)
1950 && self.is_keyword_ahead(1, &[kw::Catch])
1951 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
1952 && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1955 fn is_try_block(&self) -> bool {
1956 self.token.is_keyword(kw::Try)
1957 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
1958 && self.token.uninterpolated_span().rust_2018()
1961 /// Parses an `async move? {...}` expression.
1962 fn parse_async_block(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1963 let lo = self.token.span;
1964 self.expect_keyword(kw::Async)?;
1965 let capture_clause = self.parse_capture_clause();
1966 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1967 attrs.extend(iattrs);
1968 let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);
1969 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1972 fn is_async_block(&self) -> bool {
1973 self.token.is_keyword(kw::Async)
1976 self.is_keyword_ahead(1, &[kw::Move])
1977 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
1980 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
1984 fn is_certainly_not_a_block(&self) -> bool {
1985 self.look_ahead(1, |t| t.is_ident())
1987 // `{ ident, ` cannot start a block.
1988 self.look_ahead(2, |t| t == &token::Comma)
1989 || self.look_ahead(2, |t| t == &token::Colon)
1991 // `{ ident: token, ` cannot start a block.
1992 self.look_ahead(4, |t| t == &token::Comma) ||
1993 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
1994 self.look_ahead(3, |t| !t.can_begin_type())
1999 fn maybe_parse_struct_expr(
2003 ) -> Option<PResult<'a, P<Expr>>> {
2004 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2005 if struct_allowed || self.is_certainly_not_a_block() {
2006 // This is a struct literal, but we don't can't accept them here.
2007 let expr = self.parse_struct_expr(path.clone(), attrs.clone());
2008 if let (Ok(expr), false) = (&expr, struct_allowed) {
2009 self.error_struct_lit_not_allowed_here(path.span, expr.span);
2016 fn error_struct_lit_not_allowed_here(&self, lo: Span, sp: Span) {
2017 self.struct_span_err(sp, "struct literals are not allowed here")
2018 .multipart_suggestion(
2019 "surround the struct literal with parentheses",
2020 vec![(lo.shrink_to_lo(), "(".to_string()), (sp.shrink_to_hi(), ")".to_string())],
2021 Applicability::MachineApplicable,
2026 pub(super) fn parse_struct_expr(
2030 ) -> PResult<'a, P<Expr>> {
2032 let mut fields = Vec::new();
2033 let mut base = None;
2034 let mut recover_async = false;
2036 attrs.extend(self.parse_inner_attributes()?);
2038 let mut async_block_err = |e: &mut DiagnosticBuilder<'_>, span: Span| {
2039 recover_async = true;
2040 e.span_label(span, "`async` blocks are only allowed in the 2018 edition");
2041 e.help("set `edition = \"2018\"` in `Cargo.toml`");
2042 e.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
2045 while self.token != token::CloseDelim(token::Brace) {
2046 if self.eat(&token::DotDot) {
2047 let exp_span = self.prev_token.span;
2048 match self.parse_expr() {
2049 Ok(e) => base = Some(e),
2052 self.recover_stmt();
2055 self.recover_struct_comma_after_dotdot(exp_span);
2059 let recovery_field = self.find_struct_error_after_field_looking_code();
2060 let parsed_field = match self.parse_field() {
2063 if pth == kw::Async {
2064 async_block_err(&mut e, pth.span);
2066 e.span_label(pth.span, "while parsing this struct");
2070 // If the next token is a comma, then try to parse
2071 // what comes next as additional fields, rather than
2072 // bailing out until next `}`.
2073 if self.token != token::Comma {
2074 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2075 if self.token != token::Comma {
2083 match self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]) {
2085 if let Some(f) = parsed_field.or(recovery_field) {
2086 // Only include the field if there's no parse error for the field name.
2091 if pth == kw::Async {
2092 async_block_err(&mut e, pth.span);
2094 e.span_label(pth.span, "while parsing this struct");
2095 if let Some(f) = recovery_field {
2098 self.prev_token.span.shrink_to_hi(),
2099 "try adding a comma",
2101 Applicability::MachineApplicable,
2106 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2107 self.eat(&token::Comma);
2112 let span = pth.span.to(self.token.span);
2113 self.expect(&token::CloseDelim(token::Brace))?;
2114 let expr = if recover_async { ExprKind::Err } else { ExprKind::Struct(pth, fields, base) };
2115 Ok(self.mk_expr(span, expr, attrs))
2118 /// Use in case of error after field-looking code: `S { foo: () with a }`.
2119 fn find_struct_error_after_field_looking_code(&self) -> Option<Field> {
2120 match self.token.ident() {
2121 Some((ident, is_raw))
2122 if (is_raw || !ident.is_reserved())
2123 && self.look_ahead(1, |t| *t == token::Colon) =>
2127 span: self.token.span,
2128 expr: self.mk_expr_err(self.token.span),
2129 is_shorthand: false,
2130 attrs: AttrVec::new(),
2132 is_placeholder: false,
2139 fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
2140 if self.token != token::Comma {
2143 self.struct_span_err(
2144 span.to(self.prev_token.span),
2145 "cannot use a comma after the base struct",
2147 .span_suggestion_short(
2149 "remove this comma",
2151 Applicability::MachineApplicable,
2153 .note("the base struct must always be the last field")
2155 self.recover_stmt();
2158 /// Parses `ident (COLON expr)?`.
2159 fn parse_field(&mut self) -> PResult<'a, Field> {
2160 let attrs = self.parse_outer_attributes()?.into();
2161 let lo = self.token.span;
2163 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2164 let is_shorthand = !self.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
2165 let (ident, expr) = if is_shorthand {
2166 // Mimic `x: x` for the `x` field shorthand.
2167 let ident = self.parse_ident_common(false)?;
2168 let path = ast::Path::from_ident(ident);
2169 (ident, self.mk_expr(ident.span, ExprKind::Path(None, path), AttrVec::new()))
2171 let ident = self.parse_field_name()?;
2172 self.error_on_eq_field_init(ident);
2174 (ident, self.parse_expr()?)
2178 span: lo.to(expr.span),
2183 is_placeholder: false,
2187 /// Check for `=`. This means the source incorrectly attempts to
2188 /// initialize a field with an eq rather than a colon.
2189 fn error_on_eq_field_init(&self, field_name: Ident) {
2190 if self.token != token::Eq {
2194 self.struct_span_err(self.token.span, "expected `:`, found `=`")
2196 field_name.span.shrink_to_hi().to(self.token.span),
2197 "replace equals symbol with a colon",
2199 Applicability::MachineApplicable,
2204 fn err_dotdotdot_syntax(&self, span: Span) {
2205 self.struct_span_err(span, "unexpected token: `...`")
2208 "use `..` for an exclusive range",
2210 Applicability::MaybeIncorrect,
2214 "or `..=` for an inclusive range",
2216 Applicability::MaybeIncorrect,
2221 fn err_larrow_operator(&self, span: Span) {
2222 self.struct_span_err(span, "unexpected token: `<-`")
2225 "if you meant to write a comparison against a negative value, add a \
2226 space in between `<` and `-`",
2228 Applicability::MaybeIncorrect,
2233 fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2234 ExprKind::AssignOp(binop, lhs, rhs)
2239 start: Option<P<Expr>>,
2240 end: Option<P<Expr>>,
2241 limits: RangeLimits,
2242 ) -> PResult<'a, ExprKind> {
2243 if end.is_none() && limits == RangeLimits::Closed {
2244 self.error_inclusive_range_with_no_end(self.prev_token.span);
2247 Ok(ExprKind::Range(start, end, limits))
2251 fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
2252 ExprKind::Unary(unop, expr)
2255 fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2256 ExprKind::Binary(binop, lhs, rhs)
2259 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
2260 ExprKind::Index(expr, idx)
2263 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
2264 ExprKind::Call(f, args)
2267 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2268 let span = lo.to(self.prev_token.span);
2269 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), AttrVec::new());
2270 self.recover_from_await_method_call();
2274 crate fn mk_expr(&self, span: Span, kind: ExprKind, attrs: AttrVec) -> P<Expr> {
2275 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None })
2278 pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
2279 self.mk_expr(span, ExprKind::Err, AttrVec::new())