2 Parser, PResult, Restrictions, PrevTokenKind, TokenType, PathStyle, BlockMode, SemiColonMode,
3 SeqSep, TokenExpectType,
5 use super::pat::{GateOr, PARAM_EXPECTED};
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,
12 use crate::maybe_recover_from_interpolated_ty_qpath;
13 use crate::parse::classify;
14 use crate::parse::token::{self, Token};
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;
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 /// Parses 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 /// Parses 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),
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())
744 /// At the bottom (top?) of the precedence hierarchy,
745 /// Parses things like parenthesized exprs, macros, `return`, etc.
747 /// N.B., this does not parse outer attributes, and is private because it only works
748 /// correctly if called from `parse_dot_or_call_expr()`.
749 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
750 maybe_recover_from_interpolated_ty_qpath!(self, true);
751 maybe_whole_expr!(self);
753 // Outer attributes are already parsed and will be
754 // added to the return value after the fact.
756 // Therefore, prevent sub-parser from parsing
757 // attributes by giving them a empty "already-parsed" list.
758 let mut attrs = ThinVec::new();
760 let lo = self.token.span;
761 let mut hi = self.token.span;
765 macro_rules! parse_lit {
767 match self.parse_lit() {
770 ex = ExprKind::Lit(literal);
773 self.cancel(&mut err);
774 return Err(self.expected_expression_found());
780 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
781 match self.token.kind {
782 // This match arm is a special-case of the `_` match arm below and
783 // could be removed without changing functionality, but it's faster
784 // to have it here, especially for programs with large constants.
785 token::Literal(_) => {
788 token::OpenDelim(token::Paren) => {
791 attrs.extend(self.parse_inner_attributes()?);
793 // `(e)` is parenthesized `e`.
794 // `(e,)` is a tuple with only one field, `e`.
796 let mut trailing_comma = false;
797 let mut recovered = false;
798 while self.token != token::CloseDelim(token::Paren) {
799 es.push(match self.parse_expr() {
802 // Recover from parse error in tuple list.
803 match self.token.kind {
804 token::Ident(name, false)
805 if name == kw::Underscore && self.look_ahead(1, |t| {
808 // Special-case handling of `Foo<(_, _, _)>`
810 let sp = self.token.span;
812 self.mk_expr(sp, ExprKind::Err, ThinVec::new())
815 self.recover_seq_parse_error(token::Paren, lo, Err(err)),
820 recovered = self.expect_one_of(
822 &[token::Comma, token::CloseDelim(token::Paren)],
824 if self.eat(&token::Comma) {
825 trailing_comma = true;
827 trailing_comma = false;
836 ex = if es.len() == 1 && !trailing_comma {
837 ExprKind::Paren(es.into_iter().nth(0).unwrap())
842 token::OpenDelim(token::Brace) => {
843 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
845 token::BinOp(token::Or) | token::OrOr => {
846 return self.parse_closure_expr(attrs);
848 token::OpenDelim(token::Bracket) => {
851 attrs.extend(self.parse_inner_attributes()?);
853 if self.eat(&token::CloseDelim(token::Bracket)) {
855 ex = ExprKind::Array(Vec::new());
858 let first_expr = self.parse_expr()?;
859 if self.eat(&token::Semi) {
860 // Repeating array syntax: `[ 0; 512 ]`
861 let count = AnonConst {
863 value: self.parse_expr()?,
865 self.expect(&token::CloseDelim(token::Bracket))?;
866 ex = ExprKind::Repeat(first_expr, count);
867 } else if self.eat(&token::Comma) {
868 // Vector with two or more elements
869 let remaining_exprs = self.parse_seq_to_end(
870 &token::CloseDelim(token::Bracket),
871 SeqSep::trailing_allowed(token::Comma),
872 |p| Ok(p.parse_expr()?)
874 let mut exprs = vec![first_expr];
875 exprs.extend(remaining_exprs);
876 ex = ExprKind::Array(exprs);
878 // Vector with one element
879 self.expect(&token::CloseDelim(token::Bracket))?;
880 ex = ExprKind::Array(vec![first_expr]);
887 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
889 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
891 if self.token.is_path_start() {
892 let path = self.parse_path(PathStyle::Expr)?;
894 // `!`, as an operator, is prefix, so we know this isn't that.
895 if self.eat(&token::Not) {
896 // MACRO INVOCATION expression
897 let (delim, tts) = self.expect_delimited_token_tree()?;
899 ex = ExprKind::Mac(Mac {
904 prior_type_ascription: self.last_type_ascription,
906 } else if self.check(&token::OpenDelim(token::Brace)) {
907 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
911 ex = ExprKind::Path(None, path);
915 ex = ExprKind::Path(None, path);
918 let expr = self.mk_expr(lo.to(hi), ex, attrs);
919 return self.maybe_recover_from_bad_qpath(expr, true);
921 if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
922 return self.parse_closure_expr(attrs);
924 if self.eat_keyword(kw::If) {
925 return self.parse_if_expr(attrs);
927 if self.eat_keyword(kw::For) {
928 let lo = self.prev_span;
929 return self.parse_for_expr(None, lo, attrs);
931 if self.eat_keyword(kw::While) {
932 let lo = self.prev_span;
933 return self.parse_while_expr(None, lo, attrs);
935 if let Some(label) = self.eat_label() {
936 let lo = label.ident.span;
937 self.expect(&token::Colon)?;
938 if self.eat_keyword(kw::While) {
939 return self.parse_while_expr(Some(label), lo, attrs)
941 if self.eat_keyword(kw::For) {
942 return self.parse_for_expr(Some(label), lo, attrs)
944 if self.eat_keyword(kw::Loop) {
945 return self.parse_loop_expr(Some(label), lo, attrs)
947 if self.token == token::OpenDelim(token::Brace) {
948 return self.parse_block_expr(Some(label),
950 BlockCheckMode::Default,
953 let msg = "expected `while`, `for`, `loop` or `{` after a label";
954 let mut err = self.fatal(msg);
955 err.span_label(self.token.span, msg);
958 if self.eat_keyword(kw::Loop) {
959 let lo = self.prev_span;
960 return self.parse_loop_expr(None, lo, attrs);
962 if self.eat_keyword(kw::Continue) {
963 let label = self.eat_label();
964 let ex = ExprKind::Continue(label);
965 let hi = self.prev_span;
966 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
968 if self.eat_keyword(kw::Match) {
969 let match_sp = self.prev_span;
970 return self.parse_match_expr(attrs).map_err(|mut err| {
971 err.span_label(match_sp, "while parsing this match expression");
975 if self.eat_keyword(kw::Unsafe) {
976 return self.parse_block_expr(
979 BlockCheckMode::Unsafe(ast::UserProvided),
982 if self.is_do_catch_block() {
983 let mut db = self.fatal("found removed `do catch` syntax");
984 db.help("following RFC #2388, the new non-placeholder syntax is `try`");
987 if self.is_try_block() {
988 let lo = self.token.span;
989 assert!(self.eat_keyword(kw::Try));
990 return self.parse_try_block(lo, attrs);
993 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
994 let is_span_rust_2018 = self.token.span.rust_2018();
995 if is_span_rust_2018 && self.check_keyword(kw::Async) {
996 return if self.is_async_block() { // Check for `async {` and `async move {`.
997 self.parse_async_block(attrs)
999 self.parse_closure_expr(attrs)
1002 if self.eat_keyword(kw::Return) {
1003 if self.token.can_begin_expr() {
1004 let e = self.parse_expr()?;
1006 ex = ExprKind::Ret(Some(e));
1008 ex = ExprKind::Ret(None);
1010 } else if self.eat_keyword(kw::Break) {
1011 let label = self.eat_label();
1012 let e = if self.token.can_begin_expr()
1013 && !(self.token == token::OpenDelim(token::Brace)
1014 && self.restrictions.contains(
1015 Restrictions::NO_STRUCT_LITERAL)) {
1016 Some(self.parse_expr()?)
1020 ex = ExprKind::Break(label, e);
1021 hi = self.prev_span;
1022 } else if self.eat_keyword(kw::Yield) {
1023 if self.token.can_begin_expr() {
1024 let e = self.parse_expr()?;
1026 ex = ExprKind::Yield(Some(e));
1028 ex = ExprKind::Yield(None);
1031 let span = lo.to(hi);
1032 self.sess.gated_spans.yields.borrow_mut().push(span);
1033 } else if self.eat_keyword(kw::Let) {
1034 return self.parse_let_expr(attrs);
1035 } else if is_span_rust_2018 && self.eat_keyword(kw::Await) {
1036 let (await_hi, e_kind) = self.parse_incorrect_await_syntax(lo, self.prev_span)?;
1040 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1041 // Don't complain about bare semicolons after unclosed braces
1042 // recovery in order to keep the error count down. Fixing the
1043 // delimiters will possibly also fix the bare semicolon found in
1044 // expression context. For example, silence the following error:
1046 // error: expected expression, found `;`
1050 // | ^ expected expression
1052 return Ok(self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()));
1059 let expr = self.mk_expr(lo.to(hi), ex, attrs);
1060 self.maybe_recover_from_bad_qpath(expr, true)
1063 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1064 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1065 maybe_whole_expr!(self);
1067 let minus_lo = self.token.span;
1068 let minus_present = self.eat(&token::BinOp(token::Minus));
1069 let lo = self.token.span;
1070 let literal = self.parse_lit()?;
1071 let hi = self.prev_span;
1072 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1075 let minus_hi = self.prev_span;
1076 let unary = self.mk_unary(UnOp::Neg, expr);
1077 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1083 /// Parses a block or unsafe block.
1084 crate fn parse_block_expr(
1086 opt_label: Option<Label>,
1088 blk_mode: BlockCheckMode,
1089 outer_attrs: ThinVec<Attribute>,
1090 ) -> PResult<'a, P<Expr>> {
1091 self.expect(&token::OpenDelim(token::Brace))?;
1093 let mut attrs = outer_attrs;
1094 attrs.extend(self.parse_inner_attributes()?);
1096 let blk = self.parse_block_tail(lo, blk_mode)?;
1097 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs))
1100 /// Parses a closure expression (e.g., `move |args| expr`).
1101 fn parse_closure_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1102 let lo = self.token.span;
1104 let movability = if self.eat_keyword(kw::Static) {
1110 let asyncness = if self.token.span.rust_2018() {
1111 self.parse_asyncness()
1115 if asyncness.is_async() {
1116 // Feature-gate `async ||` closures.
1117 self.sess.gated_spans.async_closure.borrow_mut().push(self.prev_span);
1120 let capture_clause = self.parse_capture_clause();
1121 let decl = self.parse_fn_block_decl()?;
1122 let decl_hi = self.prev_span;
1123 let body = match decl.output {
1124 FunctionRetTy::Default(_) => {
1125 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
1126 self.parse_expr_res(restrictions, None)?
1129 // If an explicit return type is given, require a block to appear (RFC 968).
1130 let body_lo = self.token.span;
1131 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
1137 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
1141 /// Parses an optional `move` prefix to a closure lke construct.
1142 fn parse_capture_clause(&mut self) -> CaptureBy {
1143 if self.eat_keyword(kw::Move) {
1150 /// Parses the `|arg, arg|` header of a closure.
1151 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
1152 let inputs_captures = {
1153 if self.eat(&token::OrOr) {
1156 self.expect(&token::BinOp(token::Or))?;
1157 let args = self.parse_seq_to_before_tokens(
1158 &[&token::BinOp(token::Or), &token::OrOr],
1159 SeqSep::trailing_allowed(token::Comma),
1160 TokenExpectType::NoExpect,
1161 |p| p.parse_fn_block_param()
1167 let output = self.parse_ret_ty(true)?;
1170 inputs: inputs_captures,
1176 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1177 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
1178 let lo = self.token.span;
1179 let attrs = self.parse_param_attributes()?;
1180 let pat = self.parse_pat(PARAM_EXPECTED)?;
1181 let t = if self.eat(&token::Colon) {
1186 node: TyKind::Infer,
1187 span: self.prev_span,
1190 let span = lo.to(self.token.span);
1192 attrs: attrs.into(),
1200 /// Parses an `if` expression (`if` token already eaten).
1201 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1202 let lo = self.prev_span;
1203 let cond = self.parse_cond_expr()?;
1205 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1206 // verify that the last statement is either an implicit return (no `;`) or an explicit
1207 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1208 // the dead code lint.
1209 if self.eat_keyword(kw::Else) || !cond.returns() {
1210 let sp = self.sess.source_map().next_point(lo);
1211 let mut err = self.diagnostic()
1212 .struct_span_err(sp, "missing condition for `if` expression");
1213 err.span_label(sp, "expected if condition here");
1216 let not_block = self.token != token::OpenDelim(token::Brace);
1217 let thn = self.parse_block().map_err(|mut err| {
1219 err.span_label(lo, "this `if` statement has a condition, but no block");
1223 let mut els: Option<P<Expr>> = None;
1224 let mut hi = thn.span;
1225 if self.eat_keyword(kw::Else) {
1226 let elexpr = self.parse_else_expr()?;
1230 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
1233 /// Parses the condition of a `if` or `while` expression.
1234 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
1235 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1237 if let ExprKind::Let(..) = cond.node {
1238 // Remove the last feature gating of a `let` expression since it's stable.
1239 let last = self.sess.gated_spans.let_chains.borrow_mut().pop();
1240 debug_assert_eq!(cond.span, last.unwrap());
1246 /// Parses a `let $pat = $expr` pseudo-expression.
1247 /// The `let` token has already been eaten.
1248 fn parse_let_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1249 let lo = self.prev_span;
1250 let pat = self.parse_top_pat(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 /// Parses an `else { ... }` expression (`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 /// Parses 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 /// Parses `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 /// Parses a `match ... { ... }` expression (`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 let pat = self.parse_top_pat(GateOr::No)?;
1393 let guard = if self.eat_keyword(kw::If) {
1394 Some(self.parse_expr()?)
1398 let arrow_span = self.token.span;
1399 self.expect(&token::FatArrow)?;
1400 let arm_start_span = self.token.span;
1402 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
1403 .map_err(|mut err| {
1404 err.span_label(arrow_span, "while parsing the `match` arm starting here");
1408 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
1409 && self.token != token::CloseDelim(token::Brace);
1411 let hi = self.token.span;
1414 let cm = self.sess.source_map();
1415 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
1416 .map_err(|mut err| {
1417 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
1418 (Ok(ref expr_lines), Ok(ref arm_start_lines))
1419 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
1420 && expr_lines.lines.len() == 2
1421 && self.token == token::FatArrow => {
1422 // We check whether there's any trailing code in the parse span,
1423 // if there isn't, we very likely have the following:
1426 // | -- - missing comma
1430 // | - ^^ self.token.span
1432 // | parsed until here as `"y" & X`
1433 err.span_suggestion_short(
1434 cm.next_point(arm_start_span),
1435 "missing a comma here to end this `match` arm",
1437 Applicability::MachineApplicable
1441 err.span_label(arrow_span,
1442 "while parsing the `match` arm starting here");
1448 self.eat(&token::Comma);
1461 /// Parses a `try {...}` expression (`try` token already eaten).
1465 mut attrs: ThinVec<Attribute>
1466 ) -> PResult<'a, P<Expr>> {
1467 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1468 attrs.extend(iattrs);
1469 if self.eat_keyword(kw::Catch) {
1470 let mut error = self.struct_span_err(self.prev_span,
1471 "keyword `catch` cannot follow a `try` block");
1472 error.help("try using `match` on the result of the `try` block instead");
1476 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
1480 fn is_do_catch_block(&self) -> bool {
1481 self.token.is_keyword(kw::Do) &&
1482 self.is_keyword_ahead(1, &[kw::Catch]) &&
1483 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
1484 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1487 fn is_try_block(&self) -> bool {
1488 self.token.is_keyword(kw::Try) &&
1489 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
1490 self.token.span.rust_2018() &&
1491 // Prevent `while try {} {}`, `if try {} {} else {}`, etc.
1492 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1495 /// Parses an `async move? {...}` expression.
1496 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1497 let span_lo = self.token.span;
1498 self.expect_keyword(kw::Async)?;
1499 let capture_clause = self.parse_capture_clause();
1500 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1501 attrs.extend(iattrs);
1503 span_lo.to(body.span),
1504 ExprKind::Async(capture_clause, DUMMY_NODE_ID, body), attrs))
1507 fn is_async_block(&self) -> bool {
1508 self.token.is_keyword(kw::Async) &&
1511 self.is_keyword_ahead(1, &[kw::Move]) &&
1512 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
1514 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
1519 fn maybe_parse_struct_expr(
1523 attrs: &ThinVec<Attribute>,
1524 ) -> Option<PResult<'a, P<Expr>>> {
1525 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
1526 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
1527 // `{ ident, ` cannot start a block.
1528 self.look_ahead(2, |t| t == &token::Comma) ||
1529 self.look_ahead(2, |t| t == &token::Colon) && (
1530 // `{ ident: token, ` cannot start a block.
1531 self.look_ahead(4, |t| t == &token::Comma) ||
1532 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
1533 self.look_ahead(3, |t| !t.can_begin_type())
1537 if struct_allowed || certainly_not_a_block() {
1538 // This is a struct literal, but we don't can't accept them here.
1539 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
1540 if let (Ok(expr), false) = (&expr, struct_allowed) {
1541 self.struct_span_err(
1543 "struct literals are not allowed here",
1545 .multipart_suggestion(
1546 "surround the struct literal with parentheses",
1548 (lo.shrink_to_lo(), "(".to_string()),
1549 (expr.span.shrink_to_hi(), ")".to_string()),
1551 Applicability::MachineApplicable,
1560 pub(super) fn parse_struct_expr(
1564 mut attrs: ThinVec<Attribute>
1565 ) -> PResult<'a, P<Expr>> {
1566 let struct_sp = lo.to(self.prev_span);
1568 let mut fields = Vec::new();
1569 let mut base = None;
1571 attrs.extend(self.parse_inner_attributes()?);
1573 while self.token != token::CloseDelim(token::Brace) {
1574 if self.eat(&token::DotDot) {
1575 let exp_span = self.prev_span;
1576 match self.parse_expr() {
1582 self.recover_stmt();
1585 if self.token == token::Comma {
1586 self.struct_span_err(
1587 exp_span.to(self.prev_span),
1588 "cannot use a comma after the base struct",
1590 .span_suggestion_short(
1592 "remove this comma",
1594 Applicability::MachineApplicable
1596 .note("the base struct must always be the last field")
1598 self.recover_stmt();
1603 let mut recovery_field = None;
1604 if let token::Ident(name, _) = self.token.kind {
1605 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
1606 // Use in case of error after field-looking code: `S { foo: () with a }`.
1607 recovery_field = Some(ast::Field {
1608 ident: Ident::new(name, self.token.span),
1609 span: self.token.span,
1610 expr: self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()),
1611 is_shorthand: false,
1612 attrs: ThinVec::new(),
1617 let mut parsed_field = None;
1618 match self.parse_field() {
1619 Ok(f) => parsed_field = Some(f),
1621 e.span_label(struct_sp, "while parsing this struct");
1624 // If the next token is a comma, then try to parse
1625 // what comes next as additional fields, rather than
1626 // bailing out until next `}`.
1627 if self.token != token::Comma {
1628 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
1629 if self.token != token::Comma {
1636 match self.expect_one_of(&[token::Comma],
1637 &[token::CloseDelim(token::Brace)]) {
1638 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
1639 // Only include the field if there's no parse error for the field name.
1643 if let Some(f) = recovery_field {
1646 e.span_label(struct_sp, "while parsing this struct");
1648 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
1649 self.eat(&token::Comma);
1654 let span = lo.to(self.token.span);
1655 self.expect(&token::CloseDelim(token::Brace))?;
1656 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
1659 /// Parses `ident (COLON expr)?`.
1660 fn parse_field(&mut self) -> PResult<'a, Field> {
1661 let attrs = self.parse_outer_attributes()?;
1662 let lo = self.token.span;
1664 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1665 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
1666 t == &token::Colon || t == &token::Eq
1668 let fieldname = self.parse_field_name()?;
1670 // Check for an equals token. This means the source incorrectly attempts to
1671 // initialize a field with an eq rather than a colon.
1672 if self.token == token::Eq {
1674 .struct_span_err(self.token.span, "expected `:`, found `=`")
1676 fieldname.span.shrink_to_hi().to(self.token.span),
1677 "replace equals symbol with a colon",
1679 Applicability::MachineApplicable,
1684 (fieldname, self.parse_expr()?, false)
1686 let fieldname = self.parse_ident_common(false)?;
1688 // Mimic `x: x` for the `x` field shorthand.
1689 let path = ast::Path::from_ident(fieldname);
1690 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
1691 (fieldname, expr, true)
1695 span: lo.to(expr.span),
1698 attrs: attrs.into(),
1703 fn err_dotdotdot_syntax(&self, span: Span) {
1704 self.struct_span_err(span, "unexpected token: `...`")
1707 "use `..` for an exclusive range", "..".to_owned(),
1708 Applicability::MaybeIncorrect
1712 "or `..=` for an inclusive range", "..=".to_owned(),
1713 Applicability::MaybeIncorrect
1718 fn err_larrow_operator(&self, span: Span) {
1719 self.struct_span_err(
1721 "unexpected token: `<-`"
1724 "if you meant to write a comparison against a negative value, add a \
1725 space in between `<` and `-`",
1727 Applicability::MaybeIncorrect
1731 fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
1732 ExprKind::AssignOp(binop, lhs, rhs)
1737 start: Option<P<Expr>>,
1738 end: Option<P<Expr>>,
1740 ) -> PResult<'a, ExprKind> {
1741 if end.is_none() && limits == RangeLimits::Closed {
1742 Err(self.span_fatal_err(self.token.span, Error::InclusiveRangeWithNoEnd))
1744 Ok(ExprKind::Range(start, end, limits))
1748 fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
1749 ExprKind::Unary(unop, expr)
1752 fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
1753 ExprKind::Binary(binop, lhs, rhs)
1756 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
1757 ExprKind::Index(expr, idx)
1760 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
1761 ExprKind::Call(f, args)
1764 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
1765 let span = lo.to(self.prev_span);
1766 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), ThinVec::new());
1767 self.recover_from_await_method_call();
1771 crate fn mk_expr(&self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1772 P(Expr { node, span, attrs, id: DUMMY_NODE_ID })