1 use super::diagnostics::Error;
2 use super::pat::{GateOr, PARAM_EXPECTED};
3 use super::{BlockMode, Parser, PathStyle, PrevTokenKind, Restrictions, TokenType};
4 use super::{SemiColonMode, SeqSep, TokenExpectType};
5 use crate::maybe_recover_from_interpolated_ty_qpath;
7 use rustc_errors::{Applicability, PResult};
9 use syntax::ast::{self, AttrStyle, AttrVec, CaptureBy, Field, Ident, Lit, DUMMY_NODE_ID};
11 AnonConst, BinOp, BinOpKind, FnDecl, FunctionRetTy, Mac, Param, Ty, TyKind, UnOp,
13 use syntax::ast::{Arm, BlockCheckMode, Expr, ExprKind, IsAsync, Label, Movability, RangeLimits};
14 use syntax::print::pprust;
16 use syntax::token::{self, Token, TokenKind};
17 use syntax::util::classify;
18 use syntax::util::literal::LitError;
19 use syntax::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity};
20 use syntax_pos::source_map::{self, Span};
21 use syntax_pos::symbol::{kw, sym, Symbol};
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),
55 // N.B., `NtIdent(ident)` is normalized to `Ident` in `fn bump`.
63 pub(super) enum LhsExpr {
65 AttributesParsed(AttrVec),
66 AlreadyParsed(P<Expr>),
69 impl From<Option<AttrVec>> for LhsExpr {
70 /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
71 /// and `None` into `LhsExpr::NotYetParsed`.
73 /// This conversion does not allocate.
74 fn from(o: Option<AttrVec>) -> Self {
75 if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed }
79 impl From<P<Expr>> for LhsExpr {
80 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
82 /// This conversion does not allocate.
83 fn from(expr: P<Expr>) -> Self {
84 LhsExpr::AlreadyParsed(expr)
89 /// Parses an expression.
91 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
92 self.parse_expr_res(Restrictions::empty(), None)
95 pub(super) fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> {
96 self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
99 fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P<Expr>> {
100 match self.parse_expr() {
101 Ok(expr) => Ok(expr),
102 Err(mut err) => match self.token.kind {
103 token::Ident(name, false)
104 if name == kw::Underscore && self.look_ahead(1, |t| t == &token::Comma) =>
106 // Special-case handling of `foo(_, _, _)`
108 let sp = self.token.span;
110 Ok(self.mk_expr(sp, ExprKind::Err, AttrVec::new()))
117 /// Parses a sequence of expressions delimited by parentheses.
118 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
119 self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r)
122 /// Parses an expression, subject to the given restrictions.
124 pub(super) fn parse_expr_res(
127 already_parsed_attrs: Option<AttrVec>,
128 ) -> PResult<'a, P<Expr>> {
129 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
132 /// Parses an associative expression.
134 /// This parses an expression accounting for associativity and precedence of the operators in
137 fn parse_assoc_expr(&mut self, already_parsed_attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> {
138 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
141 /// Parses an associative expression with operators of at least `min_prec` precedence.
142 pub(super) fn parse_assoc_expr_with(
146 ) -> PResult<'a, P<Expr>> {
147 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
150 let attrs = match lhs {
151 LhsExpr::AttributesParsed(attrs) => Some(attrs),
154 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
155 return self.parse_prefix_range_expr(attrs);
157 self.parse_prefix_expr(attrs)?
160 let last_type_ascription_set = self.last_type_ascription.is_some();
162 if !self.should_continue_as_assoc_expr(&lhs) {
163 self.last_type_ascription = None;
167 self.expected_tokens.push(TokenType::Operator);
168 while let Some(op) = self.check_assoc_op() {
169 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
170 // it refers to. Interpolated identifiers are unwrapped early and never show up here
171 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
172 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
173 let lhs_span = match (self.prev_token_kind, &lhs.kind) {
174 (PrevTokenKind::Interpolated, _) => self.prev_span,
175 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
176 if path.segments.len() == 1 =>
183 let cur_op_span = self.token.span;
184 let restrictions = if op.is_assign_like() {
185 self.restrictions & Restrictions::NO_STRUCT_LITERAL
189 let prec = op.precedence();
193 // Check for deprecated `...` syntax
194 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
195 self.err_dotdotdot_syntax(self.token.span);
198 if self.token == token::LArrow {
199 self.err_larrow_operator(self.token.span);
203 if op.is_comparison() {
204 if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
209 if op == AssocOp::As {
210 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
212 } else if op == AssocOp::Colon {
213 lhs = self.parse_assoc_op_ascribe(lhs, lhs_span)?;
215 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
216 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
217 // generalise it to the Fixity::None code.
218 lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?;
222 let fixity = op.fixity();
223 let prec_adjustment = match fixity {
226 // We currently have no non-associative operators that are not handled above by
227 // the special cases. The code is here only for future convenience.
230 let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
231 this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
234 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
235 // including the attributes.
239 .filter(|a| a.style == AttrStyle::Outer)
241 .map_or(lhs_span, |a| a.span);
242 let span = lhs_span.to(rhs.span);
255 | AssocOp::ShiftRight
261 | AssocOp::GreaterEqual => {
262 let ast_op = op.to_ast_binop().unwrap();
263 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
264 self.mk_expr(span, binary, AttrVec::new())
267 self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span), AttrVec::new())
269 AssocOp::AssignOp(k) => {
271 token::Plus => BinOpKind::Add,
272 token::Minus => BinOpKind::Sub,
273 token::Star => BinOpKind::Mul,
274 token::Slash => BinOpKind::Div,
275 token::Percent => BinOpKind::Rem,
276 token::Caret => BinOpKind::BitXor,
277 token::And => BinOpKind::BitAnd,
278 token::Or => BinOpKind::BitOr,
279 token::Shl => BinOpKind::Shl,
280 token::Shr => BinOpKind::Shr,
282 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
283 self.mk_expr(span, aopexpr, AttrVec::new())
285 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
286 self.bug("AssocOp should have been handled by special case")
290 if let Fixity::None = fixity {
294 if last_type_ascription_set {
295 self.last_type_ascription = None;
300 fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
301 match (self.expr_is_complete(lhs), self.check_assoc_op()) {
302 // Semi-statement forms are odd:
303 // See https://github.com/rust-lang/rust/issues/29071
304 (true, None) => false,
305 (false, _) => true, // Continue parsing the expression.
306 // An exhaustive check is done in the following block, but these are checked first
307 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
308 // want to keep their span info to improve diagnostics in these cases in a later stage.
309 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
310 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
311 (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475)
312 (true, Some(AssocOp::Add)) // `{ 42 } + 42
313 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
314 // `if x { a } else { b } && if y { c } else { d }`
315 if !self.look_ahead(1, |t| t.is_reserved_ident()) => {
316 // These cases are ambiguous and can't be identified in the parser alone.
317 let sp = self.sess.source_map().start_point(self.token.span);
318 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
321 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => false,
323 self.error_found_expr_would_be_stmt(lhs);
329 /// We've found an expression that would be parsed as a statement,
330 /// but the next token implies this should be parsed as an expression.
331 /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
332 fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
333 let mut err = self.struct_span_err(
335 &format!("expected expression, found `{}`", pprust::token_to_string(&self.token),),
337 err.span_label(self.token.span, "expected expression");
338 self.sess.expr_parentheses_needed(&mut err, lhs.span, Some(pprust::expr_to_string(&lhs)));
342 /// Possibly translate the current token to an associative operator.
343 /// The method does not advance the current token.
345 /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
346 fn check_assoc_op(&self) -> Option<AssocOp> {
347 match (AssocOp::from_token(&self.token), &self.token.kind) {
348 (op @ Some(_), _) => op,
349 (None, token::Ident(sym::and, false)) => {
350 self.error_bad_logical_op("and", "&&", "conjunction");
353 (None, token::Ident(sym::or, false)) => {
354 self.error_bad_logical_op("or", "||", "disjunction");
361 /// Error on `and` and `or` suggesting `&&` and `||` respectively.
362 fn error_bad_logical_op(&self, bad: &str, good: &str, english: &str) {
363 self.struct_span_err(self.token.span, &format!("`{}` is not a logical operator", bad))
364 .span_suggestion_short(
366 &format!("use `{}` to perform logical {}", good, english),
368 Applicability::MachineApplicable,
370 .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators")
374 /// Checks if this expression is a successfully parsed statement.
375 fn expr_is_complete(&self, e: &Expr) -> bool {
376 self.restrictions.contains(Restrictions::STMT_EXPR)
377 && !classify::expr_requires_semi_to_be_stmt(e)
380 /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
381 /// The other two variants are handled in `parse_prefix_range_expr` below.
388 ) -> PResult<'a, P<Expr>> {
389 let rhs = if self.is_at_start_of_range_notation_rhs() {
390 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
394 let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
395 let span = lhs.span.to(rhs_span);
397 if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed };
398 Ok(self.mk_expr(span, self.mk_range(Some(lhs), rhs, limits)?, AttrVec::new()))
401 fn is_at_start_of_range_notation_rhs(&self) -> bool {
402 if self.token.can_begin_expr() {
403 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
404 if self.token == token::OpenDelim(token::Brace) {
405 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
413 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
414 fn parse_prefix_range_expr(&mut self, attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> {
415 // Check for deprecated `...` syntax.
416 if self.token == token::DotDotDot {
417 self.err_dotdotdot_syntax(self.token.span);
421 [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
422 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
426 let limits = match self.token.kind {
427 token::DotDot => RangeLimits::HalfOpen,
428 _ => RangeLimits::Closed,
430 let op = AssocOp::from_token(&self.token);
431 let attrs = self.parse_or_use_outer_attributes(attrs)?;
432 let lo = self.token.span;
434 let (span, opt_end) = if self.is_at_start_of_range_notation_rhs() {
435 // RHS must be parsed with more associativity than the dots.
436 self.parse_assoc_expr_with(op.unwrap().precedence() + 1, LhsExpr::NotYetParsed)
437 .map(|x| (lo.to(x.span), Some(x)))?
441 Ok(self.mk_expr(span, self.mk_range(None, opt_end, limits)?, attrs))
444 /// Parses a prefix-unary-operator expr.
445 fn parse_prefix_expr(&mut self, attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> {
446 let attrs = self.parse_or_use_outer_attributes(attrs)?;
447 let lo = self.token.span;
448 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
449 let (hi, ex) = match self.token.kind {
450 token::Not => self.parse_unary_expr(lo, UnOp::Not), // `!expr`
451 token::Tilde => self.recover_tilde_expr(lo), // `~expr`
452 token::BinOp(token::Minus) => self.parse_unary_expr(lo, UnOp::Neg), // `-expr`
453 token::BinOp(token::Star) => self.parse_unary_expr(lo, UnOp::Deref), // `*expr`
454 token::BinOp(token::And) | token::AndAnd => self.parse_borrow_expr(lo),
455 token::Ident(..) if self.token.is_keyword(kw::Box) => self.parse_box_expr(lo),
456 token::Ident(..) if self.is_mistaken_not_ident_negation() => self.recover_not_expr(lo),
457 _ => return self.parse_dot_or_call_expr(Some(attrs)),
459 Ok(self.mk_expr(lo.to(hi), ex, attrs))
462 fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P<Expr>)> {
464 let expr = self.parse_prefix_expr(None);
465 let (span, expr) = self.interpolated_or_expr_span(expr)?;
466 Ok((lo.to(span), expr))
469 fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
470 let (span, expr) = self.parse_prefix_expr_common(lo)?;
471 Ok((span, self.mk_unary(op, expr)))
474 // Recover on `!` suggesting for bitwise negation instead.
475 fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
476 self.struct_span_err(lo, "`~` cannot be used as a unary operator")
477 .span_suggestion_short(
479 "use `!` to perform bitwise not",
481 Applicability::MachineApplicable,
485 self.parse_unary_expr(lo, UnOp::Not)
488 /// Parse `box expr`.
489 fn parse_box_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
490 let (span, expr) = self.parse_prefix_expr_common(lo)?;
491 self.sess.gated_spans.gate(sym::box_syntax, span);
492 Ok((span, ExprKind::Box(expr)))
495 fn is_mistaken_not_ident_negation(&self) -> bool {
496 let token_cannot_continue_expr = |t: &Token| match t.kind {
497 // These tokens can start an expression after `!`, but
498 // can't continue an expression after an ident
499 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
500 token::Literal(..) | token::Pound => true,
501 _ => t.is_whole_expr(),
503 self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
506 /// Recover on `not expr` in favor of `!expr`.
507 fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
509 let not_token = self.look_ahead(1, |t| t.clone());
510 self.struct_span_err(
512 &format!("unexpected {} after identifier", super::token_descr(¬_token)),
514 .span_suggestion_short(
515 // Span the `not` plus trailing whitespace to avoid
516 // trailing whitespace after the `!` in our suggestion
517 self.sess.source_map().span_until_non_whitespace(lo.to(not_token.span)),
518 "use `!` to perform logical negation",
520 Applicability::MachineApplicable,
525 self.parse_unary_expr(lo, UnOp::Not)
528 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
529 fn interpolated_or_expr_span(
531 expr: PResult<'a, P<Expr>>,
532 ) -> PResult<'a, (Span, P<Expr>)> {
534 if self.prev_token_kind == PrevTokenKind::Interpolated {
542 fn parse_assoc_op_cast(
546 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind,
547 ) -> PResult<'a, P<Expr>> {
548 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
549 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), AttrVec::new())
552 // Save the state of the parser before parsing type normally, in case there is a
553 // LessThan comparison after this cast.
554 let parser_snapshot_before_type = self.clone();
555 match self.parse_ty_no_plus() {
556 Ok(rhs) => Ok(mk_expr(self, rhs)),
557 Err(mut type_err) => {
558 // Rewind to before attempting to parse the type with generics, to recover
559 // from situations like `x as usize < y` in which we first tried to parse
560 // `usize < y` as a type with generic arguments.
561 let parser_snapshot_after_type = self.clone();
562 mem::replace(self, parser_snapshot_before_type);
564 match self.parse_path(PathStyle::Expr) {
566 let (op_noun, op_verb) = match self.token.kind {
567 token::Lt => ("comparison", "comparing"),
568 token::BinOp(token::Shl) => ("shift", "shifting"),
570 // We can end up here even without `<` being the next token, for
571 // example because `parse_ty_no_plus` returns `Err` on keywords,
572 // but `parse_path` returns `Ok` on them due to error recovery.
573 // Return original error and parser state.
574 mem::replace(self, parser_snapshot_after_type);
575 return Err(type_err);
579 // Successfully parsed the type path leaving a `<` yet to parse.
582 // Report non-fatal diagnostics, keep `x as usize` as an expression
583 // in AST and continue parsing.
585 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
586 pprust::path_to_string(&path),
589 let span_after_type = parser_snapshot_after_type.token.span;
590 let expr = mk_expr(self, self.mk_ty(path.span, TyKind::Path(None, path)));
593 .span_to_snippet(expr.span)
594 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
596 self.struct_span_err(self.token.span, &msg)
598 self.look_ahead(1, |t| t.span).to(span_after_type),
599 "interpreted as generic arguments",
601 .span_label(self.token.span, format!("not interpreted as {}", op_noun))
604 &format!("try {} the cast value", op_verb),
605 format!("({})", expr_str),
606 Applicability::MachineApplicable,
612 Err(mut path_err) => {
613 // Couldn't parse as a path, return original error and parser state.
615 mem::replace(self, parser_snapshot_after_type);
623 fn parse_assoc_op_ascribe(&mut self, lhs: P<Expr>, lhs_span: Span) -> PResult<'a, P<Expr>> {
624 let maybe_path = self.could_ascription_be_path(&lhs.kind);
625 self.last_type_ascription = Some((self.prev_span, maybe_path));
626 let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
627 self.sess.gated_spans.gate(sym::type_ascription, lhs.span);
631 /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
632 fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
634 let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo);
635 let expr = self.parse_prefix_expr(None);
636 let (span, expr) = self.interpolated_or_expr_span(expr)?;
637 Ok((lo.to(span), ExprKind::AddrOf(borrow_kind, mutbl, expr)))
640 /// Parse `mut?` or `raw [ const | mut ]`.
641 fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) {
642 if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) {
643 // `raw [ const | mut ]`.
644 let found_raw = self.eat_keyword(kw::Raw);
646 let mutability = self.parse_const_or_mut().unwrap();
647 self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_span));
648 (ast::BorrowKind::Raw, mutability)
651 (ast::BorrowKind::Ref, self.parse_mutability())
655 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
656 fn parse_dot_or_call_expr(&mut self, attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> {
657 let attrs = self.parse_or_use_outer_attributes(attrs)?;
658 let base = self.parse_bottom_expr();
659 let (span, base) = self.interpolated_or_expr_span(base)?;
660 self.parse_dot_or_call_expr_with(base, span, attrs)
663 pub(super) fn parse_dot_or_call_expr_with(
668 ) -> PResult<'a, P<Expr>> {
669 // Stitch the list of outer attributes onto the return value.
670 // A little bit ugly, but the best way given the current code
672 self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| {
673 expr.map(|mut expr| {
674 attrs.extend::<Vec<_>>(expr.attrs.into());
676 self.error_attr_on_if_expr(&expr);
682 fn error_attr_on_if_expr(&self, expr: &Expr) {
683 if let (ExprKind::If(..), [a0, ..]) = (&expr.kind, &*expr.attrs) {
684 // Just point to the first attribute in there...
685 self.struct_span_err(a0.span, "attributes are not yet allowed on `if` expressions")
690 fn parse_dot_or_call_expr_with_(&mut self, mut e: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
692 if self.eat(&token::Question) {
694 e = self.mk_expr(lo.to(self.prev_span), ExprKind::Try(e), AttrVec::new());
697 if self.eat(&token::Dot) {
699 e = self.parse_dot_suffix_expr(lo, e)?;
702 if self.expr_is_complete(&e) {
705 e = match self.token.kind {
706 token::OpenDelim(token::Paren) => self.parse_fn_call_expr(lo, e),
707 token::OpenDelim(token::Bracket) => self.parse_index_expr(lo, e)?,
713 fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
714 match self.token.kind {
715 token::Ident(..) => self.parse_dot_suffix(base, lo),
716 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
717 Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix))
719 token::Literal(token::Lit { kind: token::Float, symbol, .. }) => {
720 self.recover_field_access_by_float_lit(lo, base, symbol)
723 self.error_unexpected_after_dot();
729 fn error_unexpected_after_dot(&self) {
730 // FIXME Could factor this out into non_fatal_unexpected or something.
731 let actual = pprust::token_to_string(&self.token);
732 self.struct_span_err(self.token.span, &format!("unexpected token: `{}`", actual)).emit();
735 fn recover_field_access_by_float_lit(
740 ) -> PResult<'a, P<Expr>> {
743 let fstr = sym.as_str();
744 let msg = format!("unexpected token: `{}`", sym);
746 let mut err = self.struct_span_err(self.prev_span, &msg);
747 err.span_label(self.prev_span, "unexpected token");
749 if fstr.chars().all(|x| "0123456789.".contains(x)) {
750 let float = match fstr.parse::<f64>() {
757 let sugg = pprust::to_string(|s| {
761 s.print_usize(float.trunc() as usize);
764 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
767 lo.to(self.prev_span),
768 "try parenthesizing the first index",
770 Applicability::MachineApplicable,
776 fn parse_tuple_field_access_expr(
781 suffix: Option<Symbol>,
783 let span = self.token.span;
785 let field = ExprKind::Field(base, Ident::new(field, span));
786 self.expect_no_suffix(span, "a tuple index", suffix);
787 self.mk_expr(lo.to(span), field, AttrVec::new())
790 /// Parse a function call expression, `expr(...)`.
791 fn parse_fn_call_expr(&mut self, lo: Span, fun: P<Expr>) -> P<Expr> {
792 let seq = self.parse_paren_expr_seq().map(|args| {
793 self.mk_expr(lo.to(self.prev_span), self.mk_call(fun, args), AttrVec::new())
795 self.recover_seq_parse_error(token::Paren, lo, seq)
798 /// Parse an indexing expression `expr[...]`.
799 fn parse_index_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
801 let index = self.parse_expr()?;
802 self.expect(&token::CloseDelim(token::Bracket))?;
803 Ok(self.mk_expr(lo.to(self.prev_span), self.mk_index(base, index), AttrVec::new()))
806 /// Assuming we have just parsed `.`, continue parsing into an expression.
807 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
808 if self.token.span.rust_2018() && self.eat_keyword(kw::Await) {
809 return self.mk_await_expr(self_arg, lo);
812 let segment = self.parse_path_segment(PathStyle::Expr)?;
813 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
815 if self.check(&token::OpenDelim(token::Paren)) {
816 // Method call `expr.f()`
817 let mut args = self.parse_paren_expr_seq()?;
818 args.insert(0, self_arg);
820 let span = lo.to(self.prev_span);
821 Ok(self.mk_expr(span, ExprKind::MethodCall(segment, args), AttrVec::new()))
823 // Field access `expr.f`
824 if let Some(args) = segment.args {
825 self.struct_span_err(
827 "field expressions may not have generic arguments",
832 let span = lo.to(self.prev_span);
833 Ok(self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), AttrVec::new()))
837 /// At the bottom (top?) of the precedence hierarchy,
838 /// Parses things like parenthesized exprs, macros, `return`, etc.
840 /// N.B., this does not parse outer attributes, and is private because it only works
841 /// correctly if called from `parse_dot_or_call_expr()`.
842 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
843 maybe_recover_from_interpolated_ty_qpath!(self, true);
844 maybe_whole_expr!(self);
846 // Outer attributes are already parsed and will be
847 // added to the return value after the fact.
849 // Therefore, prevent sub-parser from parsing
850 // attributes by giving them a empty "already-parsed" list.
851 let attrs = AttrVec::new();
853 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
854 let lo = self.token.span;
855 if let token::Literal(_) = self.token.kind {
856 // This match arm is a special-case of the `_` match arm below and
857 // could be removed without changing functionality, but it's faster
858 // to have it here, especially for programs with large constants.
859 self.parse_lit_expr(attrs)
860 } else if self.check(&token::OpenDelim(token::Paren)) {
861 self.parse_tuple_parens_expr(attrs)
862 } else if self.check(&token::OpenDelim(token::Brace)) {
863 self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs)
864 } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) {
865 self.parse_closure_expr(attrs)
866 } else if self.check(&token::OpenDelim(token::Bracket)) {
867 self.parse_array_or_repeat_expr(attrs)
868 } else if self.eat_lt() {
869 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
870 Ok(self.mk_expr(lo.to(path.span), ExprKind::Path(Some(qself), path), attrs))
871 } else if self.token.is_path_start() {
872 self.parse_path_start_expr(attrs)
873 } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
874 self.parse_closure_expr(attrs)
875 } else if self.eat_keyword(kw::If) {
876 self.parse_if_expr(attrs)
877 } else if self.eat_keyword(kw::For) {
878 self.parse_for_expr(None, self.prev_span, attrs)
879 } else if self.eat_keyword(kw::While) {
880 self.parse_while_expr(None, self.prev_span, attrs)
881 } else if let Some(label) = self.eat_label() {
882 self.parse_labeled_expr(label, attrs)
883 } else if self.eat_keyword(kw::Loop) {
884 self.parse_loop_expr(None, self.prev_span, attrs)
885 } else if self.eat_keyword(kw::Continue) {
886 let kind = ExprKind::Continue(self.eat_label());
887 Ok(self.mk_expr(lo.to(self.prev_span), kind, attrs))
888 } else if self.eat_keyword(kw::Match) {
889 let match_sp = self.prev_span;
890 self.parse_match_expr(attrs).map_err(|mut err| {
891 err.span_label(match_sp, "while parsing this match expression");
894 } else if self.eat_keyword(kw::Unsafe) {
895 self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs)
896 } else if self.is_do_catch_block() {
897 self.recover_do_catch(attrs)
898 } else if self.is_try_block() {
899 self.expect_keyword(kw::Try)?;
900 self.parse_try_block(lo, attrs)
901 } else if self.eat_keyword(kw::Return) {
902 self.parse_return_expr(attrs)
903 } else if self.eat_keyword(kw::Break) {
904 self.parse_break_expr(attrs)
905 } else if self.eat_keyword(kw::Yield) {
906 self.parse_yield_expr(attrs)
907 } else if self.eat_keyword(kw::Let) {
908 self.parse_let_expr(attrs)
909 } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
910 // Don't complain about bare semicolons after unclosed braces
911 // recovery in order to keep the error count down. Fixing the
912 // delimiters will possibly also fix the bare semicolon found in
913 // expression context. For example, silence the following error:
915 // error: expected expression, found `;`
919 // | ^ expected expression
921 Ok(self.mk_expr_err(self.token.span))
922 } else if self.token.span.rust_2018() {
923 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
924 if self.check_keyword(kw::Async) {
925 if self.is_async_block() {
926 // Check for `async {` and `async move {`.
927 self.parse_async_block(attrs)
929 self.parse_closure_expr(attrs)
931 } else if self.eat_keyword(kw::Await) {
932 self.recover_incorrect_await_syntax(lo, self.prev_span, attrs)
934 self.parse_lit_expr(attrs)
937 self.parse_lit_expr(attrs)
941 fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
942 let lo = self.token.span;
943 match self.parse_opt_lit() {
945 let expr = self.mk_expr(lo.to(self.prev_span), ExprKind::Lit(literal), attrs);
946 self.maybe_recover_from_bad_qpath(expr, true)
948 None => return Err(self.expected_expression_found()),
952 fn parse_tuple_parens_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
953 let lo = self.token.span;
954 self.expect(&token::OpenDelim(token::Paren))?;
955 attrs.extend(self.parse_inner_attributes()?); // `(#![foo] a, b, ...)` is OK.
956 let (es, trailing_comma) = match self.parse_seq_to_end(
957 &token::CloseDelim(token::Paren),
958 SeqSep::trailing_allowed(token::Comma),
959 |p| p.parse_expr_catch_underscore(),
962 Err(err) => return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err))),
964 let kind = if es.len() == 1 && !trailing_comma {
965 // `(e)` is parenthesized `e`.
966 ExprKind::Paren(es.into_iter().nth(0).unwrap())
968 // `(e,)` is a tuple with only one field, `e`.
971 let expr = self.mk_expr(lo.to(self.prev_span), kind, attrs);
972 self.maybe_recover_from_bad_qpath(expr, true)
975 fn parse_array_or_repeat_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
976 let lo = self.token.span;
979 attrs.extend(self.parse_inner_attributes()?);
981 let close = &token::CloseDelim(token::Bracket);
982 let kind = if self.eat(close) {
984 ExprKind::Array(Vec::new())
987 let first_expr = self.parse_expr()?;
988 if self.eat(&token::Semi) {
989 // Repeating array syntax: `[ 0; 512 ]`
990 let count = self.parse_anon_const_expr()?;
992 ExprKind::Repeat(first_expr, count)
993 } else if self.eat(&token::Comma) {
994 // Vector with two or more elements.
995 let sep = SeqSep::trailing_allowed(token::Comma);
996 let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
997 let mut exprs = vec![first_expr];
998 exprs.extend(remaining_exprs);
999 ExprKind::Array(exprs)
1001 // Vector with one element
1002 self.expect(close)?;
1003 ExprKind::Array(vec![first_expr])
1006 let expr = self.mk_expr(lo.to(self.prev_span), kind, attrs);
1007 self.maybe_recover_from_bad_qpath(expr, true)
1010 fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1011 let lo = self.token.span;
1012 let path = self.parse_path(PathStyle::Expr)?;
1014 // `!`, as an operator, is prefix, so we know this isn't that.
1015 let (hi, kind) = if self.eat(&token::Not) {
1016 // MACRO INVOCATION expression
1019 args: self.parse_mac_args()?,
1020 prior_type_ascription: self.last_type_ascription,
1022 (self.prev_span, ExprKind::Mac(mac))
1023 } else if self.check(&token::OpenDelim(token::Brace)) {
1024 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
1027 (path.span, ExprKind::Path(None, path))
1030 (path.span, ExprKind::Path(None, path))
1033 let expr = self.mk_expr(lo.to(hi), kind, attrs);
1034 self.maybe_recover_from_bad_qpath(expr, true)
1037 fn parse_labeled_expr(&mut self, label: Label, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1038 let lo = label.ident.span;
1039 self.expect(&token::Colon)?;
1040 if self.eat_keyword(kw::While) {
1041 return self.parse_while_expr(Some(label), lo, attrs);
1043 if self.eat_keyword(kw::For) {
1044 return self.parse_for_expr(Some(label), lo, attrs);
1046 if self.eat_keyword(kw::Loop) {
1047 return self.parse_loop_expr(Some(label), lo, attrs);
1049 if self.token == token::OpenDelim(token::Brace) {
1050 return self.parse_block_expr(Some(label), lo, BlockCheckMode::Default, attrs);
1053 let msg = "expected `while`, `for`, `loop` or `{` after a label";
1054 self.struct_span_err(self.token.span, msg).span_label(self.token.span, msg).emit();
1055 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1059 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1060 fn recover_do_catch(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1061 let lo = self.token.span;
1063 self.bump(); // `do`
1064 self.bump(); // `catch`
1066 let span_dc = lo.to(self.prev_span);
1067 self.struct_span_err(span_dc, "found removed `do catch` syntax")
1070 "replace with the new syntax",
1072 Applicability::MachineApplicable,
1074 .note("following RFC #2388, the new non-placeholder syntax is `try`")
1077 self.parse_try_block(lo, attrs)
1080 /// Parse an expression if the token can begin one.
1081 fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1082 Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1085 /// Parse `"return" expr?`.
1086 fn parse_return_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1087 let lo = self.prev_span;
1088 let kind = ExprKind::Ret(self.parse_expr_opt()?);
1089 let expr = self.mk_expr(lo.to(self.prev_span), kind, attrs);
1090 self.maybe_recover_from_bad_qpath(expr, true)
1093 /// Parse `"('label ":")? break expr?`.
1094 fn parse_break_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1095 let lo = self.prev_span;
1096 let label = self.eat_label();
1097 let kind = if self.token != token::OpenDelim(token::Brace)
1098 || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1100 self.parse_expr_opt()?
1104 let expr = self.mk_expr(lo.to(self.prev_span), ExprKind::Break(label, kind), attrs);
1105 self.maybe_recover_from_bad_qpath(expr, true)
1108 /// Parse `"yield" expr?`.
1109 fn parse_yield_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1110 let lo = self.prev_span;
1111 let kind = ExprKind::Yield(self.parse_expr_opt()?);
1112 let span = lo.to(self.prev_span);
1113 self.sess.gated_spans.gate(sym::generators, span);
1114 let expr = self.mk_expr(span, kind, attrs);
1115 self.maybe_recover_from_bad_qpath(expr, true)
1118 /// Returns a string literal if the next token is a string literal.
1119 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1120 /// and returns `None` if the next token is not literal at all.
1121 pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
1122 match self.parse_opt_lit() {
1123 Some(lit) => match lit.kind {
1124 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1126 symbol: lit.token.symbol,
1127 suffix: lit.token.suffix,
1131 _ => Err(Some(lit)),
1137 pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> {
1138 self.parse_opt_lit().ok_or_else(|| {
1139 let msg = format!("unexpected token: {}", super::token_descr(&self.token));
1140 self.struct_span_err(self.token.span, &msg)
1144 /// Matches `lit = true | false | token_lit`.
1145 /// Returns `None` if the next token is not a literal.
1146 pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
1147 let mut recovered = None;
1148 if self.token == token::Dot {
1149 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1150 // dot would follow an optional literal, so we do this unconditionally.
1151 recovered = self.look_ahead(1, |next_token| {
1152 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1155 if self.token.span.hi() == next_token.span.lo() {
1156 let s = String::from("0.") + &symbol.as_str();
1157 let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1158 return Some(Token::new(kind, self.token.span.to(next_token.span)));
1163 if let Some(token) = &recovered {
1165 self.error_float_lits_must_have_int_part(&token);
1169 let token = recovered.as_ref().unwrap_or(&self.token);
1170 match Lit::from_token(token) {
1175 Err(LitError::NotLiteral) => None,
1177 let span = token.span;
1178 let lit = match token.kind {
1179 token::Literal(lit) => lit,
1180 _ => unreachable!(),
1183 self.report_lit_error(err, lit, span);
1184 // Pack possible quotes and prefixes from the original literal into
1185 // the error literal's symbol so they can be pretty-printed faithfully.
1186 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1187 let symbol = Symbol::intern(&suffixless_lit.to_string());
1188 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1189 Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!()))
1194 fn error_float_lits_must_have_int_part(&self, token: &Token) {
1195 self.struct_span_err(token.span, "float literals must have an integer part")
1198 "must have an integer part",
1199 pprust::token_to_string(token),
1200 Applicability::MachineApplicable,
1205 fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) {
1206 // Checks if `s` looks like i32 or u1234 etc.
1207 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1208 s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
1211 let token::Lit { kind, suffix, .. } = lit;
1213 // `NotLiteral` is not an error by itself, so we don't report
1214 // it and give the parser opportunity to try something else.
1215 LitError::NotLiteral => {}
1216 // `LexerError` *is* an error, but it was already reported
1217 // by lexer, so here we don't report it the second time.
1218 LitError::LexerError => {}
1219 LitError::InvalidSuffix => {
1220 self.expect_no_suffix(
1222 &format!("{} {} literal", kind.article(), kind.descr()),
1226 LitError::InvalidIntSuffix => {
1227 let suf = suffix.expect("suffix error with no suffix").as_str();
1228 if looks_like_width_suffix(&['i', 'u'], &suf) {
1229 // If it looks like a width, try to be helpful.
1230 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
1231 self.struct_span_err(span, &msg)
1232 .help("valid widths are 8, 16, 32, 64 and 128")
1235 let msg = format!("invalid suffix `{}` for integer literal", suf);
1236 self.struct_span_err(span, &msg)
1237 .span_label(span, format!("invalid suffix `{}`", suf))
1238 .help("the suffix must be one of the integral types (`u32`, `isize`, etc)")
1242 LitError::InvalidFloatSuffix => {
1243 let suf = suffix.expect("suffix error with no suffix").as_str();
1244 if looks_like_width_suffix(&['f'], &suf) {
1245 // If it looks like a width, try to be helpful.
1246 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
1247 self.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit();
1249 let msg = format!("invalid suffix `{}` for float literal", suf);
1250 self.struct_span_err(span, &msg)
1251 .span_label(span, format!("invalid suffix `{}`", suf))
1252 .help("valid suffixes are `f32` and `f64`")
1256 LitError::NonDecimalFloat(base) => {
1257 let descr = match base {
1258 16 => "hexadecimal",
1261 _ => unreachable!(),
1263 self.struct_span_err(span, &format!("{} float literal is not supported", descr))
1264 .span_label(span, "not supported")
1267 LitError::IntTooLarge => {
1268 self.struct_span_err(span, "integer literal is too large").emit();
1273 pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) {
1274 if let Some(suf) = suffix {
1275 let mut err = if kind == "a tuple index"
1276 && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf)
1278 // #59553: warn instead of reject out of hand to allow the fix to percolate
1279 // through the ecosystem when people fix their macros
1283 .struct_span_warn(sp, &format!("suffixes on {} are invalid", kind));
1285 "`{}` is *temporarily* accepted on tuple index fields as it was \
1286 incorrectly accepted on stable for a few releases",
1290 "on proc macros, you'll want to use `syn::Index::from` or \
1291 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1292 to tuple field access",
1294 err.note("for more context, see https://github.com/rust-lang/rust/issues/60210");
1297 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1299 err.span_label(sp, format!("invalid suffix `{}`", suf));
1304 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1305 pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1306 maybe_whole_expr!(self);
1308 let lo = self.token.span;
1309 let minus_present = self.eat(&token::BinOp(token::Minus));
1310 let lit = self.parse_lit()?;
1311 let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new());
1314 Ok(self.mk_expr(lo.to(self.prev_span), self.mk_unary(UnOp::Neg, expr), AttrVec::new()))
1320 /// Parses a block or unsafe block.
1321 pub(super) fn parse_block_expr(
1323 opt_label: Option<Label>,
1325 blk_mode: BlockCheckMode,
1326 outer_attrs: AttrVec,
1327 ) -> PResult<'a, P<Expr>> {
1328 if let Some(label) = opt_label {
1329 self.sess.gated_spans.gate(sym::label_break_value, label.ident.span);
1332 self.expect(&token::OpenDelim(token::Brace))?;
1334 let mut attrs = outer_attrs;
1335 attrs.extend(self.parse_inner_attributes()?);
1337 let blk = self.parse_block_tail(lo, blk_mode)?;
1338 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs))
1341 /// Parses a closure expression (e.g., `move |args| expr`).
1342 fn parse_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1343 let lo = self.token.span;
1346 if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
1349 if self.token.span.rust_2018() { self.parse_asyncness() } else { IsAsync::NotAsync };
1350 if asyncness.is_async() {
1351 // Feature-gate `async ||` closures.
1352 self.sess.gated_spans.gate(sym::async_closure, self.prev_span);
1355 let capture_clause = self.parse_capture_clause();
1356 let decl = self.parse_fn_block_decl()?;
1357 let decl_hi = self.prev_span;
1358 let body = match decl.output {
1359 FunctionRetTy::Default(_) => {
1360 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
1361 self.parse_expr_res(restrictions, None)?
1364 // If an explicit return type is given, require a block to appear (RFC 968).
1365 let body_lo = self.token.span;
1366 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, AttrVec::new())?
1372 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
1377 /// Parses an optional `move` prefix to a closure lke construct.
1378 fn parse_capture_clause(&mut self) -> CaptureBy {
1379 if self.eat_keyword(kw::Move) { CaptureBy::Value } else { CaptureBy::Ref }
1382 /// Parses the `|arg, arg|` header of a closure.
1383 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
1384 let inputs = if self.eat(&token::OrOr) {
1387 self.expect(&token::BinOp(token::Or))?;
1389 .parse_seq_to_before_tokens(
1390 &[&token::BinOp(token::Or), &token::OrOr],
1391 SeqSep::trailing_allowed(token::Comma),
1392 TokenExpectType::NoExpect,
1393 |p| p.parse_fn_block_param(),
1399 let output = self.parse_ret_ty(true, true)?;
1401 Ok(P(FnDecl { inputs, output }))
1404 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1405 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
1406 let lo = self.token.span;
1407 let attrs = self.parse_outer_attributes()?;
1408 let pat = self.parse_pat(PARAM_EXPECTED)?;
1409 let ty = if self.eat(&token::Colon) {
1412 self.mk_ty(self.prev_span, TyKind::Infer)
1415 attrs: attrs.into(),
1418 span: lo.to(self.token.span),
1420 is_placeholder: false,
1424 /// Parses an `if` expression (`if` token already eaten).
1425 fn parse_if_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1426 let lo = self.prev_span;
1427 let cond = self.parse_cond_expr()?;
1429 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1430 // verify that the last statement is either an implicit return (no `;`) or an explicit
1431 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1432 // the dead code lint.
1433 let thn = if self.eat_keyword(kw::Else) || !cond.returns() {
1434 self.error_missing_if_cond(lo, cond.span)
1436 let not_block = self.token != token::OpenDelim(token::Brace);
1437 self.parse_block().map_err(|mut err| {
1439 err.span_label(lo, "this `if` expression has a condition, but no block");
1444 let els = if self.eat_keyword(kw::Else) { Some(self.parse_else_expr()?) } else { None };
1445 Ok(self.mk_expr(lo.to(self.prev_span), ExprKind::If(cond, thn, els), attrs))
1448 fn error_missing_if_cond(&self, lo: Span, span: Span) -> P<ast::Block> {
1449 let sp = self.sess.source_map().next_point(lo);
1450 self.struct_span_err(sp, "missing condition for `if` expression")
1451 .span_label(sp, "expected if condition here")
1453 self.mk_block_err(span)
1456 /// Parses the condition of a `if` or `while` expression.
1457 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
1458 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1460 if let ExprKind::Let(..) = cond.kind {
1461 // Remove the last feature gating of a `let` expression since it's stable.
1462 self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
1468 /// Parses a `let $pat = $expr` pseudo-expression.
1469 /// The `let` token has already been eaten.
1470 fn parse_let_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1471 let lo = self.prev_span;
1472 let pat = self.parse_top_pat(GateOr::No)?;
1473 self.expect(&token::Eq)?;
1474 let expr = self.with_res(Restrictions::NO_STRUCT_LITERAL, |this| {
1475 this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
1477 let span = lo.to(expr.span);
1478 self.sess.gated_spans.gate(sym::let_chains, span);
1479 Ok(self.mk_expr(span, ExprKind::Let(pat, expr), attrs))
1482 /// Parses an `else { ... }` expression (`else` token already eaten).
1483 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
1484 if self.eat_keyword(kw::If) {
1485 self.parse_if_expr(AttrVec::new())
1487 let blk = self.parse_block()?;
1488 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()))
1492 /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
1495 opt_label: Option<Label>,
1498 ) -> PResult<'a, P<Expr>> {
1499 // Record whether we are about to parse `for (`.
1500 // This is used below for recovery in case of `for ( $stuff ) $block`
1501 // in which case we will suggest `for $stuff $block`.
1502 let begin_paren = match self.token.kind {
1503 token::OpenDelim(token::Paren) => Some(self.token.span),
1507 let pat = self.parse_top_pat(GateOr::Yes)?;
1508 if !self.eat_keyword(kw::In) {
1509 self.error_missing_in_for_loop();
1511 self.check_for_for_in_in_typo(self.prev_span);
1512 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1514 let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
1516 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
1517 attrs.extend(iattrs);
1519 let kind = ExprKind::ForLoop(pat, expr, loop_block, opt_label);
1520 Ok(self.mk_expr(lo.to(self.prev_span), kind, attrs))
1523 fn error_missing_in_for_loop(&self) {
1524 let in_span = self.prev_span.between(self.token.span);
1525 self.struct_span_err(in_span, "missing `in` in `for` loop")
1526 .span_suggestion_short(
1528 "try adding `in` here",
1530 // Has been misleading, at least in the past (closed Issue #48492).
1531 Applicability::MaybeIncorrect,
1536 /// Parses a `while` or `while let` expression (`while` token already eaten).
1537 fn parse_while_expr(
1539 opt_label: Option<Label>,
1542 ) -> PResult<'a, P<Expr>> {
1543 let cond = self.parse_cond_expr()?;
1544 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1545 attrs.extend(iattrs);
1546 Ok(self.mk_expr(lo.to(self.prev_span), ExprKind::While(cond, body, opt_label), attrs))
1549 /// Parses `loop { ... }` (`loop` token already eaten).
1552 opt_label: Option<Label>,
1555 ) -> PResult<'a, P<Expr>> {
1556 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1557 attrs.extend(iattrs);
1558 Ok(self.mk_expr(lo.to(self.prev_span), ExprKind::Loop(body, opt_label), attrs))
1561 fn eat_label(&mut self) -> Option<Label> {
1562 self.token.lifetime().map(|ident| {
1563 let span = self.token.span;
1565 Label { ident: Ident::new(ident.name, span) }
1569 /// Parses a `match ... { ... }` expression (`match` token already eaten).
1570 fn parse_match_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1571 let match_span = self.prev_span;
1572 let lo = self.prev_span;
1573 let scrutinee = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1574 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
1575 if self.token == token::Semi {
1576 e.span_suggestion_short(
1578 "try removing this `match`",
1580 Applicability::MaybeIncorrect, // speculative
1585 attrs.extend(self.parse_inner_attributes()?);
1587 let mut arms: Vec<Arm> = Vec::new();
1588 while self.token != token::CloseDelim(token::Brace) {
1589 match self.parse_arm() {
1590 Ok(arm) => arms.push(arm),
1592 // Recover by skipping to the end of the block.
1594 self.recover_stmt();
1595 let span = lo.to(self.token.span);
1596 if self.token == token::CloseDelim(token::Brace) {
1599 return Ok(self.mk_expr(span, ExprKind::Match(scrutinee, arms), attrs));
1603 let hi = self.token.span;
1605 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(scrutinee, arms), attrs));
1608 pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
1609 let attrs = self.parse_outer_attributes()?;
1610 let lo = self.token.span;
1611 let pat = self.parse_top_pat(GateOr::No)?;
1612 let guard = if self.eat_keyword(kw::If) { Some(self.parse_expr()?) } else { None };
1613 let arrow_span = self.token.span;
1614 self.expect(&token::FatArrow)?;
1615 let arm_start_span = self.token.span;
1617 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| {
1618 err.span_label(arrow_span, "while parsing the `match` arm starting here");
1622 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
1623 && self.token != token::CloseDelim(token::Brace);
1625 let hi = self.token.span;
1628 let cm = self.sess.source_map();
1629 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]).map_err(
1631 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
1632 (Ok(ref expr_lines), Ok(ref arm_start_lines))
1633 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
1634 && expr_lines.lines.len() == 2
1635 && self.token == token::FatArrow =>
1637 // We check whether there's any trailing code in the parse span,
1638 // if there isn't, we very likely have the following:
1641 // | -- - missing comma
1645 // | - ^^ self.token.span
1647 // | parsed until here as `"y" & X`
1648 err.span_suggestion_short(
1649 cm.next_point(arm_start_span),
1650 "missing a comma here to end this `match` arm",
1652 Applicability::MachineApplicable,
1658 "while parsing the `match` arm starting here",
1666 self.eat(&token::Comma);
1676 is_placeholder: false,
1680 /// Parses a `try {...}` expression (`try` token already eaten).
1681 fn parse_try_block(&mut self, span_lo: Span, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1682 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1683 attrs.extend(iattrs);
1684 if self.eat_keyword(kw::Catch) {
1686 self.struct_span_err(self.prev_span, "keyword `catch` cannot follow a `try` block");
1687 error.help("try using `match` on the result of the `try` block instead");
1691 let span = span_lo.to(body.span);
1692 self.sess.gated_spans.gate(sym::try_blocks, span);
1693 Ok(self.mk_expr(span, ExprKind::TryBlock(body), attrs))
1697 fn is_do_catch_block(&self) -> bool {
1698 self.token.is_keyword(kw::Do)
1699 && self.is_keyword_ahead(1, &[kw::Catch])
1700 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
1701 && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1704 fn is_try_block(&self) -> bool {
1705 self.token.is_keyword(kw::Try) &&
1706 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
1707 self.token.span.rust_2018() &&
1708 // Prevent `while try {} {}`, `if try {} {} else {}`, etc.
1709 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1712 /// Parses an `async move? {...}` expression.
1713 fn parse_async_block(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1714 let lo = self.token.span;
1715 self.expect_keyword(kw::Async)?;
1716 let capture_clause = self.parse_capture_clause();
1717 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1718 attrs.extend(iattrs);
1719 let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);
1720 Ok(self.mk_expr(lo.to(self.prev_span), kind, attrs))
1723 fn is_async_block(&self) -> bool {
1724 self.token.is_keyword(kw::Async)
1727 self.is_keyword_ahead(1, &[kw::Move])
1728 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
1731 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
1735 fn is_certainly_not_a_block(&self) -> bool {
1736 self.look_ahead(1, |t| t.is_ident())
1738 // `{ ident, ` cannot start a block.
1739 self.look_ahead(2, |t| t == &token::Comma)
1740 || self.look_ahead(2, |t| t == &token::Colon)
1742 // `{ ident: token, ` cannot start a block.
1743 self.look_ahead(4, |t| t == &token::Comma) ||
1744 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
1745 self.look_ahead(3, |t| !t.can_begin_type())
1750 fn maybe_parse_struct_expr(
1755 ) -> Option<PResult<'a, P<Expr>>> {
1756 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
1757 if struct_allowed || self.is_certainly_not_a_block() {
1758 // This is a struct literal, but we don't can't accept them here.
1759 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
1760 if let (Ok(expr), false) = (&expr, struct_allowed) {
1761 self.error_struct_lit_not_allowed_here(lo, expr.span);
1768 fn error_struct_lit_not_allowed_here(&self, lo: Span, sp: Span) {
1769 self.struct_span_err(sp, "struct literals are not allowed here")
1770 .multipart_suggestion(
1771 "surround the struct literal with parentheses",
1772 vec![(lo.shrink_to_lo(), "(".to_string()), (sp.shrink_to_hi(), ")".to_string())],
1773 Applicability::MachineApplicable,
1778 pub(super) fn parse_struct_expr(
1783 ) -> PResult<'a, P<Expr>> {
1784 let struct_sp = lo.to(self.prev_span);
1786 let mut fields = Vec::new();
1787 let mut base = None;
1789 attrs.extend(self.parse_inner_attributes()?);
1791 while self.token != token::CloseDelim(token::Brace) {
1792 if self.eat(&token::DotDot) {
1793 let exp_span = self.prev_span;
1794 match self.parse_expr() {
1795 Ok(e) => base = Some(e),
1798 self.recover_stmt();
1801 self.recover_struct_comma_after_dotdot(exp_span);
1805 let recovery_field = self.find_struct_error_after_field_looking_code();
1806 let parsed_field = match self.parse_field() {
1809 e.span_label(struct_sp, "while parsing this struct");
1812 // If the next token is a comma, then try to parse
1813 // what comes next as additional fields, rather than
1814 // bailing out until next `}`.
1815 if self.token != token::Comma {
1816 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
1817 if self.token != token::Comma {
1825 match self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]) {
1827 if let Some(f) = parsed_field.or(recovery_field) {
1828 // Only include the field if there's no parse error for the field name.
1833 if let Some(f) = recovery_field {
1836 e.span_label(struct_sp, "while parsing this struct");
1838 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
1839 self.eat(&token::Comma);
1844 let span = lo.to(self.token.span);
1845 self.expect(&token::CloseDelim(token::Brace))?;
1846 Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs))
1849 /// Use in case of error after field-looking code: `S { foo: () with a }`.
1850 fn find_struct_error_after_field_looking_code(&self) -> Option<Field> {
1851 if let token::Ident(name, _) = self.token.kind {
1852 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
1853 let span = self.token.span;
1854 return Some(ast::Field {
1855 ident: Ident::new(name, span),
1857 expr: self.mk_expr_err(span),
1858 is_shorthand: false,
1859 attrs: AttrVec::new(),
1861 is_placeholder: false,
1868 fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
1869 if self.token != token::Comma {
1872 self.struct_span_err(span.to(self.prev_span), "cannot use a comma after the base struct")
1873 .span_suggestion_short(
1875 "remove this comma",
1877 Applicability::MachineApplicable,
1879 .note("the base struct must always be the last field")
1881 self.recover_stmt();
1884 /// Parses `ident (COLON expr)?`.
1885 fn parse_field(&mut self) -> PResult<'a, Field> {
1886 let attrs = self.parse_outer_attributes()?.into();
1887 let lo = self.token.span;
1889 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1890 let is_shorthand = !self.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
1891 let (ident, expr) = if is_shorthand {
1892 // Mimic `x: x` for the `x` field shorthand.
1893 let ident = self.parse_ident_common(false)?;
1894 let path = ast::Path::from_ident(ident);
1895 (ident, self.mk_expr(ident.span, ExprKind::Path(None, path), AttrVec::new()))
1897 let ident = self.parse_field_name()?;
1898 self.error_on_eq_field_init(ident);
1900 (ident, self.parse_expr()?)
1904 span: lo.to(expr.span),
1909 is_placeholder: false,
1913 /// Check for `=`. This means the source incorrectly attempts to
1914 /// initialize a field with an eq rather than a colon.
1915 fn error_on_eq_field_init(&self, field_name: Ident) {
1916 if self.token != token::Eq {
1920 self.struct_span_err(self.token.span, "expected `:`, found `=`")
1922 field_name.span.shrink_to_hi().to(self.token.span),
1923 "replace equals symbol with a colon",
1925 Applicability::MachineApplicable,
1930 fn err_dotdotdot_syntax(&self, span: Span) {
1931 self.struct_span_err(span, "unexpected token: `...`")
1934 "use `..` for an exclusive range",
1936 Applicability::MaybeIncorrect,
1940 "or `..=` for an inclusive range",
1942 Applicability::MaybeIncorrect,
1947 fn err_larrow_operator(&self, span: Span) {
1948 self.struct_span_err(span, "unexpected token: `<-`")
1951 "if you meant to write a comparison against a negative value, add a \
1952 space in between `<` and `-`",
1954 Applicability::MaybeIncorrect,
1959 fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
1960 ExprKind::AssignOp(binop, lhs, rhs)
1965 start: Option<P<Expr>>,
1966 end: Option<P<Expr>>,
1967 limits: RangeLimits,
1968 ) -> PResult<'a, ExprKind> {
1969 if end.is_none() && limits == RangeLimits::Closed {
1970 Err(self.span_fatal_err(self.token.span, Error::InclusiveRangeWithNoEnd))
1972 Ok(ExprKind::Range(start, end, limits))
1976 fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
1977 ExprKind::Unary(unop, expr)
1980 fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
1981 ExprKind::Binary(binop, lhs, rhs)
1984 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
1985 ExprKind::Index(expr, idx)
1988 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
1989 ExprKind::Call(f, args)
1992 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
1993 let span = lo.to(self.prev_span);
1994 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), AttrVec::new());
1995 self.recover_from_await_method_call();
1999 crate fn mk_expr(&self, span: Span, kind: ExprKind, attrs: AttrVec) -> P<Expr> {
2000 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID })
2003 pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
2004 self.mk_expr(span, ExprKind::Err, AttrVec::new())