1 use super::{Parser, Restrictions, PrevTokenKind, TokenType, PathStyle, BlockMode};
2 use super::{SemiColonMode, SeqSep, TokenExpectType};
3 use super::pat::{GateOr, PARAM_EXPECTED};
4 use super::diagnostics::Error;
5 use crate::maybe_recover_from_interpolated_ty_qpath;
7 use rustc_data_structures::thin_vec::ThinVec;
8 use rustc_errors::{PResult, Applicability};
9 use syntax::ast::{self, DUMMY_NODE_ID, Attribute, AttrStyle, Ident, CaptureBy, BlockCheckMode};
10 use syntax::ast::{Expr, ExprKind, RangeLimits, Label, Movability, IsAsync, Arm, Ty, TyKind};
11 use syntax::ast::{FunctionRetTy, Param, FnDecl, BinOpKind, BinOp, UnOp, Mac, AnonConst, Field, Lit};
12 use syntax::token::{self, Token, TokenKind};
13 use syntax::print::pprust;
15 use syntax::util::classify;
16 use syntax::util::literal::LitError;
17 use syntax::util::parser::{AssocOp, Fixity, prec_let_scrutinee_needs_par};
18 use syntax_pos::source_map::{self, Span};
19 use syntax_pos::symbol::{kw, sym, Symbol};
22 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
23 /// dropped into the token stream, which happens while parsing the result of
24 /// macro expansion). Placement of these is not as complex as I feared it would
25 /// be. The important thing is to make sure that lookahead doesn't balk at
26 /// `token::Interpolated` tokens.
27 macro_rules! maybe_whole_expr {
29 if let token::Interpolated(nt) = &$p.token.kind {
31 token::NtExpr(e) | token::NtLiteral(e) => {
36 token::NtPath(path) => {
37 let path = path.clone();
40 $p.token.span, ExprKind::Path(None, path), ThinVec::new()
43 token::NtBlock(block) => {
44 let block = block.clone();
47 $p.token.span, ExprKind::Block(block, None), ThinVec::new()
50 // N.B., `NtIdent(ident)` is normalized to `Ident` in `fn bump`.
58 pub(super) enum LhsExpr {
60 AttributesParsed(ThinVec<Attribute>),
61 AlreadyParsed(P<Expr>),
64 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
65 /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
66 /// and `None` into `LhsExpr::NotYetParsed`.
68 /// This conversion does not allocate.
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 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
81 /// This conversion does not allocate.
82 fn from(expr: P<Expr>) -> Self {
83 LhsExpr::AlreadyParsed(expr)
88 /// Parses an expression.
90 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
91 self.parse_expr_res(Restrictions::empty(), None)
94 fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P<Expr>> {
95 match self.parse_expr() {
97 Err(mut err) => match self.token.kind {
98 token::Ident(name, false)
99 if name == kw::Underscore && self.look_ahead(1, |t| {
102 // Special-case handling of `foo(_, _, _)`
104 let sp = self.token.span;
106 Ok(self.mk_expr(sp, ExprKind::Err, ThinVec::new()))
113 /// Parses a sequence of expressions bounded by parentheses.
114 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
115 self.parse_paren_comma_seq(|p| {
116 p.parse_expr_catch_underscore()
120 /// Parses an expression, subject to the given restrictions.
122 pub(super) fn parse_expr_res(
125 already_parsed_attrs: Option<ThinVec<Attribute>>
126 ) -> PResult<'a, P<Expr>> {
127 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
130 /// Parses an associative expression.
132 /// This parses an expression accounting for associativity and precedence of the operators in
137 already_parsed_attrs: Option<ThinVec<Attribute>>,
138 ) -> PResult<'a, P<Expr>> {
139 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
142 /// Parses an associative expression with operators of at least `min_prec` precedence.
143 pub(super) fn parse_assoc_expr_with(
147 ) -> PResult<'a, P<Expr>> {
148 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
151 let attrs = match lhs {
152 LhsExpr::AttributesParsed(attrs) => Some(attrs),
155 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
156 return self.parse_prefix_range_expr(attrs);
158 self.parse_prefix_expr(attrs)?
161 let last_type_ascription_set = self.last_type_ascription.is_some();
163 if !self.should_continue_as_assoc_expr(&lhs) {
164 self.last_type_ascription = None;
168 self.expected_tokens.push(TokenType::Operator);
169 while let Some(op) = self.check_assoc_op() {
170 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
171 // it refers to. Interpolated identifiers are unwrapped early and never show up here
172 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
173 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
174 let lhs_span = match (self.prev_token_kind, &lhs.kind) {
175 (PrevTokenKind::Interpolated, _) => self.prev_span,
176 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
177 if path.segments.len() == 1 => self.prev_span,
181 let cur_op_span = self.token.span;
182 let restrictions = if op.is_assign_like() {
183 self.restrictions & Restrictions::NO_STRUCT_LITERAL
187 let prec = op.precedence();
191 // Check for deprecated `...` syntax
192 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
193 self.err_dotdotdot_syntax(self.token.span);
196 if self.token == token::LArrow {
197 self.err_larrow_operator(self.token.span);
201 if op.is_comparison() {
202 if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
207 if op == AssocOp::As {
208 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
210 } else if op == AssocOp::Colon {
211 let maybe_path = self.could_ascription_be_path(&lhs.kind);
212 self.last_type_ascription = Some((self.prev_span, maybe_path));
214 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
215 self.sess.gated_spans.gate(sym::type_ascription, lhs.span);
217 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
218 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
219 // generalise it to the Fixity::None code.
221 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
222 // two variants are handled with `parse_prefix_range_expr` call above.
223 let rhs = if self.is_at_start_of_range_notation_rhs() {
224 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
228 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
233 let limits = if op == AssocOp::DotDot {
234 RangeLimits::HalfOpen
239 let r = self.mk_range(Some(lhs), rhs, limits)?;
240 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
244 let fixity = op.fixity();
245 let prec_adjustment = match fixity {
248 // We currently have no non-associative operators that are not handled above by
249 // the special cases. The code is here only for future convenience.
252 let rhs = self.with_res(
253 restrictions - Restrictions::STMT_EXPR,
254 |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
257 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
258 // including the attributes.
262 .filter(|a| a.style == AttrStyle::Outer)
264 .map_or(lhs_span, |a| a.span);
265 let span = lhs_span.to(rhs.span);
267 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
268 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
269 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
270 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
271 AssocOp::Greater | AssocOp::GreaterEqual => {
272 let ast_op = op.to_ast_binop().unwrap();
273 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
274 self.mk_expr(span, binary, ThinVec::new())
276 AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
277 AssocOp::AssignOp(k) => {
279 token::Plus => BinOpKind::Add,
280 token::Minus => BinOpKind::Sub,
281 token::Star => BinOpKind::Mul,
282 token::Slash => BinOpKind::Div,
283 token::Percent => BinOpKind::Rem,
284 token::Caret => BinOpKind::BitXor,
285 token::And => BinOpKind::BitAnd,
286 token::Or => BinOpKind::BitOr,
287 token::Shl => BinOpKind::Shl,
288 token::Shr => BinOpKind::Shr,
290 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
291 self.mk_expr(span, aopexpr, ThinVec::new())
293 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
294 self.bug("AssocOp should have been handled by special case")
298 if let Fixity::None = fixity { break }
300 if last_type_ascription_set {
301 self.last_type_ascription = None;
306 fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
307 match (self.expr_is_complete(lhs), self.check_assoc_op()) {
308 // Semi-statement forms are odd:
309 // See https://github.com/rust-lang/rust/issues/29071
310 (true, None) => false,
311 (false, _) => true, // Continue parsing the expression.
312 // An exhaustive check is done in the following block, but these are checked first
313 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
314 // want to keep their span info to improve diagnostics in these cases in a later stage.
315 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
316 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
317 (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475)
318 (true, Some(AssocOp::Add)) // `{ 42 } + 42
319 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
320 // `if x { a } else { b } && if y { c } else { d }`
321 if !self.look_ahead(1, |t| t.is_reserved_ident()) => {
322 // These cases are ambiguous and can't be identified in the parser alone.
323 let sp = self.sess.source_map().start_point(self.token.span);
324 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
327 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => false,
329 self.error_found_expr_would_be_stmt(lhs);
335 /// We've found an expression that would be parsed as a statement,
336 /// but the next token implies this should be parsed as an expression.
337 /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
338 fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
339 let mut err = self.struct_span_err(self.token.span, &format!(
340 "expected expression, found `{}`",
341 pprust::token_to_string(&self.token),
343 err.span_label(self.token.span, "expected expression");
344 self.sess.expr_parentheses_needed(&mut err, lhs.span, Some(pprust::expr_to_string(&lhs)));
348 /// Possibly translate the current token to an associative operator.
349 /// The method does not advance the current token.
351 /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
352 fn check_assoc_op(&self) -> Option<AssocOp> {
353 match (AssocOp::from_token(&self.token), &self.token.kind) {
354 (op @ Some(_), _) => op,
355 (None, token::Ident(sym::and, false)) => {
356 self.error_bad_logical_op("and", "&&", "conjunction");
359 (None, token::Ident(sym::or, false)) => {
360 self.error_bad_logical_op("or", "||", "disjunction");
367 /// Error on `and` and `or` suggesting `&&` and `||` respectively.
368 fn error_bad_logical_op(&self, bad: &str, good: &str, english: &str) {
369 self.struct_span_err(self.token.span, &format!("`{}` is not a logical operator", bad))
372 &format!("instead of `{}`, use `{}` to perform logical {}", bad, good, english),
374 Applicability::MachineApplicable,
376 .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators")
380 /// Checks if this expression is a successfully parsed statement.
381 fn expr_is_complete(&self, e: &Expr) -> bool {
382 self.restrictions.contains(Restrictions::STMT_EXPR) &&
383 !classify::expr_requires_semi_to_be_stmt(e)
386 fn is_at_start_of_range_notation_rhs(&self) -> bool {
387 if self.token.can_begin_expr() {
388 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
389 if self.token == token::OpenDelim(token::Brace) {
390 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
398 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
399 fn parse_prefix_range_expr(
401 already_parsed_attrs: Option<ThinVec<Attribute>>
402 ) -> PResult<'a, P<Expr>> {
403 // Check for deprecated `...` syntax.
404 if self.token == token::DotDotDot {
405 self.err_dotdotdot_syntax(self.token.span);
408 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
409 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
411 let tok = self.token.clone();
412 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
413 let lo = self.token.span;
414 let mut hi = self.token.span;
416 let opt_end = if self.is_at_start_of_range_notation_rhs() {
417 // RHS must be parsed with more associativity than the dots.
418 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
419 Some(self.parse_assoc_expr_with(next_prec, LhsExpr::NotYetParsed)
427 let limits = if tok == token::DotDot {
428 RangeLimits::HalfOpen
433 let r = self.mk_range(None, opt_end, limits)?;
434 Ok(self.mk_expr(lo.to(hi), r, attrs))
437 /// Parses a prefix-unary-operator expr.
438 fn parse_prefix_expr(
440 already_parsed_attrs: Option<ThinVec<Attribute>>
441 ) -> PResult<'a, P<Expr>> {
442 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
443 let lo = self.token.span;
444 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
445 let (hi, ex) = match self.token.kind {
448 let e = self.parse_prefix_expr(None);
449 let (span, e) = self.interpolated_or_expr_span(e)?;
450 (lo.to(span), self.mk_unary(UnOp::Not, e))
452 // Suggest `!` for bitwise negation when encountering a `~`
455 let e = self.parse_prefix_expr(None);
456 let (span, e) = self.interpolated_or_expr_span(e)?;
457 let span_of_tilde = lo;
458 self.struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator")
459 .span_suggestion_short(
461 "use `!` to perform bitwise not",
463 Applicability::MachineApplicable
466 (lo.to(span), self.mk_unary(UnOp::Not, e))
468 token::BinOp(token::Minus) => {
470 let e = self.parse_prefix_expr(None);
471 let (span, e) = self.interpolated_or_expr_span(e)?;
472 (lo.to(span), self.mk_unary(UnOp::Neg, e))
474 token::BinOp(token::Star) => {
476 let e = self.parse_prefix_expr(None);
477 let (span, e) = self.interpolated_or_expr_span(e)?;
478 (lo.to(span), self.mk_unary(UnOp::Deref, e))
480 token::BinOp(token::And) | token::AndAnd => {
481 self.parse_address_of(lo)?
483 token::Ident(..) if self.token.is_keyword(kw::Box) => {
485 let e = self.parse_prefix_expr(None);
486 let (span, e) = self.interpolated_or_expr_span(e)?;
487 let span = lo.to(span);
488 self.sess.gated_spans.gate(sym::box_syntax, span);
489 (span, ExprKind::Box(e))
491 token::Ident(..) if self.token.is_ident_named(sym::not) => {
492 // `not` is just an ordinary identifier in Rust-the-language,
493 // but as `rustc`-the-compiler, we can issue clever diagnostics
494 // for confused users who really want to say `!`
495 let token_cannot_continue_expr = |t: &Token| match t.kind {
496 // These tokens can start an expression after `!`, but
497 // can't continue an expression after an ident
498 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
499 token::Literal(..) | token::Pound => true,
500 _ => t.is_whole_expr(),
502 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
503 if cannot_continue_expr {
505 // Emit the error ...
506 self.struct_span_err(
508 &format!("unexpected {} after identifier",self.this_token_descr())
510 .span_suggestion_short(
511 // Span the `not` plus trailing whitespace to avoid
512 // trailing whitespace after the `!` in our suggestion
513 self.sess.source_map()
514 .span_until_non_whitespace(lo.to(self.token.span)),
515 "use `!` to perform logical negation",
517 Applicability::MachineApplicable
520 // —and recover! (just as if we were in the block
521 // for the `token::Not` arm)
522 let e = self.parse_prefix_expr(None);
523 let (span, e) = self.interpolated_or_expr_span(e)?;
524 (lo.to(span), self.mk_unary(UnOp::Not, e))
526 return self.parse_dot_or_call_expr(Some(attrs));
529 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
531 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
534 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
535 fn interpolated_or_expr_span(
537 expr: PResult<'a, P<Expr>>,
538 ) -> PResult<'a, (Span, P<Expr>)> {
540 if self.prev_token_kind == PrevTokenKind::Interpolated {
548 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
549 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
550 -> PResult<'a, P<Expr>> {
551 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
552 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
555 // Save the state of the parser before parsing type normally, in case there is a
556 // LessThan comparison after this cast.
557 let parser_snapshot_before_type = self.clone();
558 match self.parse_ty_no_plus() {
560 Ok(mk_expr(self, rhs))
562 Err(mut type_err) => {
563 // Rewind to before attempting to parse the type with generics, to recover
564 // from situations like `x as usize < y` in which we first tried to parse
565 // `usize < y` as a type with generic arguments.
566 let parser_snapshot_after_type = self.clone();
567 mem::replace(self, parser_snapshot_before_type);
569 match self.parse_path(PathStyle::Expr) {
571 let (op_noun, op_verb) = match self.token.kind {
572 token::Lt => ("comparison", "comparing"),
573 token::BinOp(token::Shl) => ("shift", "shifting"),
575 // We can end up here even without `<` being the next token, for
576 // example because `parse_ty_no_plus` returns `Err` on keywords,
577 // but `parse_path` returns `Ok` on them due to error recovery.
578 // Return original error and parser state.
579 mem::replace(self, parser_snapshot_after_type);
580 return Err(type_err);
584 // Successfully parsed the type path leaving a `<` yet to parse.
587 // Report non-fatal diagnostics, keep `x as usize` as an expression
588 // in AST and continue parsing.
590 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
591 pprust::path_to_string(&path),
594 let span_after_type = parser_snapshot_after_type.token.span;
595 let expr = mk_expr(self, P(Ty {
597 kind: TyKind::Path(None, path),
601 let expr_str = self.span_to_snippet(expr.span)
602 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
604 self.struct_span_err(self.token.span, &msg)
606 self.look_ahead(1, |t| t.span).to(span_after_type),
607 "interpreted as generic arguments"
609 .span_label(self.token.span, format!("not interpreted as {}", op_noun))
612 &format!("try {} the cast value", op_verb),
613 format!("({})", expr_str),
614 Applicability::MachineApplicable,
620 Err(mut path_err) => {
621 // Couldn't parse as a path, return original error and parser state.
623 mem::replace(self, parser_snapshot_after_type);
631 /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
632 fn parse_address_of(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
634 let (k, m) = if self.check_keyword(kw::Raw)
635 && self.look_ahead(1, Token::is_mutability)
637 let found_raw = self.eat_keyword(kw::Raw);
639 let mutability = self.parse_const_or_mut().unwrap();
640 self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_span));
641 (ast::BorrowKind::Raw, mutability)
643 (ast::BorrowKind::Ref, self.parse_mutability())
645 let e = self.parse_prefix_expr(None);
646 let (span, e) = self.interpolated_or_expr_span(e)?;
647 Ok((lo.to(span), ExprKind::AddrOf(k, m, e)))
650 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
651 fn parse_dot_or_call_expr(
653 already_parsed_attrs: Option<ThinVec<Attribute>>,
654 ) -> PResult<'a, P<Expr>> {
655 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
657 let b = self.parse_bottom_expr();
658 let (span, b) = self.interpolated_or_expr_span(b)?;
659 self.parse_dot_or_call_expr_with(b, span, attrs)
662 pub(super) fn parse_dot_or_call_expr_with(
666 mut attrs: ThinVec<Attribute>,
667 ) -> PResult<'a, P<Expr>> {
668 // Stitch the list of outer attributes onto the return value.
669 // A little bit ugly, but the best way given the current code
671 self.parse_dot_or_call_expr_with_(e0, lo).map(|expr|
672 expr.map(|mut expr| {
673 attrs.extend::<Vec<_>>(expr.attrs.into());
676 ExprKind::If(..) if !expr.attrs.is_empty() => {
677 // Just point to the first attribute in there...
678 let span = expr.attrs[0].span;
679 self.span_err(span, "attributes are not yet allowed on `if` expressions");
688 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
693 while self.eat(&token::Question) {
694 let hi = self.prev_span;
695 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
699 if self.eat(&token::Dot) {
700 match self.token.kind {
701 token::Ident(..) => {
702 e = self.parse_dot_suffix(e, lo)?;
704 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
705 let span = self.token.span;
707 let field = ExprKind::Field(e, Ident::new(symbol, span));
708 e = self.mk_expr(lo.to(span), field, ThinVec::new());
710 self.expect_no_suffix(span, "a tuple index", suffix);
712 token::Literal(token::Lit { kind: token::Float, symbol, .. }) => {
714 let fstr = symbol.as_str();
715 let msg = format!("unexpected token: `{}`", symbol);
716 let mut err = self.diagnostic().struct_span_err(self.prev_span, &msg);
717 err.span_label(self.prev_span, "unexpected token");
718 if fstr.chars().all(|x| "0123456789.".contains(x)) {
719 let float = match fstr.parse::<f64>().ok() {
723 let sugg = pprust::to_string(|s| {
727 s.print_usize(float.trunc() as usize);
730 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
733 lo.to(self.prev_span),
734 "try parenthesizing the first index",
736 Applicability::MachineApplicable
743 // FIXME Could factor this out into non_fatal_unexpected or something.
744 let actual = self.this_token_to_string();
745 self.span_err(self.token.span, &format!("unexpected token: `{}`", actual));
750 if self.expr_is_complete(&e) { break; }
751 match self.token.kind {
753 token::OpenDelim(token::Paren) => {
754 let seq = self.parse_paren_expr_seq().map(|es| {
755 let nd = self.mk_call(e, es);
756 let hi = self.prev_span;
757 self.mk_expr(lo.to(hi), nd, ThinVec::new())
759 e = self.recover_seq_parse_error(token::Paren, lo, seq);
763 // Could be either an index expression or a slicing expression.
764 token::OpenDelim(token::Bracket) => {
766 let ix = self.parse_expr()?;
767 hi = self.token.span;
768 self.expect(&token::CloseDelim(token::Bracket))?;
769 let index = self.mk_index(e, ix);
770 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
778 /// Assuming we have just parsed `.`, continue parsing into an expression.
779 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
780 if self.token.span.rust_2018() && self.eat_keyword(kw::Await) {
781 return self.mk_await_expr(self_arg, lo);
784 let segment = self.parse_path_segment(PathStyle::Expr)?;
785 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
787 Ok(match self.token.kind {
788 token::OpenDelim(token::Paren) => {
789 // Method call `expr.f()`
790 let mut args = self.parse_paren_expr_seq()?;
791 args.insert(0, self_arg);
793 let span = lo.to(self.prev_span);
794 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
797 // Field access `expr.f`
798 if let Some(args) = segment.args {
799 self.span_err(args.span(),
800 "field expressions may not have generic arguments");
803 let span = lo.to(self.prev_span);
804 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
809 /// At the bottom (top?) of the precedence hierarchy,
810 /// Parses things like parenthesized exprs, macros, `return`, etc.
812 /// N.B., this does not parse outer attributes, and is private because it only works
813 /// correctly if called from `parse_dot_or_call_expr()`.
814 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
815 maybe_recover_from_interpolated_ty_qpath!(self, true);
816 maybe_whole_expr!(self);
818 // Outer attributes are already parsed and will be
819 // added to the return value after the fact.
821 // Therefore, prevent sub-parser from parsing
822 // attributes by giving them a empty "already-parsed" list.
823 let attrs = ThinVec::new();
825 let lo = self.token.span;
827 macro_rules! parse_lit {
829 match self.parse_opt_lit() {
830 Some(literal) => (self.prev_span, ExprKind::Lit(literal)),
831 None => return Err(self.expected_expression_found()),
836 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
837 let (hi, ex) = match self.token.kind {
838 // This match arm is a special-case of the `_` match arm below and
839 // could be removed without changing functionality, but it's faster
840 // to have it here, especially for programs with large constants.
841 token::Literal(_) => parse_lit!(),
842 token::OpenDelim(token::Paren) => return self.parse_tuple_parens_expr(attrs),
843 token::OpenDelim(token::Brace) => {
844 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
846 token::BinOp(token::Or) | token::OrOr => return self.parse_closure_expr(attrs),
847 token::OpenDelim(token::Bracket) => return self.parse_array_or_repeat_expr(attrs),
850 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
852 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
854 if self.token.is_path_start() {
855 return self.parse_path_start_expr(attrs);
857 if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
858 return self.parse_closure_expr(attrs);
860 if self.eat_keyword(kw::If) {
861 return self.parse_if_expr(attrs);
863 if self.eat_keyword(kw::For) {
864 return self.parse_for_expr(None, self.prev_span, attrs);
866 if self.eat_keyword(kw::While) {
867 return self.parse_while_expr(None, self.prev_span, attrs);
869 if let Some(label) = self.eat_label() {
870 return self.parse_labeled_expr(label, attrs);
872 if self.eat_keyword(kw::Loop) {
873 return self.parse_loop_expr(None, self.prev_span, attrs);
875 if self.eat_keyword(kw::Continue) {
876 let kind = ExprKind::Continue(self.eat_label());
877 return Ok(self.mk_expr(lo.to(self.prev_span), kind, attrs));
879 if self.eat_keyword(kw::Match) {
880 let match_sp = self.prev_span;
881 return self.parse_match_expr(attrs).map_err(|mut err| {
882 err.span_label(match_sp, "while parsing this match expression");
886 if self.eat_keyword(kw::Unsafe) {
887 let mode = BlockCheckMode::Unsafe(ast::UserProvided);
888 return self.parse_block_expr(None, lo, mode, attrs);
890 if self.is_do_catch_block() {
891 return self.recover_do_catch(attrs);
893 if self.is_try_block() {
894 self.expect_keyword(kw::Try)?;
895 return self.parse_try_block(lo, attrs);
898 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
899 let is_span_rust_2018 = self.token.span.rust_2018();
900 if is_span_rust_2018 && self.check_keyword(kw::Async) {
901 return if self.is_async_block() { // Check for `async {` and `async move {`.
902 self.parse_async_block(attrs)
904 self.parse_closure_expr(attrs)
907 if self.eat_keyword(kw::Return) {
908 return self.parse_return_expr(attrs);
909 } else if self.eat_keyword(kw::Break) {
910 return self.parse_break_expr(attrs);
911 } else if self.eat_keyword(kw::Yield) {
912 return self.parse_yield_expr(attrs);
913 } else if self.eat_keyword(kw::Let) {
914 return self.parse_let_expr(attrs);
915 } else if is_span_rust_2018 && self.eat_keyword(kw::Await) {
916 return self.recover_incorrect_await_syntax(lo, self.prev_span, attrs);
917 } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
918 // Don't complain about bare semicolons after unclosed braces
919 // recovery in order to keep the error count down. Fixing the
920 // delimiters will possibly also fix the bare semicolon found in
921 // expression context. For example, silence the following error:
923 // error: expected expression, found `;`
927 // | ^ expected expression
929 return Ok(self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()));
936 let expr = self.mk_expr(lo.to(hi), ex, attrs);
937 self.maybe_recover_from_bad_qpath(expr, true)
940 fn parse_tuple_parens_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
941 let lo = self.token.span;
942 let mut first = true;
943 let parse_leading_attr_expr = |p: &mut Self| {
945 // `(#![foo] a, b, ...)` is OK...
946 attrs.extend(p.parse_inner_attributes()?);
947 // ...but not `(a, #![foo] b, ...)`.
950 p.parse_expr_catch_underscore()
952 let (es, trailing_comma) = match self.parse_paren_comma_seq(parse_leading_attr_expr) {
954 Err(err) => return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err))),
956 let kind = if es.len() == 1 && !trailing_comma {
957 // `(e)` is parenthesized `e`.
958 ExprKind::Paren(es.into_iter().nth(0).unwrap())
960 // `(e,)` is a tuple with only one field, `e`.
963 let expr = self.mk_expr(lo.to(self.prev_span), kind, attrs);
964 self.maybe_recover_from_bad_qpath(expr, true)
967 fn parse_array_or_repeat_expr(
969 mut attrs: ThinVec<Attribute>,
970 ) -> PResult<'a, P<Expr>> {
971 let lo = self.token.span;
974 attrs.extend(self.parse_inner_attributes()?);
976 let kind = if self.eat(&token::CloseDelim(token::Bracket)) {
978 ExprKind::Array(Vec::new())
981 let first_expr = self.parse_expr()?;
982 if self.eat(&token::Semi) {
983 // Repeating array syntax: `[ 0; 512 ]`
984 let count = AnonConst {
986 value: self.parse_expr()?,
988 self.expect(&token::CloseDelim(token::Bracket))?;
989 ExprKind::Repeat(first_expr, count)
990 } else if self.eat(&token::Comma) {
991 // Vector with two or more elements.
992 let remaining_exprs = self.parse_seq_to_end(
993 &token::CloseDelim(token::Bracket),
994 SeqSep::trailing_allowed(token::Comma),
995 |p| Ok(p.parse_expr()?)
997 let mut exprs = vec![first_expr];
998 exprs.extend(remaining_exprs);
999 ExprKind::Array(exprs)
1001 // Vector with one element
1002 self.expect(&token::CloseDelim(token::Bracket))?;
1003 ExprKind::Array(vec![first_expr])
1006 let expr = self.mk_expr(lo.to(self.prev_span), kind, attrs);
1007 self.maybe_recover_from_bad_qpath(expr, true)
1010 fn parse_path_start_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1011 let lo = self.token.span;
1012 let path = self.parse_path(PathStyle::Expr)?;
1014 // `!`, as an operator, is prefix, so we know this isn't that.
1015 let (hi, kind) = if self.eat(&token::Not) {
1016 // MACRO INVOCATION expression
1019 args: self.parse_mac_args()?,
1020 prior_type_ascription: self.last_type_ascription,
1022 (self.prev_span, ExprKind::Mac(mac))
1023 } else if self.check(&token::OpenDelim(token::Brace)) {
1024 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
1027 (path.span, ExprKind::Path(None, path))
1030 (path.span, ExprKind::Path(None, path))
1033 let expr = self.mk_expr(lo.to(hi), kind, attrs);
1034 self.maybe_recover_from_bad_qpath(expr, true)
1037 fn parse_labeled_expr(
1040 attrs: ThinVec<Attribute>,
1041 ) -> PResult<'a, P<Expr>> {
1042 let lo = label.ident.span;
1043 self.expect(&token::Colon)?;
1044 if self.eat_keyword(kw::While) {
1045 return self.parse_while_expr(Some(label), lo, attrs)
1047 if self.eat_keyword(kw::For) {
1048 return self.parse_for_expr(Some(label), lo, attrs)
1050 if self.eat_keyword(kw::Loop) {
1051 return self.parse_loop_expr(Some(label), lo, attrs)
1053 if self.token == token::OpenDelim(token::Brace) {
1054 return self.parse_block_expr(Some(label), lo, BlockCheckMode::Default, attrs);
1057 let msg = "expected `while`, `for`, `loop` or `{` after a label";
1058 self.struct_span_err(self.token.span, msg)
1059 .span_label(self.token.span, msg)
1061 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1065 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1066 fn recover_do_catch(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1067 let lo = self.token.span;
1069 self.bump(); // `do`
1070 self.bump(); // `catch`
1072 let span_dc = lo.to(self.prev_span);
1073 self.struct_span_err(span_dc, "found removed `do catch` syntax")
1076 "replace with the new syntax",
1078 Applicability::MachineApplicable,
1080 .note("following RFC #2388, the new non-placeholder syntax is `try`")
1083 self.parse_try_block(lo, attrs)
1086 /// Parse an expression if the token can begin one.
1087 fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1088 Ok(if self.token.can_begin_expr() {
1089 Some(self.parse_expr()?)
1095 /// Parse `"return" expr?`.
1096 fn parse_return_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1097 let lo = self.prev_span;
1098 let kind = ExprKind::Ret(self.parse_expr_opt()?);
1099 let expr = self.mk_expr(lo.to(self.prev_span), kind, attrs);
1100 self.maybe_recover_from_bad_qpath(expr, true)
1103 /// Parse `"('label ":")? break expr?`.
1104 fn parse_break_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1105 let lo = self.prev_span;
1106 let label = self.eat_label();
1107 let kind = if self.token != token::OpenDelim(token::Brace)
1108 || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1110 self.parse_expr_opt()?
1114 let expr = self.mk_expr(lo.to(self.prev_span), ExprKind::Break(label, kind), attrs);
1115 self.maybe_recover_from_bad_qpath(expr, true)
1118 /// Parse `"yield" expr?`.
1119 fn parse_yield_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1120 let lo = self.prev_span;
1121 let kind = ExprKind::Yield(self.parse_expr_opt()?);
1122 let span = lo.to(self.prev_span);
1123 self.sess.gated_spans.gate(sym::generators, span);
1124 let expr = self.mk_expr(span, kind, attrs);
1125 self.maybe_recover_from_bad_qpath(expr, true)
1128 /// Returns a string literal if the next token is a string literal.
1129 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1130 /// and returns `None` if the next token is not literal at all.
1131 pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
1132 match self.parse_opt_lit() {
1133 Some(lit) => match lit.kind {
1134 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1136 symbol: lit.token.symbol,
1137 suffix: lit.token.suffix,
1141 _ => Err(Some(lit)),
1147 pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> {
1148 self.parse_opt_lit().ok_or_else(|| {
1149 let msg = format!("unexpected token: {}", self.this_token_descr());
1150 self.span_fatal(self.token.span, &msg)
1154 /// Matches `lit = true | false | token_lit`.
1155 /// Returns `None` if the next token is not a literal.
1156 pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
1157 let mut recovered = None;
1158 if self.token == token::Dot {
1159 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1160 // dot would follow an optional literal, so we do this unconditionally.
1161 recovered = self.look_ahead(1, |next_token| {
1162 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix })
1164 if self.token.span.hi() == next_token.span.lo() {
1165 let s = String::from("0.") + &symbol.as_str();
1166 let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1167 return Some(Token::new(kind, self.token.span.to(next_token.span)));
1172 if let Some(token) = &recovered {
1174 self.struct_span_err(token.span, "float literals must have an integer part")
1177 "must have an integer part",
1178 pprust::token_to_string(token),
1179 Applicability::MachineApplicable,
1185 let token = recovered.as_ref().unwrap_or(&self.token);
1186 match Lit::from_token(token) {
1191 Err(LitError::NotLiteral) => {
1195 let span = token.span;
1196 let lit = match token.kind {
1197 token::Literal(lit) => lit,
1198 _ => unreachable!(),
1201 self.report_lit_error(err, lit, span);
1202 // Pack possible quotes and prefixes from the original literal into
1203 // the error literal's symbol so they can be pretty-printed faithfully.
1204 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1205 let symbol = Symbol::intern(&suffixless_lit.to_string());
1206 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1207 Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!()))
1212 fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) {
1213 // Checks if `s` looks like i32 or u1234 etc.
1214 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1216 && s.starts_with(first_chars)
1217 && s[1..].chars().all(|c| c.is_ascii_digit())
1220 let token::Lit { kind, suffix, .. } = lit;
1222 // `NotLiteral` is not an error by itself, so we don't report
1223 // it and give the parser opportunity to try something else.
1224 LitError::NotLiteral => {}
1225 // `LexerError` *is* an error, but it was already reported
1226 // by lexer, so here we don't report it the second time.
1227 LitError::LexerError => {}
1228 LitError::InvalidSuffix => {
1229 self.expect_no_suffix(
1231 &format!("{} {} literal", kind.article(), kind.descr()),
1235 LitError::InvalidIntSuffix => {
1236 let suf = suffix.expect("suffix error with no suffix").as_str();
1237 if looks_like_width_suffix(&['i', 'u'], &suf) {
1238 // If it looks like a width, try to be helpful.
1239 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
1240 self.struct_span_err(span, &msg)
1241 .help("valid widths are 8, 16, 32, 64 and 128")
1244 let msg = format!("invalid suffix `{}` for integer literal", suf);
1245 self.struct_span_err(span, &msg)
1246 .span_label(span, format!("invalid suffix `{}`", suf))
1247 .help("the suffix must be one of the integral types (`u32`, `isize`, etc)")
1251 LitError::InvalidFloatSuffix => {
1252 let suf = suffix.expect("suffix error with no suffix").as_str();
1253 if looks_like_width_suffix(&['f'], &suf) {
1254 // If it looks like a width, try to be helpful.
1255 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
1256 self.struct_span_err(span, &msg)
1257 .help("valid widths are 32 and 64")
1260 let msg = format!("invalid suffix `{}` for float literal", suf);
1261 self.struct_span_err(span, &msg)
1262 .span_label(span, format!("invalid suffix `{}`", suf))
1263 .help("valid suffixes are `f32` and `f64`")
1267 LitError::NonDecimalFloat(base) => {
1268 let descr = match base {
1269 16 => "hexadecimal",
1272 _ => unreachable!(),
1274 self.struct_span_err(span, &format!("{} float literal is not supported", descr))
1275 .span_label(span, "not supported")
1278 LitError::IntTooLarge => {
1279 self.struct_span_err(span, "integer literal is too large")
1285 pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) {
1286 if let Some(suf) = suffix {
1287 let mut err = if kind == "a tuple index"
1288 && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf)
1290 // #59553: warn instead of reject out of hand to allow the fix to percolate
1291 // through the ecosystem when people fix their macros
1292 let mut err = self.sess.span_diagnostic.struct_span_warn(
1294 &format!("suffixes on {} are invalid", kind),
1297 "`{}` is *temporarily* accepted on tuple index fields as it was \
1298 incorrectly accepted on stable for a few releases",
1302 "on proc macros, you'll want to use `syn::Index::from` or \
1303 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1304 to tuple field access",
1307 "for more context, see https://github.com/rust-lang/rust/issues/60210",
1311 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1313 err.span_label(sp, format!("invalid suffix `{}`", suf));
1318 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1319 pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1320 maybe_whole_expr!(self);
1322 let minus_lo = self.token.span;
1323 let minus_present = self.eat(&token::BinOp(token::Minus));
1324 let lo = self.token.span;
1325 let literal = self.parse_lit()?;
1326 let hi = self.prev_span;
1327 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1330 let minus_hi = self.prev_span;
1331 let unary = self.mk_unary(UnOp::Neg, expr);
1332 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1338 /// Parses a block or unsafe block.
1339 pub(super) fn parse_block_expr(
1341 opt_label: Option<Label>,
1343 blk_mode: BlockCheckMode,
1344 outer_attrs: ThinVec<Attribute>,
1345 ) -> PResult<'a, P<Expr>> {
1346 if let Some(label) = opt_label {
1347 self.sess.gated_spans.gate(sym::label_break_value, label.ident.span);
1350 self.expect(&token::OpenDelim(token::Brace))?;
1352 let mut attrs = outer_attrs;
1353 attrs.extend(self.parse_inner_attributes()?);
1355 let blk = self.parse_block_tail(lo, blk_mode)?;
1356 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs))
1359 /// Parses a closure expression (e.g., `move |args| expr`).
1360 fn parse_closure_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1361 let lo = self.token.span;
1363 let movability = if self.eat_keyword(kw::Static) {
1369 let asyncness = if self.token.span.rust_2018() {
1370 self.parse_asyncness()
1374 if asyncness.is_async() {
1375 // Feature-gate `async ||` closures.
1376 self.sess.gated_spans.gate(sym::async_closure, self.prev_span);
1379 let capture_clause = self.parse_capture_clause();
1380 let decl = self.parse_fn_block_decl()?;
1381 let decl_hi = self.prev_span;
1382 let body = match decl.output {
1383 FunctionRetTy::Default(_) => {
1384 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
1385 self.parse_expr_res(restrictions, None)?
1388 // If an explicit return type is given, require a block to appear (RFC 968).
1389 let body_lo = self.token.span;
1390 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
1396 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
1400 /// Parses an optional `move` prefix to a closure lke construct.
1401 fn parse_capture_clause(&mut self) -> CaptureBy {
1402 if self.eat_keyword(kw::Move) {
1409 /// Parses the `|arg, arg|` header of a closure.
1410 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
1411 let inputs_captures = {
1412 if self.eat(&token::OrOr) {
1415 self.expect(&token::BinOp(token::Or))?;
1416 let args = self.parse_seq_to_before_tokens(
1417 &[&token::BinOp(token::Or), &token::OrOr],
1418 SeqSep::trailing_allowed(token::Comma),
1419 TokenExpectType::NoExpect,
1420 |p| p.parse_fn_block_param()
1426 let output = self.parse_ret_ty(true, true)?;
1429 inputs: inputs_captures,
1434 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1435 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
1436 let lo = self.token.span;
1437 let attrs = self.parse_outer_attributes()?;
1438 let pat = self.parse_pat(PARAM_EXPECTED)?;
1439 let t = if self.eat(&token::Colon) {
1444 kind: TyKind::Infer,
1445 span: self.prev_span,
1448 let span = lo.to(self.token.span);
1450 attrs: attrs.into(),
1455 is_placeholder: false,
1459 /// Parses an `if` expression (`if` token already eaten).
1460 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1461 let lo = self.prev_span;
1462 let cond = self.parse_cond_expr()?;
1464 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1465 // verify that the last statement is either an implicit return (no `;`) or an explicit
1466 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1467 // the dead code lint.
1468 if self.eat_keyword(kw::Else) || !cond.returns() {
1469 let sp = self.sess.source_map().next_point(lo);
1470 let mut err = self.diagnostic()
1471 .struct_span_err(sp, "missing condition for `if` expression");
1472 err.span_label(sp, "expected if condition here");
1475 let not_block = self.token != token::OpenDelim(token::Brace);
1476 let thn = self.parse_block().map_err(|mut err| {
1478 err.span_label(lo, "this `if` statement has a condition, but no block");
1482 let mut els: Option<P<Expr>> = None;
1483 let mut hi = thn.span;
1484 if self.eat_keyword(kw::Else) {
1485 let elexpr = self.parse_else_expr()?;
1489 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
1492 /// Parses the condition of a `if` or `while` expression.
1493 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
1494 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1496 if let ExprKind::Let(..) = cond.kind {
1497 // Remove the last feature gating of a `let` expression since it's stable.
1498 self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
1504 /// Parses a `let $pat = $expr` pseudo-expression.
1505 /// The `let` token has already been eaten.
1506 fn parse_let_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1507 let lo = self.prev_span;
1508 let pat = self.parse_top_pat(GateOr::No)?;
1509 self.expect(&token::Eq)?;
1510 let expr = self.with_res(
1511 Restrictions::NO_STRUCT_LITERAL,
1512 |this| this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
1514 let span = lo.to(expr.span);
1515 self.sess.gated_spans.gate(sym::let_chains, span);
1516 Ok(self.mk_expr(span, ExprKind::Let(pat, expr), attrs))
1519 /// Parses an `else { ... }` expression (`else` token already eaten).
1520 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
1521 if self.eat_keyword(kw::If) {
1522 return self.parse_if_expr(ThinVec::new());
1524 let blk = self.parse_block()?;
1525 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
1529 /// Parses a `for ... in` expression (`for` token already eaten).
1532 opt_label: Option<Label>,
1534 mut attrs: ThinVec<Attribute>
1535 ) -> PResult<'a, P<Expr>> {
1536 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
1538 // Record whether we are about to parse `for (`.
1539 // This is used below for recovery in case of `for ( $stuff ) $block`
1540 // in which case we will suggest `for $stuff $block`.
1541 let begin_paren = match self.token.kind {
1542 token::OpenDelim(token::Paren) => Some(self.token.span),
1546 let pat = self.parse_top_pat(GateOr::Yes)?;
1547 if !self.eat_keyword(kw::In) {
1548 let in_span = self.prev_span.between(self.token.span);
1549 self.struct_span_err(in_span, "missing `in` in `for` loop")
1550 .span_suggestion_short(
1552 "try adding `in` here", " in ".into(),
1553 // has been misleading, at least in the past (closed Issue #48492)
1554 Applicability::MaybeIncorrect
1558 let in_span = self.prev_span;
1559 self.check_for_for_in_in_typo(in_span);
1560 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1562 let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
1564 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
1565 attrs.extend(iattrs);
1567 let hi = self.prev_span;
1568 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
1571 /// Parses a `while` or `while let` expression (`while` token already eaten).
1572 fn parse_while_expr(
1574 opt_label: Option<Label>,
1576 mut attrs: ThinVec<Attribute>
1577 ) -> PResult<'a, P<Expr>> {
1578 let cond = self.parse_cond_expr()?;
1579 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1580 attrs.extend(iattrs);
1581 let span = span_lo.to(body.span);
1582 Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs))
1585 /// Parses `loop { ... }` (`loop` token already eaten).
1588 opt_label: Option<Label>,
1590 mut attrs: ThinVec<Attribute>
1591 ) -> PResult<'a, P<Expr>> {
1592 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1593 attrs.extend(iattrs);
1594 let span = span_lo.to(body.span);
1595 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
1598 fn eat_label(&mut self) -> Option<Label> {
1599 if let Some(ident) = self.token.lifetime() {
1600 let span = self.token.span;
1602 Some(Label { ident: Ident::new(ident.name, span) })
1608 /// Parses a `match ... { ... }` expression (`match` token already eaten).
1609 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1610 let match_span = self.prev_span;
1611 let lo = self.prev_span;
1612 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1613 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
1614 if self.token == token::Semi {
1615 e.span_suggestion_short(
1617 "try removing this `match`",
1619 Applicability::MaybeIncorrect // speculative
1624 attrs.extend(self.parse_inner_attributes()?);
1626 let mut arms: Vec<Arm> = Vec::new();
1627 while self.token != token::CloseDelim(token::Brace) {
1628 match self.parse_arm() {
1629 Ok(arm) => arms.push(arm),
1631 // Recover by skipping to the end of the block.
1633 self.recover_stmt();
1634 let span = lo.to(self.token.span);
1635 if self.token == token::CloseDelim(token::Brace) {
1638 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
1642 let hi = self.token.span;
1644 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
1647 pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
1648 let attrs = self.parse_outer_attributes()?;
1649 let lo = self.token.span;
1650 let pat = self.parse_top_pat(GateOr::No)?;
1651 let guard = if self.eat_keyword(kw::If) {
1652 Some(self.parse_expr()?)
1656 let arrow_span = self.token.span;
1657 self.expect(&token::FatArrow)?;
1658 let arm_start_span = self.token.span;
1660 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
1661 .map_err(|mut err| {
1662 err.span_label(arrow_span, "while parsing the `match` arm starting here");
1666 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
1667 && self.token != token::CloseDelim(token::Brace);
1669 let hi = self.token.span;
1672 let cm = self.sess.source_map();
1673 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
1674 .map_err(|mut err| {
1675 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
1676 (Ok(ref expr_lines), Ok(ref arm_start_lines))
1677 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
1678 && expr_lines.lines.len() == 2
1679 && self.token == token::FatArrow => {
1680 // We check whether there's any trailing code in the parse span,
1681 // if there isn't, we very likely have the following:
1684 // | -- - missing comma
1688 // | - ^^ self.token.span
1690 // | parsed until here as `"y" & X`
1691 err.span_suggestion_short(
1692 cm.next_point(arm_start_span),
1693 "missing a comma here to end this `match` arm",
1695 Applicability::MachineApplicable
1699 err.span_label(arrow_span,
1700 "while parsing the `match` arm starting here");
1706 self.eat(&token::Comma);
1716 is_placeholder: false,
1720 /// Parses a `try {...}` expression (`try` token already eaten).
1724 mut attrs: ThinVec<Attribute>
1725 ) -> PResult<'a, P<Expr>> {
1726 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1727 attrs.extend(iattrs);
1728 if self.eat_keyword(kw::Catch) {
1729 let mut error = self.struct_span_err(self.prev_span,
1730 "keyword `catch` cannot follow a `try` block");
1731 error.help("try using `match` on the result of the `try` block instead");
1735 let span = span_lo.to(body.span);
1736 self.sess.gated_spans.gate(sym::try_blocks, span);
1737 Ok(self.mk_expr(span, ExprKind::TryBlock(body), attrs))
1741 fn is_do_catch_block(&self) -> bool {
1742 self.token.is_keyword(kw::Do) &&
1743 self.is_keyword_ahead(1, &[kw::Catch]) &&
1744 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
1745 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1748 fn is_try_block(&self) -> bool {
1749 self.token.is_keyword(kw::Try) &&
1750 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
1751 self.token.span.rust_2018() &&
1752 // Prevent `while try {} {}`, `if try {} {} else {}`, etc.
1753 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1756 /// Parses an `async move? {...}` expression.
1757 fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1758 let span_lo = self.token.span;
1759 self.expect_keyword(kw::Async)?;
1760 let capture_clause = self.parse_capture_clause();
1761 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1762 attrs.extend(iattrs);
1764 span_lo.to(body.span),
1765 ExprKind::Async(capture_clause, DUMMY_NODE_ID, body), attrs))
1768 fn is_async_block(&self) -> bool {
1769 self.token.is_keyword(kw::Async) &&
1772 self.is_keyword_ahead(1, &[kw::Move]) &&
1773 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
1775 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
1780 fn maybe_parse_struct_expr(
1784 attrs: &ThinVec<Attribute>,
1785 ) -> Option<PResult<'a, P<Expr>>> {
1786 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
1787 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
1788 // `{ ident, ` cannot start a block.
1789 self.look_ahead(2, |t| t == &token::Comma) ||
1790 self.look_ahead(2, |t| t == &token::Colon) && (
1791 // `{ ident: token, ` cannot start a block.
1792 self.look_ahead(4, |t| t == &token::Comma) ||
1793 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
1794 self.look_ahead(3, |t| !t.can_begin_type())
1798 if struct_allowed || certainly_not_a_block() {
1799 // This is a struct literal, but we don't can't accept them here.
1800 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
1801 if let (Ok(expr), false) = (&expr, struct_allowed) {
1802 self.struct_span_err(
1804 "struct literals are not allowed here",
1806 .multipart_suggestion(
1807 "surround the struct literal with parentheses",
1809 (lo.shrink_to_lo(), "(".to_string()),
1810 (expr.span.shrink_to_hi(), ")".to_string()),
1812 Applicability::MachineApplicable,
1821 pub(super) fn parse_struct_expr(
1825 mut attrs: ThinVec<Attribute>
1826 ) -> PResult<'a, P<Expr>> {
1827 let struct_sp = lo.to(self.prev_span);
1829 let mut fields = Vec::new();
1830 let mut base = None;
1832 attrs.extend(self.parse_inner_attributes()?);
1834 while self.token != token::CloseDelim(token::Brace) {
1835 if self.eat(&token::DotDot) {
1836 let exp_span = self.prev_span;
1837 match self.parse_expr() {
1843 self.recover_stmt();
1846 if self.token == token::Comma {
1847 self.struct_span_err(
1848 exp_span.to(self.prev_span),
1849 "cannot use a comma after the base struct",
1851 .span_suggestion_short(
1853 "remove this comma",
1855 Applicability::MachineApplicable
1857 .note("the base struct must always be the last field")
1859 self.recover_stmt();
1864 let mut recovery_field = None;
1865 if let token::Ident(name, _) = self.token.kind {
1866 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
1867 // Use in case of error after field-looking code: `S { foo: () with a }`.
1868 recovery_field = Some(ast::Field {
1869 ident: Ident::new(name, self.token.span),
1870 span: self.token.span,
1871 expr: self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()),
1872 is_shorthand: false,
1873 attrs: ThinVec::new(),
1875 is_placeholder: false,
1879 let mut parsed_field = None;
1880 match self.parse_field() {
1881 Ok(f) => parsed_field = Some(f),
1883 e.span_label(struct_sp, "while parsing this struct");
1886 // If the next token is a comma, then try to parse
1887 // what comes next as additional fields, rather than
1888 // bailing out until next `}`.
1889 if self.token != token::Comma {
1890 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
1891 if self.token != token::Comma {
1898 match self.expect_one_of(&[token::Comma],
1899 &[token::CloseDelim(token::Brace)]) {
1900 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
1901 // Only include the field if there's no parse error for the field name.
1905 if let Some(f) = recovery_field {
1908 e.span_label(struct_sp, "while parsing this struct");
1910 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
1911 self.eat(&token::Comma);
1916 let span = lo.to(self.token.span);
1917 self.expect(&token::CloseDelim(token::Brace))?;
1918 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
1921 /// Parses `ident (COLON expr)?`.
1922 fn parse_field(&mut self) -> PResult<'a, Field> {
1923 let attrs = self.parse_outer_attributes()?;
1924 let lo = self.token.span;
1926 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1927 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
1928 t == &token::Colon || t == &token::Eq
1930 let fieldname = self.parse_field_name()?;
1932 // Check for an equals token. This means the source incorrectly attempts to
1933 // initialize a field with an eq rather than a colon.
1934 if self.token == token::Eq {
1936 .struct_span_err(self.token.span, "expected `:`, found `=`")
1938 fieldname.span.shrink_to_hi().to(self.token.span),
1939 "replace equals symbol with a colon",
1941 Applicability::MachineApplicable,
1946 (fieldname, self.parse_expr()?, false)
1948 let fieldname = self.parse_ident_common(false)?;
1950 // Mimic `x: x` for the `x` field shorthand.
1951 let path = ast::Path::from_ident(fieldname);
1952 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
1953 (fieldname, expr, true)
1957 span: lo.to(expr.span),
1960 attrs: attrs.into(),
1962 is_placeholder: false,
1966 fn err_dotdotdot_syntax(&self, span: Span) {
1967 self.struct_span_err(span, "unexpected token: `...`")
1970 "use `..` for an exclusive range", "..".to_owned(),
1971 Applicability::MaybeIncorrect
1975 "or `..=` for an inclusive range", "..=".to_owned(),
1976 Applicability::MaybeIncorrect
1981 fn err_larrow_operator(&self, span: Span) {
1982 self.struct_span_err(
1984 "unexpected token: `<-`"
1987 "if you meant to write a comparison against a negative value, add a \
1988 space in between `<` and `-`",
1990 Applicability::MaybeIncorrect
1994 fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
1995 ExprKind::AssignOp(binop, lhs, rhs)
2000 start: Option<P<Expr>>,
2001 end: Option<P<Expr>>,
2003 ) -> PResult<'a, ExprKind> {
2004 if end.is_none() && limits == RangeLimits::Closed {
2005 Err(self.span_fatal_err(self.token.span, Error::InclusiveRangeWithNoEnd))
2007 Ok(ExprKind::Range(start, end, limits))
2011 fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
2012 ExprKind::Unary(unop, expr)
2015 fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2016 ExprKind::Binary(binop, lhs, rhs)
2019 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
2020 ExprKind::Index(expr, idx)
2023 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
2024 ExprKind::Call(f, args)
2027 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2028 let span = lo.to(self.prev_span);
2029 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), ThinVec::new());
2030 self.recover_from_await_method_call();
2034 crate fn mk_expr(&self, span: Span, kind: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2035 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID })
2038 pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
2039 self.mk_expr(span, ExprKind::Err, ThinVec::new())