1 use super::{Parser, PResult, Restrictions, PrevTokenKind, TokenType, PathStyle};
2 use super::{BlockMode, SemiColonMode};
3 use super::{SeqSep, TokenExpectType};
4 use super::pat::{GateOr, PARAM_EXPECTED};
6 use crate::maybe_recover_from_interpolated_ty_qpath;
8 use crate::ast::{self, Attribute, AttrStyle, Ident, CaptureBy, BlockCheckMode};
9 use crate::ast::{Expr, ExprKind, RangeLimits, Label, Movability, IsAsync, Arm};
10 use crate::ast::{Ty, TyKind, FunctionRetTy, Param, FnDecl};
11 use crate::ast::{BinOpKind, BinOp, UnOp};
12 use crate::ast::{Mac, AnonConst, Field};
14 use crate::parse::classify;
15 use crate::parse::token::{self, Token};
16 use crate::parse::diagnostics::{Error};
17 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};
23 use errors::Applicability;
24 use rustc_data_structures::thin_vec::ThinVec;
26 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
27 /// dropped into the token stream, which happens while parsing the result of
28 /// macro expansion). Placement of these is not as complex as I feared it would
29 /// be. The important thing is to make sure that lookahead doesn't balk at
30 /// `token::Interpolated` tokens.
31 macro_rules! maybe_whole_expr {
33 if let token::Interpolated(nt) = &$p.token.kind {
35 token::NtExpr(e) | token::NtLiteral(e) => {
40 token::NtPath(path) => {
41 let path = path.clone();
44 $p.token.span, ExprKind::Path(None, path), ThinVec::new()
47 token::NtBlock(block) => {
48 let block = block.clone();
51 $p.token.span, ExprKind::Block(block, None), ThinVec::new()
54 // N.B: `NtIdent(ident)` is normalized to `Ident` in `fn bump`.
62 pub(super) enum LhsExpr {
64 AttributesParsed(ThinVec<Attribute>),
65 AlreadyParsed(P<Expr>),
68 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
69 fn from(o: Option<ThinVec<Attribute>>) -> Self {
70 if let Some(attrs) = o {
71 LhsExpr::AttributesParsed(attrs)
78 impl From<P<Expr>> for LhsExpr {
79 fn from(expr: P<Expr>) -> Self {
80 LhsExpr::AlreadyParsed(expr)
85 /// Parses an expression.
87 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
88 self.parse_expr_res(Restrictions::empty(), None)
91 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
92 self.parse_paren_comma_seq(|p| {
93 match p.parse_expr() {
95 Err(mut err) => match p.token.kind {
96 token::Ident(name, false)
97 if name == kw::Underscore && p.look_ahead(1, |t| {
100 // Special-case handling of `foo(_, _, _)`
102 let sp = p.token.span;
104 Ok(p.mk_expr(sp, ExprKind::Err, ThinVec::new()))
112 /// Parses an expression, subject to the given restrictions.
114 pub(super) fn parse_expr_res(
117 already_parsed_attrs: Option<ThinVec<Attribute>>
118 ) -> PResult<'a, P<Expr>> {
119 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
122 /// Parses an associative expression.
124 /// This parses an expression accounting for associativity and precedence of the operators in
129 already_parsed_attrs: Option<ThinVec<Attribute>>,
130 ) -> PResult<'a, P<Expr>> {
131 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
134 /// Parses an associative expression with operators of at least `min_prec` precedence.
135 pub(super) fn parse_assoc_expr_with(
139 ) -> PResult<'a, P<Expr>> {
140 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
143 let attrs = match lhs {
144 LhsExpr::AttributesParsed(attrs) => Some(attrs),
147 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
148 return self.parse_prefix_range_expr(attrs);
150 self.parse_prefix_expr(attrs)?
153 let last_type_ascription_set = self.last_type_ascription.is_some();
155 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
157 self.last_type_ascription = None;
158 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
161 (false, _) => {} // continue parsing the expression
162 // An exhaustive check is done in the following block, but these are checked first
163 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
164 // want to keep their span info to improve diagnostics in these cases in a later stage.
165 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
166 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
167 (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475)
168 (true, Some(AssocOp::Add)) // `{ 42 } + 42
169 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
170 // `if x { a } else { b } && if y { c } else { d }`
171 if !self.look_ahead(1, |t| t.is_reserved_ident()) => {
172 self.last_type_ascription = None;
173 // These cases are ambiguous and can't be identified in the parser alone
174 let sp = self.sess.source_map().start_point(self.token.span);
175 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
178 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
179 self.last_type_ascription = None;
183 // We've found an expression that would be parsed as a statement, but the next
184 // token implies this should be parsed as an expression.
185 // For example: `if let Some(x) = x { x } else { 0 } / 2`
186 let mut err = self.struct_span_err(self.token.span, &format!(
187 "expected expression, found `{}`",
188 pprust::token_to_string(&self.token),
190 err.span_label(self.token.span, "expected expression");
191 self.sess.expr_parentheses_needed(
194 Some(pprust::expr_to_string(&lhs),
199 self.expected_tokens.push(TokenType::Operator);
200 while let Some(op) = AssocOp::from_token(&self.token) {
202 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
203 // it refers to. Interpolated identifiers are unwrapped early and never show up here
204 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
205 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
206 let lhs_span = match (self.prev_token_kind, &lhs.node) {
207 (PrevTokenKind::Interpolated, _) => self.prev_span,
208 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
209 if path.segments.len() == 1 => self.prev_span,
213 let cur_op_span = self.token.span;
214 let restrictions = if op.is_assign_like() {
215 self.restrictions & Restrictions::NO_STRUCT_LITERAL
219 let prec = op.precedence();
223 // Check for deprecated `...` syntax
224 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
225 self.err_dotdotdot_syntax(self.token.span);
228 if self.token == token::LArrow {
229 self.err_larrow_operator(self.token.span);
233 if op.is_comparison() {
234 self.check_no_chained_comparison(&lhs, &op);
237 if op == AssocOp::As {
238 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
240 } else if op == AssocOp::Colon {
241 let maybe_path = self.could_ascription_be_path(&lhs.node);
242 self.last_type_ascription = Some((self.prev_span, maybe_path));
244 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
246 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
247 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
248 // generalise it to the Fixity::None code.
250 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
251 // two variants are handled with `parse_prefix_range_expr` call above.
252 let rhs = if self.is_at_start_of_range_notation_rhs() {
253 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
257 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
262 let limits = if op == AssocOp::DotDot {
263 RangeLimits::HalfOpen
268 let r = self.mk_range(Some(lhs), rhs, limits)?;
269 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
273 let fixity = op.fixity();
274 let prec_adjustment = match fixity {
277 // We currently have no non-associative operators that are not handled above by
278 // the special cases. The code is here only for future convenience.
281 let rhs = self.with_res(
282 restrictions - Restrictions::STMT_EXPR,
283 |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
286 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
287 // including the attributes.
291 .filter(|a| a.style == AttrStyle::Outer)
293 .map_or(lhs_span, |a| a.span);
294 let span = lhs_span.to(rhs.span);
296 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
297 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
298 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
299 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
300 AssocOp::Greater | AssocOp::GreaterEqual => {
301 let ast_op = op.to_ast_binop().unwrap();
302 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
303 self.mk_expr(span, binary, ThinVec::new())
305 AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
306 AssocOp::AssignOp(k) => {
308 token::Plus => BinOpKind::Add,
309 token::Minus => BinOpKind::Sub,
310 token::Star => BinOpKind::Mul,
311 token::Slash => BinOpKind::Div,
312 token::Percent => BinOpKind::Rem,
313 token::Caret => BinOpKind::BitXor,
314 token::And => BinOpKind::BitAnd,
315 token::Or => BinOpKind::BitOr,
316 token::Shl => BinOpKind::Shl,
317 token::Shr => BinOpKind::Shr,
319 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
320 self.mk_expr(span, aopexpr, ThinVec::new())
322 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
323 self.bug("AssocOp should have been handled by special case")
327 if let Fixity::None = fixity { break }
329 if last_type_ascription_set {
330 self.last_type_ascription = None;
335 /// Checks if this expression is a successfully parsed statement.
336 fn expr_is_complete(&self, e: &Expr) -> bool {
337 self.restrictions.contains(Restrictions::STMT_EXPR) &&
338 !classify::expr_requires_semi_to_be_stmt(e)
341 fn is_at_start_of_range_notation_rhs(&self) -> bool {
342 if self.token.can_begin_expr() {
343 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
344 if self.token == token::OpenDelim(token::Brace) {
345 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
353 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
354 fn parse_prefix_range_expr(
356 already_parsed_attrs: Option<ThinVec<Attribute>>
357 ) -> PResult<'a, P<Expr>> {
358 // Check for deprecated `...` syntax
359 if self.token == token::DotDotDot {
360 self.err_dotdotdot_syntax(self.token.span);
363 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
364 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
366 let tok = self.token.clone();
367 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
368 let lo = self.token.span;
369 let mut hi = self.token.span;
371 let opt_end = if self.is_at_start_of_range_notation_rhs() {
372 // RHS must be parsed with more associativity than the dots.
373 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
374 Some(self.parse_assoc_expr_with(next_prec, LhsExpr::NotYetParsed)
382 let limits = if tok == token::DotDot {
383 RangeLimits::HalfOpen
388 let r = self.mk_range(None, opt_end, limits)?;
389 Ok(self.mk_expr(lo.to(hi), r, attrs))
392 /// Parse a prefix-unary-operator expr
393 fn parse_prefix_expr(
395 already_parsed_attrs: Option<ThinVec<Attribute>>
396 ) -> PResult<'a, P<Expr>> {
397 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
398 let lo = self.token.span;
399 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
400 let (hi, ex) = match self.token.kind {
403 let e = self.parse_prefix_expr(None);
404 let (span, e) = self.interpolated_or_expr_span(e)?;
405 (lo.to(span), self.mk_unary(UnOp::Not, e))
407 // Suggest `!` for bitwise negation when encountering a `~`
410 let e = self.parse_prefix_expr(None);
411 let (span, e) = self.interpolated_or_expr_span(e)?;
412 let span_of_tilde = lo;
413 self.struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator")
414 .span_suggestion_short(
416 "use `!` to perform bitwise negation",
418 Applicability::MachineApplicable
421 (lo.to(span), self.mk_unary(UnOp::Not, e))
423 token::BinOp(token::Minus) => {
425 let e = self.parse_prefix_expr(None);
426 let (span, e) = self.interpolated_or_expr_span(e)?;
427 (lo.to(span), self.mk_unary(UnOp::Neg, e))
429 token::BinOp(token::Star) => {
431 let e = self.parse_prefix_expr(None);
432 let (span, e) = self.interpolated_or_expr_span(e)?;
433 (lo.to(span), self.mk_unary(UnOp::Deref, e))
435 token::BinOp(token::And) | token::AndAnd => {
437 let m = self.parse_mutability();
438 let e = self.parse_prefix_expr(None);
439 let (span, e) = self.interpolated_or_expr_span(e)?;
440 (lo.to(span), ExprKind::AddrOf(m, e))
442 token::Ident(..) if self.token.is_keyword(kw::Box) => {
444 let e = self.parse_prefix_expr(None);
445 let (span, e) = self.interpolated_or_expr_span(e)?;
446 (lo.to(span), ExprKind::Box(e))
448 token::Ident(..) if self.token.is_ident_named(sym::not) => {
449 // `not` is just an ordinary identifier in Rust-the-language,
450 // but as `rustc`-the-compiler, we can issue clever diagnostics
451 // for confused users who really want to say `!`
452 let token_cannot_continue_expr = |t: &Token| match t.kind {
453 // These tokens can start an expression after `!`, but
454 // can't continue an expression after an ident
455 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
456 token::Literal(..) | token::Pound => true,
457 _ => t.is_whole_expr(),
459 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
460 if cannot_continue_expr {
462 // Emit the error ...
463 self.struct_span_err(
465 &format!("unexpected {} after identifier",self.this_token_descr())
467 .span_suggestion_short(
468 // Span the `not` plus trailing whitespace to avoid
469 // trailing whitespace after the `!` in our suggestion
470 self.sess.source_map()
471 .span_until_non_whitespace(lo.to(self.token.span)),
472 "use `!` to perform logical negation",
474 Applicability::MachineApplicable
477 // —and recover! (just as if we were in the block
478 // for the `token::Not` arm)
479 let e = self.parse_prefix_expr(None);
480 let (span, e) = self.interpolated_or_expr_span(e)?;
481 (lo.to(span), self.mk_unary(UnOp::Not, e))
483 return self.parse_dot_or_call_expr(Some(attrs));
486 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
488 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
491 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
492 fn interpolated_or_expr_span(
494 expr: PResult<'a, P<Expr>>,
495 ) -> PResult<'a, (Span, P<Expr>)> {
497 if self.prev_token_kind == PrevTokenKind::Interpolated {
505 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
506 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
507 -> PResult<'a, P<Expr>> {
508 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
509 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
512 // Save the state of the parser before parsing type normally, in case there is a
513 // LessThan comparison after this cast.
514 let parser_snapshot_before_type = self.clone();
515 match self.parse_ty_no_plus() {
517 Ok(mk_expr(self, rhs))
519 Err(mut type_err) => {
520 // Rewind to before attempting to parse the type with generics, to recover
521 // from situations like `x as usize < y` in which we first tried to parse
522 // `usize < y` as a type with generic arguments.
523 let parser_snapshot_after_type = self.clone();
524 mem::replace(self, parser_snapshot_before_type);
526 match self.parse_path(PathStyle::Expr) {
528 let (op_noun, op_verb) = match self.token.kind {
529 token::Lt => ("comparison", "comparing"),
530 token::BinOp(token::Shl) => ("shift", "shifting"),
532 // We can end up here even without `<` being the next token, for
533 // example because `parse_ty_no_plus` returns `Err` on keywords,
534 // but `parse_path` returns `Ok` on them due to error recovery.
535 // Return original error and parser state.
536 mem::replace(self, parser_snapshot_after_type);
537 return Err(type_err);
541 // Successfully parsed the type path leaving a `<` yet to parse.
544 // Report non-fatal diagnostics, keep `x as usize` as an expression
545 // in AST and continue parsing.
546 let msg = format!("`<` is interpreted as a start of generic \
547 arguments for `{}`, not a {}", path, op_noun);
548 let span_after_type = parser_snapshot_after_type.token.span;
549 let expr = mk_expr(self, P(Ty {
551 node: TyKind::Path(None, path),
552 id: ast::DUMMY_NODE_ID
555 let expr_str = self.span_to_snippet(expr.span)
556 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
558 self.struct_span_err(self.token.span, &msg)
560 self.look_ahead(1, |t| t.span).to(span_after_type),
561 "interpreted as generic arguments"
563 .span_label(self.token.span, format!("not interpreted as {}", op_noun))
566 &format!("try {} the cast value", op_verb),
567 format!("({})", expr_str),
568 Applicability::MachineApplicable
574 Err(mut path_err) => {
575 // Couldn't parse as a path, return original error and parser state.
577 mem::replace(self, parser_snapshot_after_type);
585 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
586 fn parse_dot_or_call_expr(
588 already_parsed_attrs: Option<ThinVec<Attribute>>,
589 ) -> PResult<'a, P<Expr>> {
590 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
592 let b = self.parse_bottom_expr();
593 let (span, b) = self.interpolated_or_expr_span(b)?;
594 self.parse_dot_or_call_expr_with(b, span, attrs)
597 pub(super) fn parse_dot_or_call_expr_with(
601 mut attrs: ThinVec<Attribute>,
602 ) -> PResult<'a, P<Expr>> {
603 // Stitch the list of outer attributes onto the return value.
604 // A little bit ugly, but the best way given the current code
606 self.parse_dot_or_call_expr_with_(e0, lo).map(|expr|
607 expr.map(|mut expr| {
608 attrs.extend::<Vec<_>>(expr.attrs.into());
611 ExprKind::If(..) if !expr.attrs.is_empty() => {
612 // Just point to the first attribute in there...
613 let span = expr.attrs[0].span;
614 self.span_err(span, "attributes are not yet allowed on `if` expressions");
623 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
628 while self.eat(&token::Question) {
629 let hi = self.prev_span;
630 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
634 if self.eat(&token::Dot) {
635 match self.token.kind {
636 token::Ident(..) => {
637 e = self.parse_dot_suffix(e, lo)?;
639 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
640 let span = self.token.span;
642 let field = ExprKind::Field(e, Ident::new(symbol, span));
643 e = self.mk_expr(lo.to(span), field, ThinVec::new());
645 self.expect_no_suffix(span, "a tuple index", suffix);
647 token::Literal(token::Lit { kind: token::Float, symbol, .. }) => {
649 let fstr = symbol.as_str();
650 let msg = format!("unexpected token: `{}`", symbol);
651 let mut err = self.diagnostic().struct_span_err(self.prev_span, &msg);
652 err.span_label(self.prev_span, "unexpected token");
653 if fstr.chars().all(|x| "0123456789.".contains(x)) {
654 let float = match fstr.parse::<f64>().ok() {
658 let sugg = pprust::to_string(|s| {
662 s.print_usize(float.trunc() as usize);
665 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
668 lo.to(self.prev_span),
669 "try parenthesizing the first index",
671 Applicability::MachineApplicable
678 // FIXME Could factor this out into non_fatal_unexpected or something.
679 let actual = self.this_token_to_string();
680 self.span_err(self.token.span, &format!("unexpected token: `{}`", actual));
685 if self.expr_is_complete(&e) { break; }
686 match self.token.kind {
688 token::OpenDelim(token::Paren) => {
689 let seq = self.parse_paren_expr_seq().map(|es| {
690 let nd = self.mk_call(e, es);
691 let hi = self.prev_span;
692 self.mk_expr(lo.to(hi), nd, ThinVec::new())
694 e = self.recover_seq_parse_error(token::Paren, lo, seq);
698 // Could be either an index expression or a slicing expression.
699 token::OpenDelim(token::Bracket) => {
701 let ix = self.parse_expr()?;
702 hi = self.token.span;
703 self.expect(&token::CloseDelim(token::Bracket))?;
704 let index = self.mk_index(e, ix);
705 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
713 /// Assuming we have just parsed `.`, continue parsing into an expression.
714 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
715 if self.token.span.rust_2018() && self.eat_keyword(kw::Await) {
716 return self.mk_await_expr(self_arg, lo);
719 let segment = self.parse_path_segment(PathStyle::Expr)?;
720 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
722 Ok(match self.token.kind {
723 token::OpenDelim(token::Paren) => {
724 // Method call `expr.f()`
725 let mut args = self.parse_paren_expr_seq()?;
726 args.insert(0, self_arg);
728 let span = lo.to(self.prev_span);
729 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
732 // Field access `expr.f`
733 if let Some(args) = segment.args {
734 self.span_err(args.span(),
735 "field expressions may not have generic arguments");
738 let span = lo.to(self.prev_span);
739 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
745 /// At the bottom (top?) of the precedence hierarchy,
746 /// Parses things like parenthesized exprs, macros, `return`, etc.
748 /// N.B., this does not parse outer attributes, and is private because it only works
749 /// correctly if called from `parse_dot_or_call_expr()`.
750 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
751 maybe_recover_from_interpolated_ty_qpath!(self, true);
752 maybe_whole_expr!(self);
754 // Outer attributes are already parsed and will be
755 // added to the return value after the fact.
757 // Therefore, prevent sub-parser from parsing
758 // attributes by giving them a empty "already parsed" list.
759 let mut attrs = ThinVec::new();
761 let lo = self.token.span;
762 let mut hi = self.token.span;
766 macro_rules! parse_lit {
768 match self.parse_lit() {
771 ex = ExprKind::Lit(literal);
774 self.cancel(&mut err);
775 return Err(self.expected_expression_found());
781 // Note: when adding new syntax here, don't forget to adjust TokenKind::can_begin_expr().
782 match self.token.kind {
783 // This match arm is a special-case of the `_` match arm below and
784 // could be removed without changing functionality, but it's faster
785 // to have it here, especially for programs with large constants.
786 token::Literal(_) => {
789 token::OpenDelim(token::Paren) => {
792 attrs.extend(self.parse_inner_attributes()?);
794 // (e) is parenthesized e
795 // (e,) is a tuple with only one field, e
797 let mut trailing_comma = false;
798 let mut recovered = false;
799 while self.token != token::CloseDelim(token::Paren) {
800 es.push(match self.parse_expr() {
803 // recover from parse error in tuple list
804 match self.token.kind {
805 token::Ident(name, false)
806 if name == kw::Underscore && self.look_ahead(1, |t| {
809 // Special-case handling of `Foo<(_, _, _)>`
811 let sp = self.token.span;
813 self.mk_expr(sp, ExprKind::Err, ThinVec::new())
816 self.recover_seq_parse_error(token::Paren, lo, Err(err)),
821 recovered = self.expect_one_of(
823 &[token::Comma, token::CloseDelim(token::Paren)],
825 if self.eat(&token::Comma) {
826 trailing_comma = true;
828 trailing_comma = false;
837 ex = if es.len() == 1 && !trailing_comma {
838 ExprKind::Paren(es.into_iter().nth(0).unwrap())
843 token::OpenDelim(token::Brace) => {
844 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
846 token::BinOp(token::Or) | token::OrOr => {
847 return self.parse_lambda_expr(attrs);
849 token::OpenDelim(token::Bracket) => {
852 attrs.extend(self.parse_inner_attributes()?);
854 if self.eat(&token::CloseDelim(token::Bracket)) {
856 ex = ExprKind::Array(Vec::new());
859 let first_expr = self.parse_expr()?;
860 if self.eat(&token::Semi) {
861 // Repeating array syntax: [ 0; 512 ]
862 let count = AnonConst {
863 id: ast::DUMMY_NODE_ID,
864 value: self.parse_expr()?,
866 self.expect(&token::CloseDelim(token::Bracket))?;
867 ex = ExprKind::Repeat(first_expr, count);
868 } else if self.eat(&token::Comma) {
869 // Vector with two or more elements.
870 let remaining_exprs = self.parse_seq_to_end(
871 &token::CloseDelim(token::Bracket),
872 SeqSep::trailing_allowed(token::Comma),
873 |p| Ok(p.parse_expr()?)
875 let mut exprs = vec![first_expr];
876 exprs.extend(remaining_exprs);
877 ex = ExprKind::Array(exprs);
879 // Vector with one element.
880 self.expect(&token::CloseDelim(token::Bracket))?;
881 ex = ExprKind::Array(vec![first_expr]);
888 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
890 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
892 if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
893 return self.parse_lambda_expr(attrs);
895 if self.eat_keyword(kw::If) {
896 return self.parse_if_expr(attrs);
898 if self.eat_keyword(kw::For) {
899 let lo = self.prev_span;
900 return self.parse_for_expr(None, lo, attrs);
902 if self.eat_keyword(kw::While) {
903 let lo = self.prev_span;
904 return self.parse_while_expr(None, lo, attrs);
906 if let Some(label) = self.eat_label() {
907 let lo = label.ident.span;
908 self.expect(&token::Colon)?;
909 if self.eat_keyword(kw::While) {
910 return self.parse_while_expr(Some(label), lo, attrs)
912 if self.eat_keyword(kw::For) {
913 return self.parse_for_expr(Some(label), lo, attrs)
915 if self.eat_keyword(kw::Loop) {
916 return self.parse_loop_expr(Some(label), lo, attrs)
918 if self.token == token::OpenDelim(token::Brace) {
919 return self.parse_block_expr(Some(label),
921 BlockCheckMode::Default,
924 let msg = "expected `while`, `for`, `loop` or `{` after a label";
925 let mut err = self.fatal(msg);
926 err.span_label(self.token.span, msg);
929 if self.eat_keyword(kw::Loop) {
930 let lo = self.prev_span;
931 return self.parse_loop_expr(None, lo, attrs);
933 if self.eat_keyword(kw::Continue) {
934 let label = self.eat_label();
935 let ex = ExprKind::Continue(label);
936 let hi = self.prev_span;
937 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
939 if self.eat_keyword(kw::Match) {
940 let match_sp = self.prev_span;
941 return self.parse_match_expr(attrs).map_err(|mut err| {
942 err.span_label(match_sp, "while parsing this match expression");
946 if self.eat_keyword(kw::Unsafe) {
947 return self.parse_block_expr(
950 BlockCheckMode::Unsafe(ast::UserProvided),
953 if self.is_do_catch_block() {
954 let mut db = self.fatal("found removed `do catch` syntax");
955 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
958 if self.is_try_block() {
959 let lo = self.token.span;
960 assert!(self.eat_keyword(kw::Try));
961 return self.parse_try_block(lo, attrs);
964 // Span::rust_2018() is somewhat expensive; don't get it repeatedly.
965 let is_span_rust_2018 = self.token.span.rust_2018();
966 if is_span_rust_2018 && self.check_keyword(kw::Async) {
967 return if self.is_async_block() { // check for `async {` and `async move {`
968 self.parse_async_block(attrs)
970 self.parse_lambda_expr(attrs)
973 if self.eat_keyword(kw::Return) {
974 if self.token.can_begin_expr() {
975 let e = self.parse_expr()?;
977 ex = ExprKind::Ret(Some(e));
979 ex = ExprKind::Ret(None);
981 } else if self.eat_keyword(kw::Break) {
982 let label = self.eat_label();
983 let e = if self.token.can_begin_expr()
984 && !(self.token == token::OpenDelim(token::Brace)
985 && self.restrictions.contains(
986 Restrictions::NO_STRUCT_LITERAL)) {
987 Some(self.parse_expr()?)
991 ex = ExprKind::Break(label, e);
993 } else if self.eat_keyword(kw::Yield) {
994 if self.token.can_begin_expr() {
995 let e = self.parse_expr()?;
997 ex = ExprKind::Yield(Some(e));
999 ex = ExprKind::Yield(None);
1002 let span = lo.to(hi);
1003 self.sess.gated_spans.yields.borrow_mut().push(span);
1004 } else if self.eat_keyword(kw::Let) {
1005 return self.parse_let_expr(attrs);
1006 } else if is_span_rust_2018 && self.eat_keyword(kw::Await) {
1007 let (await_hi, e_kind) = self.parse_incorrect_await_syntax(lo, self.prev_span)?;
1010 } else if self.token.is_path_start() {
1011 let path = self.parse_path(PathStyle::Expr)?;
1013 // `!`, as an operator, is prefix, so we know this isn't that
1014 if self.eat(&token::Not) {
1015 // MACRO INVOCATION expression
1016 let (delim, tts) = self.expect_delimited_token_tree()?;
1017 hi = self.prev_span;
1018 ex = ExprKind::Mac(Mac {
1023 prior_type_ascription: self.last_type_ascription,
1025 } else if self.check(&token::OpenDelim(token::Brace)) {
1026 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
1030 ex = ExprKind::Path(None, path);
1034 ex = ExprKind::Path(None, path);
1037 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1038 // Don't complain about bare semicolons after unclosed braces
1039 // recovery in order to keep the error count down. Fixing the
1040 // delimiters will possibly also fix the bare semicolon found in
1041 // expression context. For example, silence the following error:
1043 // error: expected expression, found `;`
1047 // | ^ expected expression
1050 return Ok(self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()));
1057 let expr = self.mk_expr(lo.to(hi), ex, attrs);
1058 self.maybe_recover_from_bad_qpath(expr, true)
1061 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1062 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1063 maybe_whole_expr!(self);
1065 let minus_lo = self.token.span;
1066 let minus_present = self.eat(&token::BinOp(token::Minus));
1067 let lo = self.token.span;
1068 let literal = self.parse_lit()?;
1069 let hi = self.prev_span;
1070 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1073 let minus_hi = self.prev_span;
1074 let unary = self.mk_unary(UnOp::Neg, expr);
1075 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1081 /// Parses a block or unsafe block.
1082 crate fn parse_block_expr(
1084 opt_label: Option<Label>,
1086 blk_mode: BlockCheckMode,
1087 outer_attrs: ThinVec<Attribute>,
1088 ) -> PResult<'a, P<Expr>> {
1089 self.expect(&token::OpenDelim(token::Brace))?;
1091 let mut attrs = outer_attrs;
1092 attrs.extend(self.parse_inner_attributes()?);
1094 let blk = self.parse_block_tail(lo, blk_mode)?;
1095 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
1098 /// Parses `move |args| expr`.
1099 fn parse_lambda_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1100 let lo = self.token.span;
1102 let movability = if self.eat_keyword(kw::Static) {
1108 let asyncness = if self.token.span.rust_2018() {
1109 self.parse_asyncness()
1113 if asyncness.is_async() {
1114 // Feature gate `async ||` closures.
1115 self.sess.gated_spans.async_closure.borrow_mut().push(self.prev_span);
1118 let capture_clause = self.parse_capture_clause();
1119 let decl = self.parse_fn_block_decl()?;
1120 let decl_hi = self.prev_span;
1121 let body = match decl.output {
1122 FunctionRetTy::Default(_) => {
1123 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
1124 self.parse_expr_res(restrictions, None)?
1127 // If an explicit return type is given, require a
1128 // block to appear (RFC 968).
1129 let body_lo = self.token.span;
1130 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
1136 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
1140 /// Parse an optional `move` prefix to a closure lke construct.
1141 fn parse_capture_clause(&mut self) -> CaptureBy {
1142 if self.eat_keyword(kw::Move) {
1149 /// Parses the `|arg, arg|` header of a closure.
1150 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
1151 let inputs_captures = {
1152 if self.eat(&token::OrOr) {
1155 self.expect(&token::BinOp(token::Or))?;
1156 let args = self.parse_seq_to_before_tokens(
1157 &[&token::BinOp(token::Or), &token::OrOr],
1158 SeqSep::trailing_allowed(token::Comma),
1159 TokenExpectType::NoExpect,
1160 |p| p.parse_fn_block_param()
1166 let output = self.parse_ret_ty(true)?;
1169 inputs: inputs_captures,
1175 /// Parses a parameter in a lambda header (e.g., `|arg, arg|`).
1176 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
1177 let lo = self.token.span;
1178 let attrs = self.parse_param_attributes()?;
1179 let pat = self.parse_pat(PARAM_EXPECTED)?;
1180 let t = if self.eat(&token::Colon) {
1184 id: ast::DUMMY_NODE_ID,
1185 node: TyKind::Infer,
1186 span: self.prev_span,
1189 let span = lo.to(self.token.span);
1191 attrs: attrs.into(),
1195 id: ast::DUMMY_NODE_ID
1199 /// Parses an `if` expression (`if` token already eaten).
1200 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1201 let lo = self.prev_span;
1202 let cond = self.parse_cond_expr()?;
1204 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1205 // verify that the last statement is either an implicit return (no `;`) or an explicit
1206 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1207 // the dead code lint.
1208 if self.eat_keyword(kw::Else) || !cond.returns() {
1209 let sp = self.sess.source_map().next_point(lo);
1210 let mut err = self.diagnostic()
1211 .struct_span_err(sp, "missing condition for `if` expression");
1212 err.span_label(sp, "expected if condition here");
1215 let not_block = self.token != token::OpenDelim(token::Brace);
1216 let thn = self.parse_block().map_err(|mut err| {
1218 err.span_label(lo, "this `if` statement has a condition, but no block");
1222 let mut els: Option<P<Expr>> = None;
1223 let mut hi = thn.span;
1224 if self.eat_keyword(kw::Else) {
1225 let elexpr = self.parse_else_expr()?;
1229 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
1232 /// Parse the condition of a `if`- or `while`-expression
1233 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
1234 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1236 if let ExprKind::Let(..) = cond.node {
1237 // Remove the last feature gating of a `let` expression since it's stable.
1238 let last = self.sess.gated_spans.let_chains.borrow_mut().pop();
1239 debug_assert_eq!(cond.span, last.unwrap());
1245 /// Parses a `let $pat = $expr` pseudo-expression.
1246 /// The `let` token has already been eaten.
1247 fn parse_let_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1248 let lo = self.prev_span;
1249 // FIXME(or_patterns, Centril | dlrobertson): use `parse_top_pat` instead.
1250 let pat = self.parse_top_pat_unpack(GateOr::No)?;
1251 self.expect(&token::Eq)?;
1252 let expr = self.with_res(
1253 Restrictions::NO_STRUCT_LITERAL,
1254 |this| this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
1256 let span = lo.to(expr.span);
1257 self.sess.gated_spans.let_chains.borrow_mut().push(span);
1258 Ok(self.mk_expr(span, ExprKind::Let(pat, expr), attrs))
1261 /// `else` token already eaten
1262 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
1263 if self.eat_keyword(kw::If) {
1264 return self.parse_if_expr(ThinVec::new());
1266 let blk = self.parse_block()?;
1267 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
1271 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
1274 opt_label: Option<Label>,
1276 mut attrs: ThinVec<Attribute>
1277 ) -> PResult<'a, P<Expr>> {
1278 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
1280 // Record whether we are about to parse `for (`.
1281 // This is used below for recovery in case of `for ( $stuff ) $block`
1282 // in which case we will suggest `for $stuff $block`.
1283 let begin_paren = match self.token.kind {
1284 token::OpenDelim(token::Paren) => Some(self.token.span),
1288 let pat = self.parse_top_pat(GateOr::Yes)?;
1289 if !self.eat_keyword(kw::In) {
1290 let in_span = self.prev_span.between(self.token.span);
1291 self.struct_span_err(in_span, "missing `in` in `for` loop")
1292 .span_suggestion_short(
1294 "try adding `in` here", " in ".into(),
1295 // has been misleading, at least in the past (closed Issue #48492)
1296 Applicability::MaybeIncorrect
1300 let in_span = self.prev_span;
1301 self.check_for_for_in_in_typo(in_span);
1302 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1304 let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
1306 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
1307 attrs.extend(iattrs);
1309 let hi = self.prev_span;
1310 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
1313 /// Parses a `while` or `while let` expression (`while` token already eaten).
1314 fn parse_while_expr(
1316 opt_label: Option<Label>,
1318 mut attrs: ThinVec<Attribute>
1319 ) -> PResult<'a, P<Expr>> {
1320 let cond = self.parse_cond_expr()?;
1321 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1322 attrs.extend(iattrs);
1323 let span = span_lo.to(body.span);
1324 Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs))
1327 /// Parse `loop {...}`, `loop` token already eaten.
1330 opt_label: Option<Label>,
1332 mut attrs: ThinVec<Attribute>
1333 ) -> PResult<'a, P<Expr>> {
1334 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1335 attrs.extend(iattrs);
1336 let span = span_lo.to(body.span);
1337 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
1340 fn eat_label(&mut self) -> Option<Label> {
1341 if let Some(ident) = self.token.lifetime() {
1342 let span = self.token.span;
1344 Some(Label { ident: Ident::new(ident.name, span) })
1350 // `match` token already eaten
1351 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1352 let match_span = self.prev_span;
1353 let lo = self.prev_span;
1354 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1355 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
1356 if self.token == token::Semi {
1357 e.span_suggestion_short(
1359 "try removing this `match`",
1361 Applicability::MaybeIncorrect // speculative
1366 attrs.extend(self.parse_inner_attributes()?);
1368 let mut arms: Vec<Arm> = Vec::new();
1369 while self.token != token::CloseDelim(token::Brace) {
1370 match self.parse_arm() {
1371 Ok(arm) => arms.push(arm),
1373 // Recover by skipping to the end of the block.
1375 self.recover_stmt();
1376 let span = lo.to(self.token.span);
1377 if self.token == token::CloseDelim(token::Brace) {
1380 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
1384 let hi = self.token.span;
1386 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
1389 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
1390 let attrs = self.parse_outer_attributes()?;
1391 let lo = self.token.span;
1392 // FIXME(or_patterns, Centril | dlrobertson): use `parse_top_pat` instead.
1393 let pat = self.parse_top_pat_unpack(GateOr::No)?;
1394 let guard = if self.eat_keyword(kw::If) {
1395 Some(self.parse_expr()?)
1399 let arrow_span = self.token.span;
1400 self.expect(&token::FatArrow)?;
1401 let arm_start_span = self.token.span;
1403 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
1404 .map_err(|mut err| {
1405 err.span_label(arrow_span, "while parsing the `match` arm starting here");
1409 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
1410 && self.token != token::CloseDelim(token::Brace);
1412 let hi = self.token.span;
1415 let cm = self.sess.source_map();
1416 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
1417 .map_err(|mut err| {
1418 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
1419 (Ok(ref expr_lines), Ok(ref arm_start_lines))
1420 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
1421 && expr_lines.lines.len() == 2
1422 && self.token == token::FatArrow => {
1423 // We check whether there's any trailing code in the parse span,
1424 // if there isn't, we very likely have the following:
1427 // | -- - missing comma
1431 // | - ^^ self.token.span
1433 // | parsed until here as `"y" & X`
1434 err.span_suggestion_short(
1435 cm.next_point(arm_start_span),
1436 "missing a comma here to end this `match` arm",
1438 Applicability::MachineApplicable
1442 err.span_label(arrow_span,
1443 "while parsing the `match` arm starting here");
1449 self.eat(&token::Comma);
1454 pats: pat, // FIXME(or_patterns, Centril | dlrobertson): this should just be `pat,`.
1458 id: ast::DUMMY_NODE_ID,
1462 /// Parses a `try {...}` expression (`try` token already eaten).
1466 mut attrs: ThinVec<Attribute>
1467 ) -> PResult<'a, P<Expr>> {
1468 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1469 attrs.extend(iattrs);
1470 if self.eat_keyword(kw::Catch) {
1471 let mut error = self.struct_span_err(self.prev_span,
1472 "keyword `catch` cannot follow a `try` block");
1473 error.help("try using `match` on the result of the `try` block instead");
1477 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
1481 fn is_do_catch_block(&self) -> bool {
1482 self.token.is_keyword(kw::Do) &&
1483 self.is_keyword_ahead(1, &[kw::Catch]) &&
1484 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
1485 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1488 fn is_try_block(&self) -> bool {
1489 self.token.is_keyword(kw::Try) &&
1490 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
1491 self.token.span.rust_2018() &&
1492 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
1493 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1496 /// Parses an `async move? {...}` expression.
1497 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1498 let span_lo = self.token.span;
1499 self.expect_keyword(kw::Async)?;
1500 let capture_clause = self.parse_capture_clause();
1501 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1502 attrs.extend(iattrs);
1504 span_lo.to(body.span),
1505 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
1508 fn is_async_block(&self) -> bool {
1509 self.token.is_keyword(kw::Async) &&
1512 self.is_keyword_ahead(1, &[kw::Move]) &&
1513 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
1515 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
1520 fn maybe_parse_struct_expr(
1524 attrs: &ThinVec<Attribute>,
1525 ) -> Option<PResult<'a, P<Expr>>> {
1526 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
1527 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
1528 // `{ ident, ` cannot start a block
1529 self.look_ahead(2, |t| t == &token::Comma) ||
1530 self.look_ahead(2, |t| t == &token::Colon) && (
1531 // `{ ident: token, ` cannot start a block
1532 self.look_ahead(4, |t| t == &token::Comma) ||
1533 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
1534 self.look_ahead(3, |t| !t.can_begin_type())
1538 if struct_allowed || certainly_not_a_block() {
1539 // This is a struct literal, but we don't can't accept them here
1540 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
1541 if let (Ok(expr), false) = (&expr, struct_allowed) {
1542 self.struct_span_err(
1544 "struct literals are not allowed here",
1546 .multipart_suggestion(
1547 "surround the struct literal with parentheses",
1549 (lo.shrink_to_lo(), "(".to_string()),
1550 (expr.span.shrink_to_hi(), ")".to_string()),
1552 Applicability::MachineApplicable,
1561 pub(super) fn parse_struct_expr(
1565 mut attrs: ThinVec<Attribute>
1566 ) -> PResult<'a, P<Expr>> {
1567 let struct_sp = lo.to(self.prev_span);
1569 let mut fields = Vec::new();
1570 let mut base = None;
1572 attrs.extend(self.parse_inner_attributes()?);
1574 while self.token != token::CloseDelim(token::Brace) {
1575 if self.eat(&token::DotDot) {
1576 let exp_span = self.prev_span;
1577 match self.parse_expr() {
1583 self.recover_stmt();
1586 if self.token == token::Comma {
1587 self.struct_span_err(
1588 exp_span.to(self.prev_span),
1589 "cannot use a comma after the base struct",
1591 .span_suggestion_short(
1593 "remove this comma",
1595 Applicability::MachineApplicable
1597 .note("the base struct must always be the last field")
1599 self.recover_stmt();
1604 let mut recovery_field = None;
1605 if let token::Ident(name, _) = self.token.kind {
1606 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
1607 // Use in case of error after field-looking code: `S { foo: () with a }`
1608 recovery_field = Some(ast::Field {
1609 ident: Ident::new(name, self.token.span),
1610 span: self.token.span,
1611 expr: self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()),
1612 is_shorthand: false,
1613 attrs: ThinVec::new(),
1614 id: ast::DUMMY_NODE_ID,
1618 let mut parsed_field = None;
1619 match self.parse_field() {
1620 Ok(f) => parsed_field = Some(f),
1622 e.span_label(struct_sp, "while parsing this struct");
1625 // If the next token is a comma, then try to parse
1626 // what comes next as additional fields, rather than
1627 // bailing out until next `}`.
1628 if self.token != token::Comma {
1629 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
1630 if self.token != token::Comma {
1637 match self.expect_one_of(&[token::Comma],
1638 &[token::CloseDelim(token::Brace)]) {
1639 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
1640 // only include the field if there's no parse error for the field name
1644 if let Some(f) = recovery_field {
1647 e.span_label(struct_sp, "while parsing this struct");
1649 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
1650 self.eat(&token::Comma);
1655 let span = lo.to(self.token.span);
1656 self.expect(&token::CloseDelim(token::Brace))?;
1657 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
1660 /// Parse ident (COLON expr)?
1661 fn parse_field(&mut self) -> PResult<'a, Field> {
1662 let attrs = self.parse_outer_attributes()?;
1663 let lo = self.token.span;
1665 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1666 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
1667 t == &token::Colon || t == &token::Eq
1669 let fieldname = self.parse_field_name()?;
1671 // Check for an equals token. This means the source incorrectly attempts to
1672 // initialize a field with an eq rather than a colon.
1673 if self.token == token::Eq {
1675 .struct_span_err(self.token.span, "expected `:`, found `=`")
1677 fieldname.span.shrink_to_hi().to(self.token.span),
1678 "replace equals symbol with a colon",
1680 Applicability::MachineApplicable,
1685 (fieldname, self.parse_expr()?, false)
1687 let fieldname = self.parse_ident_common(false)?;
1689 // Mimic `x: x` for the `x` field shorthand.
1690 let path = ast::Path::from_ident(fieldname);
1691 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
1692 (fieldname, expr, true)
1696 span: lo.to(expr.span),
1699 attrs: attrs.into(),
1700 id: ast::DUMMY_NODE_ID,
1704 fn err_dotdotdot_syntax(&self, span: Span) {
1705 self.struct_span_err(span, "unexpected token: `...`")
1708 "use `..` for an exclusive range", "..".to_owned(),
1709 Applicability::MaybeIncorrect
1713 "or `..=` for an inclusive range", "..=".to_owned(),
1714 Applicability::MaybeIncorrect
1719 fn err_larrow_operator(&self, span: Span) {
1720 self.struct_span_err(
1722 "unexpected token: `<-`"
1725 "if you meant to write a comparison against a negative value, add a \
1726 space in between `<` and `-`",
1728 Applicability::MaybeIncorrect
1732 fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
1733 ExprKind::AssignOp(binop, lhs, rhs)
1738 start: Option<P<Expr>>,
1739 end: Option<P<Expr>>,
1741 ) -> PResult<'a, ExprKind> {
1742 if end.is_none() && limits == RangeLimits::Closed {
1743 Err(self.span_fatal_err(self.token.span, Error::InclusiveRangeWithNoEnd))
1745 Ok(ExprKind::Range(start, end, limits))
1749 fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
1750 ExprKind::Unary(unop, expr)
1753 fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
1754 ExprKind::Binary(binop, lhs, rhs)
1757 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
1758 ExprKind::Index(expr, idx)
1761 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
1762 ExprKind::Call(f, args)
1765 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
1766 let span = lo.to(self.prev_span);
1767 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), ThinVec::new());
1768 self.recover_from_await_method_call();
1772 crate fn mk_expr(&self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1773 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })