1 use super::{Parser, PResult, Restrictions, PrevTokenKind, TokenType, PathStyle, BlockMode};
2 use super::{SemiColonMode, SeqSep, TokenExpectType};
3 use super::pat::{GateOr, PARAM_EXPECTED};
5 use crate::parse::literal::LitError;
8 self, DUMMY_NODE_ID, Attribute, AttrStyle, Ident, CaptureBy, BlockCheckMode,
9 Expr, ExprKind, RangeLimits, Label, Movability, IsAsync, Arm, Ty, TyKind,
10 FunctionRetTy, Param, FnDecl, BinOpKind, BinOp, UnOp, Mac, AnonConst, Field, Lit,
12 use crate::maybe_recover_from_interpolated_ty_qpath;
13 use crate::parse::classify;
14 use crate::parse::token::{self, Token, TokenKind};
15 use crate::parse::diagnostics::Error;
16 use crate::print::pprust;
18 use crate::source_map::{self, Span};
19 use crate::symbol::{kw, sym};
20 use crate::util::parser::{AssocOp, Fixity, prec_let_scrutinee_needs_par};
22 use errors::Applicability;
23 use syntax_pos::Symbol;
25 use rustc_data_structures::thin_vec::ThinVec;
27 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
28 /// dropped into the token stream, which happens while parsing the result of
29 /// macro expansion). Placement of these is not as complex as I feared it would
30 /// be. The important thing is to make sure that lookahead doesn't balk at
31 /// `token::Interpolated` tokens.
32 macro_rules! maybe_whole_expr {
34 if let token::Interpolated(nt) = &$p.token.kind {
36 token::NtExpr(e) | token::NtLiteral(e) => {
41 token::NtPath(path) => {
42 let path = path.clone();
45 $p.token.span, ExprKind::Path(None, path), ThinVec::new()
48 token::NtBlock(block) => {
49 let block = block.clone();
52 $p.token.span, ExprKind::Block(block, None), ThinVec::new()
55 // N.B., `NtIdent(ident)` is normalized to `Ident` in `fn bump`.
63 pub(super) enum LhsExpr {
65 AttributesParsed(ThinVec<Attribute>),
66 AlreadyParsed(P<Expr>),
69 impl From<Option<ThinVec<Attribute>>> 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<ThinVec<Attribute>>) -> Self {
75 if let Some(attrs) = o {
76 LhsExpr::AttributesParsed(attrs)
83 impl From<P<Expr>> for LhsExpr {
84 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
86 /// This conversion does not allocate.
87 fn from(expr: P<Expr>) -> Self {
88 LhsExpr::AlreadyParsed(expr)
93 /// Parses an expression.
95 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
96 self.parse_expr_res(Restrictions::empty(), None)
99 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
100 self.parse_paren_comma_seq(|p| {
101 match p.parse_expr() {
102 Ok(expr) => Ok(expr),
103 Err(mut err) => match p.token.kind {
104 token::Ident(name, false)
105 if name == kw::Underscore && p.look_ahead(1, |t| {
108 // Special-case handling of `foo(_, _, _)`
110 let sp = p.token.span;
112 Ok(p.mk_expr(sp, ExprKind::Err, ThinVec::new()))
120 /// Parses an expression, subject to the given restrictions.
122 pub(super) fn parse_expr_res(
125 already_parsed_attrs: Option<ThinVec<Attribute>>
126 ) -> PResult<'a, P<Expr>> {
127 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
130 /// Parses an associative expression.
132 /// This parses an expression accounting for associativity and precedence of the operators in
137 already_parsed_attrs: Option<ThinVec<Attribute>>,
138 ) -> PResult<'a, P<Expr>> {
139 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
142 /// Parses an associative expression with operators of at least `min_prec` precedence.
143 pub(super) fn parse_assoc_expr_with(
147 ) -> PResult<'a, P<Expr>> {
148 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
151 let attrs = match lhs {
152 LhsExpr::AttributesParsed(attrs) => Some(attrs),
155 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
156 return self.parse_prefix_range_expr(attrs);
158 self.parse_prefix_expr(attrs)?
161 let last_type_ascription_set = self.last_type_ascription.is_some();
163 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
165 self.last_type_ascription = None;
166 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
169 (false, _) => {} // continue parsing the expression
170 // An exhaustive check is done in the following block, but these are checked first
171 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
172 // want to keep their span info to improve diagnostics in these cases in a later stage.
173 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
174 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
175 (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475)
176 (true, Some(AssocOp::Add)) // `{ 42 } + 42
177 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
178 // `if x { a } else { b } && if y { c } else { d }`
179 if !self.look_ahead(1, |t| t.is_reserved_ident()) => {
180 self.last_type_ascription = None;
181 // These cases are ambiguous and can't be identified in the parser alone
182 let sp = self.sess.source_map().start_point(self.token.span);
183 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
186 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
187 self.last_type_ascription = None;
191 // We've found an expression that would be parsed as a statement, but the next
192 // token implies this should be parsed as an expression.
193 // For example: `if let Some(x) = x { x } else { 0 } / 2`
194 let mut err = self.struct_span_err(self.token.span, &format!(
195 "expected expression, found `{}`",
196 pprust::token_to_string(&self.token),
198 err.span_label(self.token.span, "expected expression");
199 self.sess.expr_parentheses_needed(
202 Some(pprust::expr_to_string(&lhs),
207 self.expected_tokens.push(TokenType::Operator);
208 while let Some(op) = AssocOp::from_token(&self.token) {
210 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
211 // it refers to. Interpolated identifiers are unwrapped early and never show up here
212 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
213 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
214 let lhs_span = match (self.prev_token_kind, &lhs.kind) {
215 (PrevTokenKind::Interpolated, _) => self.prev_span,
216 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
217 if path.segments.len() == 1 => self.prev_span,
221 let cur_op_span = self.token.span;
222 let restrictions = if op.is_assign_like() {
223 self.restrictions & Restrictions::NO_STRUCT_LITERAL
227 let prec = op.precedence();
231 // Check for deprecated `...` syntax
232 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
233 self.err_dotdotdot_syntax(self.token.span);
236 if self.token == token::LArrow {
237 self.err_larrow_operator(self.token.span);
241 if op.is_comparison() {
242 if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
247 if op == AssocOp::As {
248 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
250 } else if op == AssocOp::Colon {
251 let maybe_path = self.could_ascription_be_path(&lhs.kind);
252 self.last_type_ascription = Some((self.prev_span, maybe_path));
254 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
256 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
257 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
258 // generalise it to the Fixity::None code.
260 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
261 // two variants are handled with `parse_prefix_range_expr` call above.
262 let rhs = if self.is_at_start_of_range_notation_rhs() {
263 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
267 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
272 let limits = if op == AssocOp::DotDot {
273 RangeLimits::HalfOpen
278 let r = self.mk_range(Some(lhs), rhs, limits)?;
279 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
283 let fixity = op.fixity();
284 let prec_adjustment = match fixity {
287 // We currently have no non-associative operators that are not handled above by
288 // the special cases. The code is here only for future convenience.
291 let rhs = self.with_res(
292 restrictions - Restrictions::STMT_EXPR,
293 |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
296 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
297 // including the attributes.
301 .filter(|a| a.style == AttrStyle::Outer)
303 .map_or(lhs_span, |a| a.span);
304 let span = lhs_span.to(rhs.span);
306 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
307 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
308 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
309 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
310 AssocOp::Greater | AssocOp::GreaterEqual => {
311 let ast_op = op.to_ast_binop().unwrap();
312 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
313 self.mk_expr(span, binary, ThinVec::new())
315 AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
316 AssocOp::AssignOp(k) => {
318 token::Plus => BinOpKind::Add,
319 token::Minus => BinOpKind::Sub,
320 token::Star => BinOpKind::Mul,
321 token::Slash => BinOpKind::Div,
322 token::Percent => BinOpKind::Rem,
323 token::Caret => BinOpKind::BitXor,
324 token::And => BinOpKind::BitAnd,
325 token::Or => BinOpKind::BitOr,
326 token::Shl => BinOpKind::Shl,
327 token::Shr => BinOpKind::Shr,
329 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
330 self.mk_expr(span, aopexpr, ThinVec::new())
332 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
333 self.bug("AssocOp should have been handled by special case")
337 if let Fixity::None = fixity { break }
339 if last_type_ascription_set {
340 self.last_type_ascription = None;
345 /// Checks if this expression is a successfully parsed statement.
346 fn expr_is_complete(&self, e: &Expr) -> bool {
347 self.restrictions.contains(Restrictions::STMT_EXPR) &&
348 !classify::expr_requires_semi_to_be_stmt(e)
351 fn is_at_start_of_range_notation_rhs(&self) -> bool {
352 if self.token.can_begin_expr() {
353 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
354 if self.token == token::OpenDelim(token::Brace) {
355 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
363 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
364 fn parse_prefix_range_expr(
366 already_parsed_attrs: Option<ThinVec<Attribute>>
367 ) -> PResult<'a, P<Expr>> {
368 // Check for deprecated `...` syntax.
369 if self.token == token::DotDotDot {
370 self.err_dotdotdot_syntax(self.token.span);
373 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
374 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
376 let tok = self.token.clone();
377 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
378 let lo = self.token.span;
379 let mut hi = self.token.span;
381 let opt_end = if self.is_at_start_of_range_notation_rhs() {
382 // RHS must be parsed with more associativity than the dots.
383 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
384 Some(self.parse_assoc_expr_with(next_prec, LhsExpr::NotYetParsed)
392 let limits = if tok == token::DotDot {
393 RangeLimits::HalfOpen
398 let r = self.mk_range(None, opt_end, limits)?;
399 Ok(self.mk_expr(lo.to(hi), r, attrs))
402 /// Parses a prefix-unary-operator expr.
403 fn parse_prefix_expr(
405 already_parsed_attrs: Option<ThinVec<Attribute>>
406 ) -> PResult<'a, P<Expr>> {
407 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
408 let lo = self.token.span;
409 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
410 let (hi, ex) = match self.token.kind {
413 let e = self.parse_prefix_expr(None);
414 let (span, e) = self.interpolated_or_expr_span(e)?;
415 (lo.to(span), self.mk_unary(UnOp::Not, e))
417 // Suggest `!` for bitwise negation when encountering a `~`
420 let e = self.parse_prefix_expr(None);
421 let (span, e) = self.interpolated_or_expr_span(e)?;
422 let span_of_tilde = lo;
423 self.struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator")
424 .span_suggestion_short(
426 "use `!` to perform bitwise negation",
428 Applicability::MachineApplicable
431 (lo.to(span), self.mk_unary(UnOp::Not, e))
433 token::BinOp(token::Minus) => {
435 let e = self.parse_prefix_expr(None);
436 let (span, e) = self.interpolated_or_expr_span(e)?;
437 (lo.to(span), self.mk_unary(UnOp::Neg, e))
439 token::BinOp(token::Star) => {
441 let e = self.parse_prefix_expr(None);
442 let (span, e) = self.interpolated_or_expr_span(e)?;
443 (lo.to(span), self.mk_unary(UnOp::Deref, e))
445 token::BinOp(token::And) | token::AndAnd => {
447 let m = self.parse_mutability();
448 let e = self.parse_prefix_expr(None);
449 let (span, e) = self.interpolated_or_expr_span(e)?;
450 (lo.to(span), ExprKind::AddrOf(m, e))
452 token::Ident(..) if self.token.is_keyword(kw::Box) => {
454 let e = self.parse_prefix_expr(None);
455 let (span, e) = self.interpolated_or_expr_span(e)?;
456 (lo.to(span), ExprKind::Box(e))
458 token::Ident(..) if self.token.is_ident_named(sym::not) => {
459 // `not` is just an ordinary identifier in Rust-the-language,
460 // but as `rustc`-the-compiler, we can issue clever diagnostics
461 // for confused users who really want to say `!`
462 let token_cannot_continue_expr = |t: &Token| match t.kind {
463 // These tokens can start an expression after `!`, but
464 // can't continue an expression after an ident
465 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
466 token::Literal(..) | token::Pound => true,
467 _ => t.is_whole_expr(),
469 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
470 if cannot_continue_expr {
472 // Emit the error ...
473 self.struct_span_err(
475 &format!("unexpected {} after identifier",self.this_token_descr())
477 .span_suggestion_short(
478 // Span the `not` plus trailing whitespace to avoid
479 // trailing whitespace after the `!` in our suggestion
480 self.sess.source_map()
481 .span_until_non_whitespace(lo.to(self.token.span)),
482 "use `!` to perform logical negation",
484 Applicability::MachineApplicable
487 // —and recover! (just as if we were in the block
488 // for the `token::Not` arm)
489 let e = self.parse_prefix_expr(None);
490 let (span, e) = self.interpolated_or_expr_span(e)?;
491 (lo.to(span), self.mk_unary(UnOp::Not, e))
493 return self.parse_dot_or_call_expr(Some(attrs));
496 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
498 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
501 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
502 fn interpolated_or_expr_span(
504 expr: PResult<'a, P<Expr>>,
505 ) -> PResult<'a, (Span, P<Expr>)> {
507 if self.prev_token_kind == PrevTokenKind::Interpolated {
515 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
516 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
517 -> PResult<'a, P<Expr>> {
518 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
519 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
522 // Save the state of the parser before parsing type normally, in case there is a
523 // LessThan comparison after this cast.
524 let parser_snapshot_before_type = self.clone();
525 match self.parse_ty_no_plus() {
527 Ok(mk_expr(self, rhs))
529 Err(mut type_err) => {
530 // Rewind to before attempting to parse the type with generics, to recover
531 // from situations like `x as usize < y` in which we first tried to parse
532 // `usize < y` as a type with generic arguments.
533 let parser_snapshot_after_type = self.clone();
534 mem::replace(self, parser_snapshot_before_type);
536 match self.parse_path(PathStyle::Expr) {
538 let (op_noun, op_verb) = match self.token.kind {
539 token::Lt => ("comparison", "comparing"),
540 token::BinOp(token::Shl) => ("shift", "shifting"),
542 // We can end up here even without `<` being the next token, for
543 // example because `parse_ty_no_plus` returns `Err` on keywords,
544 // but `parse_path` returns `Ok` on them due to error recovery.
545 // Return original error and parser state.
546 mem::replace(self, parser_snapshot_after_type);
547 return Err(type_err);
551 // Successfully parsed the type path leaving a `<` yet to parse.
554 // Report non-fatal diagnostics, keep `x as usize` as an expression
555 // in AST and continue parsing.
557 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
558 pprust::path_to_string(&path),
561 let span_after_type = parser_snapshot_after_type.token.span;
562 let expr = mk_expr(self, P(Ty {
564 kind: TyKind::Path(None, path),
568 let expr_str = self.span_to_snippet(expr.span)
569 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
571 self.struct_span_err(self.token.span, &msg)
573 self.look_ahead(1, |t| t.span).to(span_after_type),
574 "interpreted as generic arguments"
576 .span_label(self.token.span, format!("not interpreted as {}", op_noun))
579 &format!("try {} the cast value", op_verb),
580 format!("({})", expr_str),
581 Applicability::MachineApplicable,
587 Err(mut path_err) => {
588 // Couldn't parse as a path, return original error and parser state.
590 mem::replace(self, parser_snapshot_after_type);
598 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
599 fn parse_dot_or_call_expr(
601 already_parsed_attrs: Option<ThinVec<Attribute>>,
602 ) -> PResult<'a, P<Expr>> {
603 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
605 let b = self.parse_bottom_expr();
606 let (span, b) = self.interpolated_or_expr_span(b)?;
607 self.parse_dot_or_call_expr_with(b, span, attrs)
610 pub(super) fn parse_dot_or_call_expr_with(
614 mut attrs: ThinVec<Attribute>,
615 ) -> PResult<'a, P<Expr>> {
616 // Stitch the list of outer attributes onto the return value.
617 // A little bit ugly, but the best way given the current code
619 self.parse_dot_or_call_expr_with_(e0, lo).map(|expr|
620 expr.map(|mut expr| {
621 attrs.extend::<Vec<_>>(expr.attrs.into());
624 ExprKind::If(..) if !expr.attrs.is_empty() => {
625 // Just point to the first attribute in there...
626 let span = expr.attrs[0].span;
627 self.span_err(span, "attributes are not yet allowed on `if` expressions");
636 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
641 while self.eat(&token::Question) {
642 let hi = self.prev_span;
643 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
647 if self.eat(&token::Dot) {
648 match self.token.kind {
649 token::Ident(..) => {
650 e = self.parse_dot_suffix(e, lo)?;
652 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
653 let span = self.token.span;
655 let field = ExprKind::Field(e, Ident::new(symbol, span));
656 e = self.mk_expr(lo.to(span), field, ThinVec::new());
658 self.expect_no_suffix(span, "a tuple index", suffix);
660 token::Literal(token::Lit { kind: token::Float, symbol, .. }) => {
662 let fstr = symbol.as_str();
663 let msg = format!("unexpected token: `{}`", symbol);
664 let mut err = self.diagnostic().struct_span_err(self.prev_span, &msg);
665 err.span_label(self.prev_span, "unexpected token");
666 if fstr.chars().all(|x| "0123456789.".contains(x)) {
667 let float = match fstr.parse::<f64>().ok() {
671 let sugg = pprust::to_string(|s| {
675 s.print_usize(float.trunc() as usize);
678 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
681 lo.to(self.prev_span),
682 "try parenthesizing the first index",
684 Applicability::MachineApplicable
691 // FIXME Could factor this out into non_fatal_unexpected or something.
692 let actual = self.this_token_to_string();
693 self.span_err(self.token.span, &format!("unexpected token: `{}`", actual));
698 if self.expr_is_complete(&e) { break; }
699 match self.token.kind {
701 token::OpenDelim(token::Paren) => {
702 let seq = self.parse_paren_expr_seq().map(|es| {
703 let nd = self.mk_call(e, es);
704 let hi = self.prev_span;
705 self.mk_expr(lo.to(hi), nd, ThinVec::new())
707 e = self.recover_seq_parse_error(token::Paren, lo, seq);
711 // Could be either an index expression or a slicing expression.
712 token::OpenDelim(token::Bracket) => {
714 let ix = self.parse_expr()?;
715 hi = self.token.span;
716 self.expect(&token::CloseDelim(token::Bracket))?;
717 let index = self.mk_index(e, ix);
718 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
726 /// Assuming we have just parsed `.`, continue parsing into an expression.
727 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
728 if self.token.span.rust_2018() && self.eat_keyword(kw::Await) {
729 return self.mk_await_expr(self_arg, lo);
732 let segment = self.parse_path_segment(PathStyle::Expr)?;
733 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
735 Ok(match self.token.kind {
736 token::OpenDelim(token::Paren) => {
737 // Method call `expr.f()`
738 let mut args = self.parse_paren_expr_seq()?;
739 args.insert(0, self_arg);
741 let span = lo.to(self.prev_span);
742 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
745 // Field access `expr.f`
746 if let Some(args) = segment.args {
747 self.span_err(args.span(),
748 "field expressions may not have generic arguments");
751 let span = lo.to(self.prev_span);
752 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
757 /// At the bottom (top?) of the precedence hierarchy,
758 /// Parses things like parenthesized exprs, macros, `return`, etc.
760 /// N.B., this does not parse outer attributes, and is private because it only works
761 /// correctly if called from `parse_dot_or_call_expr()`.
762 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
763 maybe_recover_from_interpolated_ty_qpath!(self, true);
764 maybe_whole_expr!(self);
766 // Outer attributes are already parsed and will be
767 // added to the return value after the fact.
769 // Therefore, prevent sub-parser from parsing
770 // attributes by giving them a empty "already-parsed" list.
771 let mut attrs = ThinVec::new();
773 let lo = self.token.span;
774 let mut hi = self.token.span;
778 macro_rules! parse_lit {
780 match self.parse_lit() {
783 ex = ExprKind::Lit(literal);
787 return Err(self.expected_expression_found());
793 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
794 match self.token.kind {
795 // This match arm is a special-case of the `_` match arm below and
796 // could be removed without changing functionality, but it's faster
797 // to have it here, especially for programs with large constants.
798 token::Literal(_) => {
801 token::OpenDelim(token::Paren) => {
804 attrs.extend(self.parse_inner_attributes()?);
806 // `(e)` is parenthesized `e`.
807 // `(e,)` is a tuple with only one field, `e`.
809 let mut trailing_comma = false;
810 let mut recovered = false;
811 while self.token != token::CloseDelim(token::Paren) {
812 es.push(match self.parse_expr() {
815 // Recover from parse error in tuple list.
816 match self.token.kind {
817 token::Ident(name, false)
818 if name == kw::Underscore && self.look_ahead(1, |t| {
821 // Special-case handling of `Foo<(_, _, _)>`
823 let sp = self.token.span;
825 self.mk_expr(sp, ExprKind::Err, ThinVec::new())
828 self.recover_seq_parse_error(token::Paren, lo, Err(err)),
833 recovered = self.expect_one_of(
835 &[token::Comma, token::CloseDelim(token::Paren)],
837 if self.eat(&token::Comma) {
838 trailing_comma = true;
840 trailing_comma = false;
849 ex = if es.len() == 1 && !trailing_comma {
850 ExprKind::Paren(es.into_iter().nth(0).unwrap())
855 token::OpenDelim(token::Brace) => {
856 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
858 token::BinOp(token::Or) | token::OrOr => {
859 return self.parse_closure_expr(attrs);
861 token::OpenDelim(token::Bracket) => {
864 attrs.extend(self.parse_inner_attributes()?);
866 if self.eat(&token::CloseDelim(token::Bracket)) {
868 ex = ExprKind::Array(Vec::new());
871 let first_expr = self.parse_expr()?;
872 if self.eat(&token::Semi) {
873 // Repeating array syntax: `[ 0; 512 ]`
874 let count = AnonConst {
876 value: self.parse_expr()?,
878 self.expect(&token::CloseDelim(token::Bracket))?;
879 ex = ExprKind::Repeat(first_expr, count);
880 } else if self.eat(&token::Comma) {
881 // Vector with two or more elements
882 let remaining_exprs = self.parse_seq_to_end(
883 &token::CloseDelim(token::Bracket),
884 SeqSep::trailing_allowed(token::Comma),
885 |p| Ok(p.parse_expr()?)
887 let mut exprs = vec![first_expr];
888 exprs.extend(remaining_exprs);
889 ex = ExprKind::Array(exprs);
891 // Vector with one element
892 self.expect(&token::CloseDelim(token::Bracket))?;
893 ex = ExprKind::Array(vec![first_expr]);
900 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
902 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
904 if self.token.is_path_start() {
905 let path = self.parse_path(PathStyle::Expr)?;
907 // `!`, as an operator, is prefix, so we know this isn't that.
908 if self.eat(&token::Not) {
909 // MACRO INVOCATION expression
910 let (delim, tts) = self.expect_delimited_token_tree()?;
912 ex = ExprKind::Mac(Mac {
917 prior_type_ascription: self.last_type_ascription,
919 } else if self.check(&token::OpenDelim(token::Brace)) {
920 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
924 ex = ExprKind::Path(None, path);
928 ex = ExprKind::Path(None, path);
931 let expr = self.mk_expr(lo.to(hi), ex, attrs);
932 return self.maybe_recover_from_bad_qpath(expr, true);
934 if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
935 return self.parse_closure_expr(attrs);
937 if self.eat_keyword(kw::If) {
938 return self.parse_if_expr(attrs);
940 if self.eat_keyword(kw::For) {
941 let lo = self.prev_span;
942 return self.parse_for_expr(None, lo, attrs);
944 if self.eat_keyword(kw::While) {
945 let lo = self.prev_span;
946 return self.parse_while_expr(None, lo, attrs);
948 if let Some(label) = self.eat_label() {
949 let lo = label.ident.span;
950 self.expect(&token::Colon)?;
951 if self.eat_keyword(kw::While) {
952 return self.parse_while_expr(Some(label), lo, attrs)
954 if self.eat_keyword(kw::For) {
955 return self.parse_for_expr(Some(label), lo, attrs)
957 if self.eat_keyword(kw::Loop) {
958 return self.parse_loop_expr(Some(label), lo, attrs)
960 if self.token == token::OpenDelim(token::Brace) {
961 return self.parse_block_expr(Some(label),
963 BlockCheckMode::Default,
966 let msg = "expected `while`, `for`, `loop` or `{` after a label";
967 let mut err = self.fatal(msg);
968 err.span_label(self.token.span, msg);
971 if self.eat_keyword(kw::Loop) {
972 let lo = self.prev_span;
973 return self.parse_loop_expr(None, lo, attrs);
975 if self.eat_keyword(kw::Continue) {
976 let label = self.eat_label();
977 let ex = ExprKind::Continue(label);
978 let hi = self.prev_span;
979 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
981 if self.eat_keyword(kw::Match) {
982 let match_sp = self.prev_span;
983 return self.parse_match_expr(attrs).map_err(|mut err| {
984 err.span_label(match_sp, "while parsing this match expression");
988 if self.eat_keyword(kw::Unsafe) {
989 return self.parse_block_expr(
992 BlockCheckMode::Unsafe(ast::UserProvided),
995 if self.is_do_catch_block() {
996 let mut db = self.fatal("found removed `do catch` syntax");
997 db.help("following RFC #2388, the new non-placeholder syntax is `try`");
1000 if self.is_try_block() {
1001 let lo = self.token.span;
1002 assert!(self.eat_keyword(kw::Try));
1003 return self.parse_try_block(lo, attrs);
1006 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1007 let is_span_rust_2018 = self.token.span.rust_2018();
1008 if is_span_rust_2018 && self.check_keyword(kw::Async) {
1009 return if self.is_async_block() { // Check for `async {` and `async move {`.
1010 self.parse_async_block(attrs)
1012 self.parse_closure_expr(attrs)
1015 if self.eat_keyword(kw::Return) {
1016 if self.token.can_begin_expr() {
1017 let e = self.parse_expr()?;
1019 ex = ExprKind::Ret(Some(e));
1021 ex = ExprKind::Ret(None);
1023 } else if self.eat_keyword(kw::Break) {
1024 let label = self.eat_label();
1025 let e = if self.token.can_begin_expr()
1026 && !(self.token == token::OpenDelim(token::Brace)
1027 && self.restrictions.contains(
1028 Restrictions::NO_STRUCT_LITERAL)) {
1029 Some(self.parse_expr()?)
1033 ex = ExprKind::Break(label, e);
1034 hi = self.prev_span;
1035 } else if self.eat_keyword(kw::Yield) {
1036 if self.token.can_begin_expr() {
1037 let e = self.parse_expr()?;
1039 ex = ExprKind::Yield(Some(e));
1041 ex = ExprKind::Yield(None);
1044 let span = lo.to(hi);
1045 self.sess.gated_spans.yields.borrow_mut().push(span);
1046 } else if self.eat_keyword(kw::Let) {
1047 return self.parse_let_expr(attrs);
1048 } else if is_span_rust_2018 && self.eat_keyword(kw::Await) {
1049 let (await_hi, e_kind) = self.parse_incorrect_await_syntax(lo, self.prev_span)?;
1053 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1054 // Don't complain about bare semicolons after unclosed braces
1055 // recovery in order to keep the error count down. Fixing the
1056 // delimiters will possibly also fix the bare semicolon found in
1057 // expression context. For example, silence the following error:
1059 // error: expected expression, found `;`
1063 // | ^ expected expression
1065 return Ok(self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()));
1072 let expr = self.mk_expr(lo.to(hi), ex, attrs);
1073 self.maybe_recover_from_bad_qpath(expr, true)
1076 /// Matches `lit = true | false | token_lit`.
1077 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1078 let mut recovered = None;
1079 if self.token == token::Dot {
1080 // Attempt to recover `.4` as `0.4`.
1081 recovered = self.look_ahead(1, |next_token| {
1082 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix })
1084 if self.token.span.hi() == next_token.span.lo() {
1085 let s = String::from("0.") + &symbol.as_str();
1086 let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1087 return Some(Token::new(kind, self.token.span.to(next_token.span)));
1092 if let Some(token) = &recovered {
1094 self.struct_span_err(token.span, "float literals must have an integer part")
1097 "must have an integer part",
1098 pprust::token_to_string(token),
1099 Applicability::MachineApplicable,
1105 let token = recovered.as_ref().unwrap_or(&self.token);
1106 match Lit::from_token(token) {
1111 Err(LitError::NotLiteral) => {
1112 let msg = format!("unexpected token: {}", self.this_token_descr());
1113 Err(self.span_fatal(token.span, &msg))
1116 let (lit, span) = (token.expect_lit(), token.span);
1118 self.error_literal_from_token(err, lit, span);
1119 // Pack possible quotes and prefixes from the original literal into
1120 // the error literal's symbol so they can be pretty-printed faithfully.
1121 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1122 let symbol = Symbol::intern(&suffixless_lit.to_string());
1123 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1124 Lit::from_lit_token(lit, span).map_err(|_| unreachable!())
1129 fn error_literal_from_token(&self, err: LitError, lit: token::Lit, span: Span) {
1130 // Checks if `s` looks like i32 or u1234 etc.
1131 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1133 && s.starts_with(first_chars)
1134 && s[1..].chars().all(|c| c.is_ascii_digit())
1137 let token::Lit { kind, suffix, .. } = lit;
1139 // `NotLiteral` is not an error by itself, so we don't report
1140 // it and give the parser opportunity to try something else.
1141 LitError::NotLiteral => {}
1142 // `LexerError` *is* an error, but it was already reported
1143 // by lexer, so here we don't report it the second time.
1144 LitError::LexerError => {}
1145 LitError::InvalidSuffix => {
1146 self.expect_no_suffix(
1148 &format!("{} {} literal", kind.article(), kind.descr()),
1152 LitError::InvalidIntSuffix => {
1153 let suf = suffix.expect("suffix error with no suffix").as_str();
1154 if looks_like_width_suffix(&['i', 'u'], &suf) {
1155 // If it looks like a width, try to be helpful.
1156 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
1157 self.struct_span_err(span, &msg)
1158 .help("valid widths are 8, 16, 32, 64 and 128")
1161 let msg = format!("invalid suffix `{}` for integer literal", suf);
1162 self.struct_span_err(span, &msg)
1163 .span_label(span, format!("invalid suffix `{}`", suf))
1164 .help("the suffix must be one of the integral types (`u32`, `isize`, etc)")
1168 LitError::InvalidFloatSuffix => {
1169 let suf = suffix.expect("suffix error with no suffix").as_str();
1170 if looks_like_width_suffix(&['f'], &suf) {
1171 // If it looks like a width, try to be helpful.
1172 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
1173 self.struct_span_err(span, &msg)
1174 .help("valid widths are 32 and 64")
1177 let msg = format!("invalid suffix `{}` for float literal", suf);
1178 self.struct_span_err(span, &msg)
1179 .span_label(span, format!("invalid suffix `{}`", suf))
1180 .help("valid suffixes are `f32` and `f64`")
1184 LitError::NonDecimalFloat(base) => {
1185 let descr = match base {
1186 16 => "hexadecimal",
1189 _ => unreachable!(),
1191 self.struct_span_err(span, &format!("{} float literal is not supported", descr))
1192 .span_label(span, "not supported")
1195 LitError::IntTooLarge => {
1196 self.struct_span_err(span, "integer literal is too large")
1202 pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) {
1203 if let Some(suf) = suffix {
1204 let mut err = if kind == "a tuple index"
1205 && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf)
1207 // #59553: warn instead of reject out of hand to allow the fix to percolate
1208 // through the ecosystem when people fix their macros
1209 let mut err = self.sess.span_diagnostic.struct_span_warn(
1211 &format!("suffixes on {} are invalid", kind),
1214 "`{}` is *temporarily* accepted on tuple index fields as it was \
1215 incorrectly accepted on stable for a few releases",
1219 "on proc macros, you'll want to use `syn::Index::from` or \
1220 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1221 to tuple field access",
1224 "for more context, see https://github.com/rust-lang/rust/issues/60210",
1228 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1230 err.span_label(sp, format!("invalid suffix `{}`", suf));
1235 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1236 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1237 maybe_whole_expr!(self);
1239 let minus_lo = self.token.span;
1240 let minus_present = self.eat(&token::BinOp(token::Minus));
1241 let lo = self.token.span;
1242 let literal = self.parse_lit()?;
1243 let hi = self.prev_span;
1244 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1247 let minus_hi = self.prev_span;
1248 let unary = self.mk_unary(UnOp::Neg, expr);
1249 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1255 /// Parses a block or unsafe block.
1256 crate fn parse_block_expr(
1258 opt_label: Option<Label>,
1260 blk_mode: BlockCheckMode,
1261 outer_attrs: ThinVec<Attribute>,
1262 ) -> PResult<'a, P<Expr>> {
1263 self.expect(&token::OpenDelim(token::Brace))?;
1265 let mut attrs = outer_attrs;
1266 attrs.extend(self.parse_inner_attributes()?);
1268 let blk = self.parse_block_tail(lo, blk_mode)?;
1269 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs))
1272 /// Parses a closure expression (e.g., `move |args| expr`).
1273 fn parse_closure_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1274 let lo = self.token.span;
1276 let movability = if self.eat_keyword(kw::Static) {
1282 let asyncness = if self.token.span.rust_2018() {
1283 self.parse_asyncness()
1287 if asyncness.is_async() {
1288 // Feature-gate `async ||` closures.
1289 self.sess.gated_spans.async_closure.borrow_mut().push(self.prev_span);
1292 let capture_clause = self.parse_capture_clause();
1293 let decl = self.parse_fn_block_decl()?;
1294 let decl_hi = self.prev_span;
1295 let body = match decl.output {
1296 FunctionRetTy::Default(_) => {
1297 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
1298 self.parse_expr_res(restrictions, None)?
1301 // If an explicit return type is given, require a block to appear (RFC 968).
1302 let body_lo = self.token.span;
1303 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
1309 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
1313 /// Parses an optional `move` prefix to a closure lke construct.
1314 fn parse_capture_clause(&mut self) -> CaptureBy {
1315 if self.eat_keyword(kw::Move) {
1322 /// Parses the `|arg, arg|` header of a closure.
1323 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
1324 let inputs_captures = {
1325 if self.eat(&token::OrOr) {
1328 self.expect(&token::BinOp(token::Or))?;
1329 let args = self.parse_seq_to_before_tokens(
1330 &[&token::BinOp(token::Or), &token::OrOr],
1331 SeqSep::trailing_allowed(token::Comma),
1332 TokenExpectType::NoExpect,
1333 |p| p.parse_fn_block_param()
1339 let output = self.parse_ret_ty(true)?;
1342 inputs: inputs_captures,
1347 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1348 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
1349 let lo = self.token.span;
1350 let attrs = self.parse_outer_attributes()?;
1351 let pat = self.parse_pat(PARAM_EXPECTED)?;
1352 let t = if self.eat(&token::Colon) {
1357 kind: TyKind::Infer,
1358 span: self.prev_span,
1361 let span = lo.to(self.token.span);
1363 attrs: attrs.into(),
1368 is_placeholder: false,
1372 /// Parses an `if` expression (`if` token already eaten).
1373 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1374 let lo = self.prev_span;
1375 let cond = self.parse_cond_expr()?;
1377 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1378 // verify that the last statement is either an implicit return (no `;`) or an explicit
1379 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1380 // the dead code lint.
1381 if self.eat_keyword(kw::Else) || !cond.returns() {
1382 let sp = self.sess.source_map().next_point(lo);
1383 let mut err = self.diagnostic()
1384 .struct_span_err(sp, "missing condition for `if` expression");
1385 err.span_label(sp, "expected if condition here");
1388 let not_block = self.token != token::OpenDelim(token::Brace);
1389 let thn = self.parse_block().map_err(|mut err| {
1391 err.span_label(lo, "this `if` statement has a condition, but no block");
1395 let mut els: Option<P<Expr>> = None;
1396 let mut hi = thn.span;
1397 if self.eat_keyword(kw::Else) {
1398 let elexpr = self.parse_else_expr()?;
1402 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
1405 /// Parses the condition of a `if` or `while` expression.
1406 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
1407 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1409 if let ExprKind::Let(..) = cond.kind {
1410 // Remove the last feature gating of a `let` expression since it's stable.
1411 let last = self.sess.gated_spans.let_chains.borrow_mut().pop();
1412 debug_assert_eq!(cond.span, last.unwrap());
1418 /// Parses a `let $pat = $expr` pseudo-expression.
1419 /// The `let` token has already been eaten.
1420 fn parse_let_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1421 let lo = self.prev_span;
1422 let pat = self.parse_top_pat(GateOr::No)?;
1423 self.expect(&token::Eq)?;
1424 let expr = self.with_res(
1425 Restrictions::NO_STRUCT_LITERAL,
1426 |this| this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
1428 let span = lo.to(expr.span);
1429 self.sess.gated_spans.let_chains.borrow_mut().push(span);
1430 Ok(self.mk_expr(span, ExprKind::Let(pat, expr), attrs))
1433 /// Parses an `else { ... }` expression (`else` token already eaten).
1434 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
1435 if self.eat_keyword(kw::If) {
1436 return self.parse_if_expr(ThinVec::new());
1438 let blk = self.parse_block()?;
1439 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
1443 /// Parses a `for ... in` expression (`for` token already eaten).
1446 opt_label: Option<Label>,
1448 mut attrs: ThinVec<Attribute>
1449 ) -> PResult<'a, P<Expr>> {
1450 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
1452 // Record whether we are about to parse `for (`.
1453 // This is used below for recovery in case of `for ( $stuff ) $block`
1454 // in which case we will suggest `for $stuff $block`.
1455 let begin_paren = match self.token.kind {
1456 token::OpenDelim(token::Paren) => Some(self.token.span),
1460 let pat = self.parse_top_pat(GateOr::Yes)?;
1461 if !self.eat_keyword(kw::In) {
1462 let in_span = self.prev_span.between(self.token.span);
1463 self.struct_span_err(in_span, "missing `in` in `for` loop")
1464 .span_suggestion_short(
1466 "try adding `in` here", " in ".into(),
1467 // has been misleading, at least in the past (closed Issue #48492)
1468 Applicability::MaybeIncorrect
1472 let in_span = self.prev_span;
1473 self.check_for_for_in_in_typo(in_span);
1474 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1476 let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
1478 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
1479 attrs.extend(iattrs);
1481 let hi = self.prev_span;
1482 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
1485 /// Parses a `while` or `while let` expression (`while` token already eaten).
1486 fn parse_while_expr(
1488 opt_label: Option<Label>,
1490 mut attrs: ThinVec<Attribute>
1491 ) -> PResult<'a, P<Expr>> {
1492 let cond = self.parse_cond_expr()?;
1493 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1494 attrs.extend(iattrs);
1495 let span = span_lo.to(body.span);
1496 Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs))
1499 /// Parses `loop { ... }` (`loop` token already eaten).
1502 opt_label: Option<Label>,
1504 mut attrs: ThinVec<Attribute>
1505 ) -> PResult<'a, P<Expr>> {
1506 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1507 attrs.extend(iattrs);
1508 let span = span_lo.to(body.span);
1509 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
1512 fn eat_label(&mut self) -> Option<Label> {
1513 if let Some(ident) = self.token.lifetime() {
1514 let span = self.token.span;
1516 Some(Label { ident: Ident::new(ident.name, span) })
1522 /// Parses a `match ... { ... }` expression (`match` token already eaten).
1523 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1524 let match_span = self.prev_span;
1525 let lo = self.prev_span;
1526 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1527 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
1528 if self.token == token::Semi {
1529 e.span_suggestion_short(
1531 "try removing this `match`",
1533 Applicability::MaybeIncorrect // speculative
1538 attrs.extend(self.parse_inner_attributes()?);
1540 let mut arms: Vec<Arm> = Vec::new();
1541 while self.token != token::CloseDelim(token::Brace) {
1542 match self.parse_arm() {
1543 Ok(arm) => arms.push(arm),
1545 // Recover by skipping to the end of the block.
1547 self.recover_stmt();
1548 let span = lo.to(self.token.span);
1549 if self.token == token::CloseDelim(token::Brace) {
1552 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
1556 let hi = self.token.span;
1558 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
1561 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
1562 let attrs = self.parse_outer_attributes()?;
1563 let lo = self.token.span;
1564 let pat = self.parse_top_pat(GateOr::No)?;
1565 let guard = if self.eat_keyword(kw::If) {
1566 Some(self.parse_expr()?)
1570 let arrow_span = self.token.span;
1571 self.expect(&token::FatArrow)?;
1572 let arm_start_span = self.token.span;
1574 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
1575 .map_err(|mut err| {
1576 err.span_label(arrow_span, "while parsing the `match` arm starting here");
1580 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
1581 && self.token != token::CloseDelim(token::Brace);
1583 let hi = self.token.span;
1586 let cm = self.sess.source_map();
1587 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
1588 .map_err(|mut err| {
1589 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
1590 (Ok(ref expr_lines), Ok(ref arm_start_lines))
1591 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
1592 && expr_lines.lines.len() == 2
1593 && self.token == token::FatArrow => {
1594 // We check whether there's any trailing code in the parse span,
1595 // if there isn't, we very likely have the following:
1598 // | -- - missing comma
1602 // | - ^^ self.token.span
1604 // | parsed until here as `"y" & X`
1605 err.span_suggestion_short(
1606 cm.next_point(arm_start_span),
1607 "missing a comma here to end this `match` arm",
1609 Applicability::MachineApplicable
1613 err.span_label(arrow_span,
1614 "while parsing the `match` arm starting here");
1620 self.eat(&token::Comma);
1630 is_placeholder: false,
1634 /// Parses a `try {...}` expression (`try` token already eaten).
1638 mut attrs: ThinVec<Attribute>
1639 ) -> PResult<'a, P<Expr>> {
1640 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1641 attrs.extend(iattrs);
1642 if self.eat_keyword(kw::Catch) {
1643 let mut error = self.struct_span_err(self.prev_span,
1644 "keyword `catch` cannot follow a `try` block");
1645 error.help("try using `match` on the result of the `try` block instead");
1649 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
1653 fn is_do_catch_block(&self) -> bool {
1654 self.token.is_keyword(kw::Do) &&
1655 self.is_keyword_ahead(1, &[kw::Catch]) &&
1656 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
1657 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1660 fn is_try_block(&self) -> bool {
1661 self.token.is_keyword(kw::Try) &&
1662 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
1663 self.token.span.rust_2018() &&
1664 // Prevent `while try {} {}`, `if try {} {} else {}`, etc.
1665 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1668 /// Parses an `async move? {...}` expression.
1669 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1670 let span_lo = self.token.span;
1671 self.expect_keyword(kw::Async)?;
1672 let capture_clause = self.parse_capture_clause();
1673 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1674 attrs.extend(iattrs);
1676 span_lo.to(body.span),
1677 ExprKind::Async(capture_clause, DUMMY_NODE_ID, body), attrs))
1680 fn is_async_block(&self) -> bool {
1681 self.token.is_keyword(kw::Async) &&
1684 self.is_keyword_ahead(1, &[kw::Move]) &&
1685 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
1687 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
1692 fn maybe_parse_struct_expr(
1696 attrs: &ThinVec<Attribute>,
1697 ) -> Option<PResult<'a, P<Expr>>> {
1698 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
1699 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
1700 // `{ ident, ` cannot start a block.
1701 self.look_ahead(2, |t| t == &token::Comma) ||
1702 self.look_ahead(2, |t| t == &token::Colon) && (
1703 // `{ ident: token, ` cannot start a block.
1704 self.look_ahead(4, |t| t == &token::Comma) ||
1705 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
1706 self.look_ahead(3, |t| !t.can_begin_type())
1710 if struct_allowed || certainly_not_a_block() {
1711 // This is a struct literal, but we don't can't accept them here.
1712 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
1713 if let (Ok(expr), false) = (&expr, struct_allowed) {
1714 self.struct_span_err(
1716 "struct literals are not allowed here",
1718 .multipart_suggestion(
1719 "surround the struct literal with parentheses",
1721 (lo.shrink_to_lo(), "(".to_string()),
1722 (expr.span.shrink_to_hi(), ")".to_string()),
1724 Applicability::MachineApplicable,
1733 pub(super) fn parse_struct_expr(
1737 mut attrs: ThinVec<Attribute>
1738 ) -> PResult<'a, P<Expr>> {
1739 let struct_sp = lo.to(self.prev_span);
1741 let mut fields = Vec::new();
1742 let mut base = None;
1744 attrs.extend(self.parse_inner_attributes()?);
1746 while self.token != token::CloseDelim(token::Brace) {
1747 if self.eat(&token::DotDot) {
1748 let exp_span = self.prev_span;
1749 match self.parse_expr() {
1755 self.recover_stmt();
1758 if self.token == token::Comma {
1759 self.struct_span_err(
1760 exp_span.to(self.prev_span),
1761 "cannot use a comma after the base struct",
1763 .span_suggestion_short(
1765 "remove this comma",
1767 Applicability::MachineApplicable
1769 .note("the base struct must always be the last field")
1771 self.recover_stmt();
1776 let mut recovery_field = None;
1777 if let token::Ident(name, _) = self.token.kind {
1778 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
1779 // Use in case of error after field-looking code: `S { foo: () with a }`.
1780 recovery_field = Some(ast::Field {
1781 ident: Ident::new(name, self.token.span),
1782 span: self.token.span,
1783 expr: self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()),
1784 is_shorthand: false,
1785 attrs: ThinVec::new(),
1787 is_placeholder: false,
1791 let mut parsed_field = None;
1792 match self.parse_field() {
1793 Ok(f) => parsed_field = Some(f),
1795 e.span_label(struct_sp, "while parsing this struct");
1798 // If the next token is a comma, then try to parse
1799 // what comes next as additional fields, rather than
1800 // bailing out until next `}`.
1801 if self.token != token::Comma {
1802 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
1803 if self.token != token::Comma {
1810 match self.expect_one_of(&[token::Comma],
1811 &[token::CloseDelim(token::Brace)]) {
1812 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
1813 // Only include the field if there's no parse error for the field name.
1817 if let Some(f) = recovery_field {
1820 e.span_label(struct_sp, "while parsing this struct");
1822 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
1823 self.eat(&token::Comma);
1828 let span = lo.to(self.token.span);
1829 self.expect(&token::CloseDelim(token::Brace))?;
1830 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
1833 /// Parses `ident (COLON expr)?`.
1834 fn parse_field(&mut self) -> PResult<'a, Field> {
1835 let attrs = self.parse_outer_attributes()?;
1836 let lo = self.token.span;
1838 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1839 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
1840 t == &token::Colon || t == &token::Eq
1842 let fieldname = self.parse_field_name()?;
1844 // Check for an equals token. This means the source incorrectly attempts to
1845 // initialize a field with an eq rather than a colon.
1846 if self.token == token::Eq {
1848 .struct_span_err(self.token.span, "expected `:`, found `=`")
1850 fieldname.span.shrink_to_hi().to(self.token.span),
1851 "replace equals symbol with a colon",
1853 Applicability::MachineApplicable,
1858 (fieldname, self.parse_expr()?, false)
1860 let fieldname = self.parse_ident_common(false)?;
1862 // Mimic `x: x` for the `x` field shorthand.
1863 let path = ast::Path::from_ident(fieldname);
1864 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
1865 (fieldname, expr, true)
1869 span: lo.to(expr.span),
1872 attrs: attrs.into(),
1874 is_placeholder: false,
1878 fn err_dotdotdot_syntax(&self, span: Span) {
1879 self.struct_span_err(span, "unexpected token: `...`")
1882 "use `..` for an exclusive range", "..".to_owned(),
1883 Applicability::MaybeIncorrect
1887 "or `..=` for an inclusive range", "..=".to_owned(),
1888 Applicability::MaybeIncorrect
1893 fn err_larrow_operator(&self, span: Span) {
1894 self.struct_span_err(
1896 "unexpected token: `<-`"
1899 "if you meant to write a comparison against a negative value, add a \
1900 space in between `<` and `-`",
1902 Applicability::MaybeIncorrect
1906 fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
1907 ExprKind::AssignOp(binop, lhs, rhs)
1912 start: Option<P<Expr>>,
1913 end: Option<P<Expr>>,
1915 ) -> PResult<'a, ExprKind> {
1916 if end.is_none() && limits == RangeLimits::Closed {
1917 Err(self.span_fatal_err(self.token.span, Error::InclusiveRangeWithNoEnd))
1919 Ok(ExprKind::Range(start, end, limits))
1923 fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
1924 ExprKind::Unary(unop, expr)
1927 fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
1928 ExprKind::Binary(binop, lhs, rhs)
1931 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
1932 ExprKind::Index(expr, idx)
1935 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
1936 ExprKind::Call(f, args)
1939 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
1940 let span = lo.to(self.prev_span);
1941 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), ThinVec::new());
1942 self.recover_from_await_method_call();
1946 crate fn mk_expr(&self, span: Span, kind: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1947 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID })