1 use super::pat::{GateOr, PARAM_EXPECTED};
2 use super::ty::{AllowPlus, RecoverQPath};
3 use super::{BlockMode, Parser, PathStyle, Restrictions, TokenType};
4 use super::{SemiColonMode, SeqSep, TokenExpectType};
5 use crate::maybe_recover_from_interpolated_ty_qpath;
7 use rustc_ast::ast::{self, AttrStyle, AttrVec, CaptureBy, Field, Ident, Lit, UnOp, DUMMY_NODE_ID};
8 use rustc_ast::ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty, TyKind};
9 use rustc_ast::ast::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits};
10 use rustc_ast::ptr::P;
11 use rustc_ast::token::{self, Token, TokenKind};
12 use rustc_ast::util::classify;
13 use rustc_ast::util::literal::LitError;
14 use rustc_ast::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity};
15 use rustc_ast_pretty::pprust;
16 use rustc_errors::{Applicability, PResult};
17 use rustc_span::source_map::{self, Span, Spanned};
18 use rustc_span::symbol::{kw, sym, Symbol};
21 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
22 /// dropped into the token stream, which happens while parsing the result of
23 /// macro expansion). Placement of these is not as complex as I feared it would
24 /// be. The important thing is to make sure that lookahead doesn't balk at
25 /// `token::Interpolated` tokens.
26 macro_rules! maybe_whole_expr {
28 if let token::Interpolated(nt) = &$p.token.kind {
30 token::NtExpr(e) | token::NtLiteral(e) => {
35 token::NtPath(path) => {
36 let path = path.clone();
40 ExprKind::Path(None, path),
44 token::NtBlock(block) => {
45 let block = block.clone();
49 ExprKind::Block(block, None),
60 pub(super) enum LhsExpr {
62 AttributesParsed(AttrVec),
63 AlreadyParsed(P<Expr>),
66 impl From<Option<AttrVec>> for LhsExpr {
67 /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
68 /// and `None` into `LhsExpr::NotYetParsed`.
70 /// This conversion does not allocate.
71 fn from(o: Option<AttrVec>) -> Self {
72 if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed }
76 impl From<P<Expr>> for LhsExpr {
77 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
79 /// This conversion does not allocate.
80 fn from(expr: P<Expr>) -> Self {
81 LhsExpr::AlreadyParsed(expr)
86 /// Parses an expression.
88 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
89 self.parse_expr_res(Restrictions::empty(), None)
92 pub(super) fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> {
93 self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
96 fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P<Expr>> {
97 match self.parse_expr() {
99 Err(mut err) => match self.token.ident() {
100 Some((Ident { name: kw::Underscore, .. }, false))
101 if self.look_ahead(1, |t| t == &token::Comma) =>
103 // Special-case handling of `foo(_, _, _)`
106 Ok(self.mk_expr(self.prev_token.span, ExprKind::Err, AttrVec::new()))
113 /// Parses a sequence of expressions delimited by parentheses.
114 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
115 self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r)
118 /// Parses an expression, subject to the given restrictions.
120 pub(super) fn parse_expr_res(
123 already_parsed_attrs: Option<AttrVec>,
124 ) -> PResult<'a, P<Expr>> {
125 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
128 /// Parses an associative expression.
130 /// This parses an expression accounting for associativity and precedence of the operators in
133 fn parse_assoc_expr(&mut self, already_parsed_attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> {
134 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
137 /// Parses an associative expression with operators of at least `min_prec` precedence.
138 pub(super) fn parse_assoc_expr_with(
142 ) -> PResult<'a, P<Expr>> {
143 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
146 let attrs = match lhs {
147 LhsExpr::AttributesParsed(attrs) => Some(attrs),
150 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
151 return self.parse_prefix_range_expr(attrs);
153 self.parse_prefix_expr(attrs)?
156 let last_type_ascription_set = self.last_type_ascription.is_some();
158 if !self.should_continue_as_assoc_expr(&lhs) {
159 self.last_type_ascription = None;
163 self.expected_tokens.push(TokenType::Operator);
164 while let Some(op) = self.check_assoc_op() {
165 // Adjust the span for interpolated LHS to point to the `$lhs` token
166 // and not to what it refers to.
167 let lhs_span = match self.prev_token.kind {
168 TokenKind::Interpolated(..) => self.prev_token.span,
172 let cur_op_span = self.token.span;
173 let restrictions = if op.node.is_assign_like() {
174 self.restrictions & Restrictions::NO_STRUCT_LITERAL
178 let prec = op.node.precedence();
182 // Check for deprecated `...` syntax
183 if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq {
184 self.err_dotdotdot_syntax(self.token.span);
187 if self.token == token::LArrow {
188 self.err_larrow_operator(self.token.span);
192 if op.node.is_comparison() {
193 if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
199 if op == AssocOp::As {
200 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
202 } else if op == AssocOp::Colon {
203 lhs = self.parse_assoc_op_ascribe(lhs, lhs_span)?;
205 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
206 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
207 // generalise it to the Fixity::None code.
208 lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?;
212 let fixity = op.fixity();
213 let prec_adjustment = match fixity {
216 // We currently have no non-associative operators that are not handled above by
217 // the special cases. The code is here only for future convenience.
220 let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
221 this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
224 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
225 // including the attributes.
227 lhs.attrs.iter().find(|a| a.style == AttrStyle::Outer).map_or(lhs_span, |a| a.span);
228 let span = lhs_span.to(rhs.span);
241 | AssocOp::ShiftRight
247 | AssocOp::GreaterEqual => {
248 let ast_op = op.to_ast_binop().unwrap();
249 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
250 self.mk_expr(span, binary, AttrVec::new())
253 self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span), AttrVec::new())
255 AssocOp::AssignOp(k) => {
257 token::Plus => BinOpKind::Add,
258 token::Minus => BinOpKind::Sub,
259 token::Star => BinOpKind::Mul,
260 token::Slash => BinOpKind::Div,
261 token::Percent => BinOpKind::Rem,
262 token::Caret => BinOpKind::BitXor,
263 token::And => BinOpKind::BitAnd,
264 token::Or => BinOpKind::BitOr,
265 token::Shl => BinOpKind::Shl,
266 token::Shr => BinOpKind::Shr,
268 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
269 self.mk_expr(span, aopexpr, AttrVec::new())
271 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
272 self.span_bug(span, "AssocOp should have been handled by special case")
276 if let Fixity::None = fixity {
280 if last_type_ascription_set {
281 self.last_type_ascription = None;
286 fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
287 match (self.expr_is_complete(lhs), self.check_assoc_op().map(|op| op.node)) {
288 // Semi-statement forms are odd:
289 // See https://github.com/rust-lang/rust/issues/29071
290 (true, None) => false,
291 (false, _) => true, // Continue parsing the expression.
292 // An exhaustive check is done in the following block, but these are checked first
293 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
294 // want to keep their span info to improve diagnostics in these cases in a later stage.
295 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
296 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
297 (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475)
298 (true, Some(AssocOp::Add)) // `{ 42 } + 42
299 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
300 // `if x { a } else { b } && if y { c } else { d }`
301 if !self.look_ahead(1, |t| t.is_reserved_ident()) => {
302 // These cases are ambiguous and can't be identified in the parser alone.
303 let sp = self.sess.source_map().start_point(self.token.span);
304 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
307 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => false,
309 self.error_found_expr_would_be_stmt(lhs);
315 /// We've found an expression that would be parsed as a statement,
316 /// but the next token implies this should be parsed as an expression.
317 /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
318 fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
319 let mut err = self.struct_span_err(
321 &format!("expected expression, found `{}`", pprust::token_to_string(&self.token),),
323 err.span_label(self.token.span, "expected expression");
324 self.sess.expr_parentheses_needed(&mut err, lhs.span, Some(pprust::expr_to_string(&lhs)));
328 /// Possibly translate the current token to an associative operator.
329 /// The method does not advance the current token.
331 /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
332 fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
333 let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
334 (Some(op), _) => (op, self.token.span),
335 (None, Some((Ident { name: sym::and, span }, false))) => {
336 self.error_bad_logical_op("and", "&&", "conjunction");
337 (AssocOp::LAnd, span)
339 (None, Some((Ident { name: sym::or, span }, false))) => {
340 self.error_bad_logical_op("or", "||", "disjunction");
345 Some(source_map::respan(span, op))
348 /// Error on `and` and `or` suggesting `&&` and `||` respectively.
349 fn error_bad_logical_op(&self, bad: &str, good: &str, english: &str) {
350 self.struct_span_err(self.token.span, &format!("`{}` is not a logical operator", bad))
351 .span_suggestion_short(
353 &format!("use `{}` to perform logical {}", good, english),
355 Applicability::MachineApplicable,
357 .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators")
361 /// Checks if this expression is a successfully parsed statement.
362 fn expr_is_complete(&self, e: &Expr) -> bool {
363 self.restrictions.contains(Restrictions::STMT_EXPR)
364 && !classify::expr_requires_semi_to_be_stmt(e)
367 /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
368 /// The other two variants are handled in `parse_prefix_range_expr` below.
375 ) -> PResult<'a, P<Expr>> {
376 let rhs = if self.is_at_start_of_range_notation_rhs() {
377 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
381 let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
382 let span = lhs.span.to(rhs_span);
384 if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed };
385 Ok(self.mk_expr(span, self.mk_range(Some(lhs), rhs, limits)?, AttrVec::new()))
388 fn is_at_start_of_range_notation_rhs(&self) -> bool {
389 if self.token.can_begin_expr() {
390 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
391 if self.token == token::OpenDelim(token::Brace) {
392 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
400 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
401 fn parse_prefix_range_expr(&mut self, attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> {
402 // Check for deprecated `...` syntax.
403 if self.token == token::DotDotDot {
404 self.err_dotdotdot_syntax(self.token.span);
408 [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
409 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
413 let limits = match self.token.kind {
414 token::DotDot => RangeLimits::HalfOpen,
415 _ => RangeLimits::Closed,
417 let op = AssocOp::from_token(&self.token);
418 let attrs = self.parse_or_use_outer_attributes(attrs)?;
419 let lo = self.token.span;
421 let (span, opt_end) = if self.is_at_start_of_range_notation_rhs() {
422 // RHS must be parsed with more associativity than the dots.
423 self.parse_assoc_expr_with(op.unwrap().precedence() + 1, LhsExpr::NotYetParsed)
424 .map(|x| (lo.to(x.span), Some(x)))?
428 Ok(self.mk_expr(span, self.mk_range(None, opt_end, limits)?, attrs))
431 /// Parses a prefix-unary-operator expr.
432 fn parse_prefix_expr(&mut self, attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> {
433 let attrs = self.parse_or_use_outer_attributes(attrs)?;
434 let lo = self.token.span;
435 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
436 let (hi, ex) = match self.token.uninterpolate().kind {
437 token::Not => self.parse_unary_expr(lo, UnOp::Not), // `!expr`
438 token::Tilde => self.recover_tilde_expr(lo), // `~expr`
439 token::BinOp(token::Minus) => self.parse_unary_expr(lo, UnOp::Neg), // `-expr`
440 token::BinOp(token::Star) => self.parse_unary_expr(lo, UnOp::Deref), // `*expr`
441 token::BinOp(token::And) | token::AndAnd => self.parse_borrow_expr(lo),
442 token::Ident(..) if self.token.is_keyword(kw::Box) => self.parse_box_expr(lo),
443 token::Ident(..) if self.is_mistaken_not_ident_negation() => self.recover_not_expr(lo),
444 _ => return self.parse_dot_or_call_expr(Some(attrs)),
446 Ok(self.mk_expr(lo.to(hi), ex, attrs))
449 fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P<Expr>)> {
451 let expr = self.parse_prefix_expr(None);
452 let (span, expr) = self.interpolated_or_expr_span(expr)?;
453 Ok((lo.to(span), expr))
456 fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
457 let (span, expr) = self.parse_prefix_expr_common(lo)?;
458 Ok((span, self.mk_unary(op, expr)))
461 // Recover on `!` suggesting for bitwise negation instead.
462 fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
463 self.struct_span_err(lo, "`~` cannot be used as a unary operator")
464 .span_suggestion_short(
466 "use `!` to perform bitwise not",
468 Applicability::MachineApplicable,
472 self.parse_unary_expr(lo, UnOp::Not)
475 /// Parse `box expr`.
476 fn parse_box_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
477 let (span, expr) = self.parse_prefix_expr_common(lo)?;
478 self.sess.gated_spans.gate(sym::box_syntax, span);
479 Ok((span, ExprKind::Box(expr)))
482 fn is_mistaken_not_ident_negation(&self) -> bool {
483 let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
484 // These tokens can start an expression after `!`, but
485 // can't continue an expression after an ident
486 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
487 token::Literal(..) | token::Pound => true,
488 _ => t.is_whole_expr(),
490 self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
493 /// Recover on `not expr` in favor of `!expr`.
494 fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
496 let not_token = self.look_ahead(1, |t| t.clone());
497 self.struct_span_err(
499 &format!("unexpected {} after identifier", super::token_descr(¬_token)),
501 .span_suggestion_short(
502 // Span the `not` plus trailing whitespace to avoid
503 // trailing whitespace after the `!` in our suggestion
504 self.sess.source_map().span_until_non_whitespace(lo.to(not_token.span)),
505 "use `!` to perform logical negation",
507 Applicability::MachineApplicable,
512 self.parse_unary_expr(lo, UnOp::Not)
515 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
516 fn interpolated_or_expr_span(
518 expr: PResult<'a, P<Expr>>,
519 ) -> PResult<'a, (Span, P<Expr>)> {
522 match self.prev_token.kind {
523 TokenKind::Interpolated(..) => self.prev_token.span,
531 fn parse_assoc_op_cast(
535 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind,
536 ) -> PResult<'a, P<Expr>> {
537 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
538 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), AttrVec::new())
541 // Save the state of the parser before parsing type normally, in case there is a
542 // LessThan comparison after this cast.
543 let parser_snapshot_before_type = self.clone();
544 let cast_expr = match self.parse_ty_no_plus() {
545 Ok(rhs) => mk_expr(self, rhs),
546 Err(mut type_err) => {
547 // Rewind to before attempting to parse the type with generics, to recover
548 // from situations like `x as usize < y` in which we first tried to parse
549 // `usize < y` as a type with generic arguments.
550 let parser_snapshot_after_type = self.clone();
551 mem::replace(self, parser_snapshot_before_type);
553 match self.parse_path(PathStyle::Expr) {
555 let (op_noun, op_verb) = match self.token.kind {
556 token::Lt => ("comparison", "comparing"),
557 token::BinOp(token::Shl) => ("shift", "shifting"),
559 // We can end up here even without `<` being the next token, for
560 // example because `parse_ty_no_plus` returns `Err` on keywords,
561 // but `parse_path` returns `Ok` on them due to error recovery.
562 // Return original error and parser state.
563 mem::replace(self, parser_snapshot_after_type);
564 return Err(type_err);
568 // Successfully parsed the type path leaving a `<` yet to parse.
571 // Report non-fatal diagnostics, keep `x as usize` as an expression
572 // in AST and continue parsing.
574 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
575 pprust::path_to_string(&path),
578 let span_after_type = parser_snapshot_after_type.token.span;
579 let expr = mk_expr(self, self.mk_ty(path.span, TyKind::Path(None, path)));
582 .span_to_snippet(expr.span)
583 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
585 self.struct_span_err(self.token.span, &msg)
587 self.look_ahead(1, |t| t.span).to(span_after_type),
588 "interpreted as generic arguments",
590 .span_label(self.token.span, format!("not interpreted as {}", op_noun))
593 &format!("try {} the cast value", op_verb),
594 format!("({})", expr_str),
595 Applicability::MachineApplicable,
601 Err(mut path_err) => {
602 // Couldn't parse as a path, return original error and parser state.
604 mem::replace(self, parser_snapshot_after_type);
605 return Err(type_err);
611 self.parse_and_disallow_postfix_after_cast(cast_expr)
614 /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
615 /// then emits an error and returns the newly parsed tree.
616 /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
617 fn parse_and_disallow_postfix_after_cast(
620 ) -> PResult<'a, P<Expr>> {
621 // Save the memory location of expr before parsing any following postfix operators.
622 // This will be compared with the memory location of the output expression.
623 // If they different we can assume we parsed another expression because the existing expression is not reallocated.
624 let addr_before = &*cast_expr as *const _ as usize;
625 let span = cast_expr.span;
626 let with_postfix = self.parse_dot_or_call_expr_with_(cast_expr, span)?;
627 let changed = addr_before != &*with_postfix as *const _ as usize;
629 // Check if an illegal postfix operator has been added after the cast.
630 // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator.
631 if !matches!(with_postfix.kind, ExprKind::Cast(_, _) | ExprKind::Type(_, _)) || changed {
633 "casts cannot be followed by {}",
634 match with_postfix.kind {
635 ExprKind::Index(_, _) => "indexing",
636 ExprKind::Try(_) => "?",
637 ExprKind::Field(_, _) => "a field access",
638 ExprKind::MethodCall(_, _) => "a method call",
639 ExprKind::Call(_, _) => "a function call",
640 ExprKind::Await(_) => "`.await`",
641 _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"),
644 let mut err = self.struct_span_err(span, &msg);
645 // If type ascription is "likely an error", the user will already be getting a useful
646 // help message, and doesn't need a second.
647 if self.last_type_ascription.map_or(false, |last_ascription| last_ascription.1) {
648 self.maybe_annotate_with_ascription(&mut err, false);
650 let suggestions = vec![
651 (span.shrink_to_lo(), "(".to_string()),
652 (span.shrink_to_hi(), ")".to_string()),
654 err.multipart_suggestion(
655 "try surrounding the expression in parentheses",
657 Applicability::MachineApplicable,
665 fn parse_assoc_op_ascribe(&mut self, lhs: P<Expr>, lhs_span: Span) -> PResult<'a, P<Expr>> {
666 let maybe_path = self.could_ascription_be_path(&lhs.kind);
667 self.last_type_ascription = Some((self.prev_token.span, maybe_path));
668 let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
669 self.sess.gated_spans.gate(sym::type_ascription, lhs.span);
673 /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
674 fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
676 let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
677 let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
678 let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo);
679 let expr = self.parse_prefix_expr(None);
680 let (hi, expr) = self.interpolated_or_expr_span(expr)?;
681 let span = lo.to(hi);
682 if let Some(lt) = lifetime {
683 self.error_remove_borrow_lifetime(span, lt.ident.span);
685 Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
688 fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
689 self.struct_span_err(span, "borrow expressions cannot be annotated with lifetimes")
690 .span_label(lt_span, "annotated with lifetime here")
693 "remove the lifetime annotation",
695 Applicability::MachineApplicable,
700 /// Parse `mut?` or `raw [ const | mut ]`.
701 fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) {
702 if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) {
703 // `raw [ const | mut ]`.
704 let found_raw = self.eat_keyword(kw::Raw);
706 let mutability = self.parse_const_or_mut().unwrap();
707 self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span));
708 (ast::BorrowKind::Raw, mutability)
711 (ast::BorrowKind::Ref, self.parse_mutability())
715 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
716 fn parse_dot_or_call_expr(&mut self, attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> {
717 let attrs = self.parse_or_use_outer_attributes(attrs)?;
718 let base = self.parse_bottom_expr();
719 let (span, base) = self.interpolated_or_expr_span(base)?;
720 self.parse_dot_or_call_expr_with(base, span, attrs)
723 pub(super) fn parse_dot_or_call_expr_with(
728 ) -> PResult<'a, P<Expr>> {
729 // Stitch the list of outer attributes onto the return value.
730 // A little bit ugly, but the best way given the current code
732 self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| {
733 expr.map(|mut expr| {
734 attrs.extend::<Vec<_>>(expr.attrs.into());
741 fn parse_dot_or_call_expr_with_(&mut self, mut e: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
743 if self.eat(&token::Question) {
745 e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e), AttrVec::new());
748 if self.eat(&token::Dot) {
750 e = self.parse_dot_suffix_expr(lo, e)?;
753 if self.expr_is_complete(&e) {
756 e = match self.token.kind {
757 token::OpenDelim(token::Paren) => self.parse_fn_call_expr(lo, e),
758 token::OpenDelim(token::Bracket) => self.parse_index_expr(lo, e)?,
764 fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
765 match self.token.uninterpolate().kind {
766 token::Ident(..) => self.parse_dot_suffix(base, lo),
767 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
768 Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix))
770 token::Literal(token::Lit { kind: token::Float, symbol, .. }) => {
771 self.recover_field_access_by_float_lit(lo, base, symbol)
774 self.error_unexpected_after_dot();
780 fn error_unexpected_after_dot(&self) {
781 // FIXME Could factor this out into non_fatal_unexpected or something.
782 let actual = pprust::token_to_string(&self.token);
783 self.struct_span_err(self.token.span, &format!("unexpected token: `{}`", actual)).emit();
786 fn recover_field_access_by_float_lit(
791 ) -> PResult<'a, P<Expr>> {
794 let fstr = sym.as_str();
795 let msg = format!("unexpected token: `{}`", sym);
797 let mut err = self.struct_span_err(self.prev_token.span, &msg);
798 err.span_label(self.prev_token.span, "unexpected token");
800 if fstr.chars().all(|x| "0123456789.".contains(x)) {
801 let float = match fstr.parse::<f64>() {
808 let sugg = pprust::to_string(|s| {
812 s.print_usize(float.trunc() as usize);
815 s.s.word(fstr.splitn(2, '.').last().unwrap().to_string())
818 lo.to(self.prev_token.span),
819 "try parenthesizing the first index",
821 Applicability::MachineApplicable,
827 fn parse_tuple_field_access_expr(
832 suffix: Option<Symbol>,
835 let span = self.prev_token.span;
836 let field = ExprKind::Field(base, Ident::new(field, span));
837 self.expect_no_suffix(span, "a tuple index", suffix);
838 self.mk_expr(lo.to(span), field, AttrVec::new())
841 /// Parse a function call expression, `expr(...)`.
842 fn parse_fn_call_expr(&mut self, lo: Span, fun: P<Expr>) -> P<Expr> {
843 let seq = self.parse_paren_expr_seq().map(|args| {
844 self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args), AttrVec::new())
846 self.recover_seq_parse_error(token::Paren, lo, seq)
849 /// Parse an indexing expression `expr[...]`.
850 fn parse_index_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
852 let index = self.parse_expr()?;
853 self.expect(&token::CloseDelim(token::Bracket))?;
854 Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_index(base, index), AttrVec::new()))
857 /// Assuming we have just parsed `.`, continue parsing into an expression.
858 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
859 if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) {
860 return self.mk_await_expr(self_arg, lo);
863 let segment = self.parse_path_segment(PathStyle::Expr)?;
864 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
866 if self.check(&token::OpenDelim(token::Paren)) {
867 // Method call `expr.f()`
868 let mut args = self.parse_paren_expr_seq()?;
869 args.insert(0, self_arg);
871 let span = lo.to(self.prev_token.span);
872 Ok(self.mk_expr(span, ExprKind::MethodCall(segment, args), AttrVec::new()))
874 // Field access `expr.f`
875 if let Some(args) = segment.args {
876 self.struct_span_err(
878 "field expressions cannot have generic arguments",
883 let span = lo.to(self.prev_token.span);
884 Ok(self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), AttrVec::new()))
888 /// At the bottom (top?) of the precedence hierarchy,
889 /// Parses things like parenthesized exprs, macros, `return`, etc.
891 /// N.B., this does not parse outer attributes, and is private because it only works
892 /// correctly if called from `parse_dot_or_call_expr()`.
893 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
894 maybe_recover_from_interpolated_ty_qpath!(self, true);
895 maybe_whole_expr!(self);
897 // Outer attributes are already parsed and will be
898 // added to the return value after the fact.
900 // Therefore, prevent sub-parser from parsing
901 // attributes by giving them a empty "already-parsed" list.
902 let attrs = AttrVec::new();
904 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
905 let lo = self.token.span;
906 if let token::Literal(_) = self.token.kind {
907 // This match arm is a special-case of the `_` match arm below and
908 // could be removed without changing functionality, but it's faster
909 // to have it here, especially for programs with large constants.
910 self.parse_lit_expr(attrs)
911 } else if self.check(&token::OpenDelim(token::Paren)) {
912 self.parse_tuple_parens_expr(attrs)
913 } else if self.check(&token::OpenDelim(token::Brace)) {
914 self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs)
915 } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) {
916 self.parse_closure_expr(attrs)
917 } else if self.check(&token::OpenDelim(token::Bracket)) {
918 self.parse_array_or_repeat_expr(attrs)
919 } else if self.eat_lt() {
920 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
921 Ok(self.mk_expr(lo.to(path.span), ExprKind::Path(Some(qself), path), attrs))
922 } else if self.check_path() {
923 self.parse_path_start_expr(attrs)
924 } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
925 self.parse_closure_expr(attrs)
926 } else if self.eat_keyword(kw::If) {
927 self.parse_if_expr(attrs)
928 } else if self.eat_keyword(kw::For) {
929 self.parse_for_expr(None, self.prev_token.span, attrs)
930 } else if self.eat_keyword(kw::While) {
931 self.parse_while_expr(None, self.prev_token.span, attrs)
932 } else if let Some(label) = self.eat_label() {
933 self.parse_labeled_expr(label, attrs)
934 } else if self.eat_keyword(kw::Loop) {
935 self.parse_loop_expr(None, self.prev_token.span, attrs)
936 } else if self.eat_keyword(kw::Continue) {
937 let kind = ExprKind::Continue(self.eat_label());
938 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
939 } else if self.eat_keyword(kw::Match) {
940 let match_sp = self.prev_token.span;
941 self.parse_match_expr(attrs).map_err(|mut err| {
942 err.span_label(match_sp, "while parsing this match expression");
945 } else if self.eat_keyword(kw::Unsafe) {
946 self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs)
947 } else if self.is_do_catch_block() {
948 self.recover_do_catch(attrs)
949 } else if self.is_try_block() {
950 self.expect_keyword(kw::Try)?;
951 self.parse_try_block(lo, attrs)
952 } else if self.eat_keyword(kw::Return) {
953 self.parse_return_expr(attrs)
954 } else if self.eat_keyword(kw::Break) {
955 self.parse_break_expr(attrs)
956 } else if self.eat_keyword(kw::Yield) {
957 self.parse_yield_expr(attrs)
958 } else if self.eat_keyword(kw::Let) {
959 self.parse_let_expr(attrs)
960 } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
961 // Don't complain about bare semicolons after unclosed braces
962 // recovery in order to keep the error count down. Fixing the
963 // delimiters will possibly also fix the bare semicolon found in
964 // expression context. For example, silence the following error:
966 // error: expected expression, found `;`
970 // | ^ expected expression
972 Ok(self.mk_expr_err(self.token.span))
973 } else if self.token.uninterpolated_span().rust_2018() {
974 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
975 if self.check_keyword(kw::Async) {
976 if self.is_async_block() {
977 // Check for `async {` and `async move {`.
978 self.parse_async_block(attrs)
980 self.parse_closure_expr(attrs)
982 } else if self.eat_keyword(kw::Await) {
983 self.recover_incorrect_await_syntax(lo, self.prev_token.span, attrs)
985 self.parse_lit_expr(attrs)
988 self.parse_lit_expr(attrs)
992 fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
993 let lo = self.token.span;
994 match self.parse_opt_lit() {
996 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs);
997 self.maybe_recover_from_bad_qpath(expr, true)
999 None => return Err(self.expected_expression_found()),
1003 fn parse_tuple_parens_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1004 let lo = self.token.span;
1005 self.expect(&token::OpenDelim(token::Paren))?;
1006 attrs.extend(self.parse_inner_attributes()?); // `(#![foo] a, b, ...)` is OK.
1007 let (es, trailing_comma) = match self.parse_seq_to_end(
1008 &token::CloseDelim(token::Paren),
1009 SeqSep::trailing_allowed(token::Comma),
1010 |p| p.parse_expr_catch_underscore(),
1013 Err(err) => return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err))),
1015 let kind = if es.len() == 1 && !trailing_comma {
1016 // `(e)` is parenthesized `e`.
1017 ExprKind::Paren(es.into_iter().next().unwrap())
1019 // `(e,)` is a tuple with only one field, `e`.
1022 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1023 self.maybe_recover_from_bad_qpath(expr, true)
1026 fn parse_array_or_repeat_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1027 let lo = self.token.span;
1030 attrs.extend(self.parse_inner_attributes()?);
1032 let close = &token::CloseDelim(token::Bracket);
1033 let kind = if self.eat(close) {
1035 ExprKind::Array(Vec::new())
1038 let first_expr = self.parse_expr()?;
1039 if self.eat(&token::Semi) {
1040 // Repeating array syntax: `[ 0; 512 ]`
1041 let count = self.parse_anon_const_expr()?;
1042 self.expect(close)?;
1043 ExprKind::Repeat(first_expr, count)
1044 } else if self.eat(&token::Comma) {
1045 // Vector with two or more elements.
1046 let sep = SeqSep::trailing_allowed(token::Comma);
1047 let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1048 let mut exprs = vec![first_expr];
1049 exprs.extend(remaining_exprs);
1050 ExprKind::Array(exprs)
1052 // Vector with one element
1053 self.expect(close)?;
1054 ExprKind::Array(vec![first_expr])
1057 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1058 self.maybe_recover_from_bad_qpath(expr, true)
1061 fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1062 let lo = self.token.span;
1063 let path = self.parse_path(PathStyle::Expr)?;
1065 // `!`, as an operator, is prefix, so we know this isn't that.
1066 let (hi, kind) = if self.eat(&token::Not) {
1067 // MACRO INVOCATION expression
1070 args: self.parse_mac_args()?,
1071 prior_type_ascription: self.last_type_ascription,
1073 (self.prev_token.span, ExprKind::MacCall(mac))
1074 } else if self.check(&token::OpenDelim(token::Brace)) {
1075 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
1078 (path.span, ExprKind::Path(None, path))
1081 (path.span, ExprKind::Path(None, path))
1084 let expr = self.mk_expr(lo.to(hi), kind, attrs);
1085 self.maybe_recover_from_bad_qpath(expr, true)
1088 /// Parse `'label: $expr`. The label is already parsed.
1089 fn parse_labeled_expr(&mut self, label: Label, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1090 let lo = label.ident.span;
1091 let label = Some(label);
1092 let ate_colon = self.eat(&token::Colon);
1093 let expr = if self.eat_keyword(kw::While) {
1094 self.parse_while_expr(label, lo, attrs)
1095 } else if self.eat_keyword(kw::For) {
1096 self.parse_for_expr(label, lo, attrs)
1097 } else if self.eat_keyword(kw::Loop) {
1098 self.parse_loop_expr(label, lo, attrs)
1099 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1100 self.parse_block_expr(label, lo, BlockCheckMode::Default, attrs)
1102 let msg = "expected `while`, `for`, `loop` or `{` after a label";
1103 self.struct_span_err(self.token.span, msg).span_label(self.token.span, msg).emit();
1104 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1109 self.error_labeled_expr_must_be_followed_by_colon(lo, expr.span);
1115 fn error_labeled_expr_must_be_followed_by_colon(&self, lo: Span, span: Span) {
1116 self.struct_span_err(span, "labeled expression must be followed by `:`")
1117 .span_label(lo, "the label")
1118 .span_suggestion_short(
1120 "add `:` after the label",
1122 Applicability::MachineApplicable,
1124 .note("labels are used before loops and blocks, allowing e.g., `break 'label` to them")
1128 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1129 fn recover_do_catch(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1130 let lo = self.token.span;
1132 self.bump(); // `do`
1133 self.bump(); // `catch`
1135 let span_dc = lo.to(self.prev_token.span);
1136 self.struct_span_err(span_dc, "found removed `do catch` syntax")
1139 "replace with the new syntax",
1141 Applicability::MachineApplicable,
1143 .note("following RFC #2388, the new non-placeholder syntax is `try`")
1146 self.parse_try_block(lo, attrs)
1149 /// Parse an expression if the token can begin one.
1150 fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1151 Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1154 /// Parse `"return" expr?`.
1155 fn parse_return_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1156 let lo = self.prev_token.span;
1157 let kind = ExprKind::Ret(self.parse_expr_opt()?);
1158 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1159 self.maybe_recover_from_bad_qpath(expr, true)
1162 /// Parse `"('label ":")? break expr?`.
1163 fn parse_break_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1164 let lo = self.prev_token.span;
1165 let label = self.eat_label();
1166 let kind = if self.token != token::OpenDelim(token::Brace)
1167 || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1169 self.parse_expr_opt()?
1173 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind), attrs);
1174 self.maybe_recover_from_bad_qpath(expr, true)
1177 /// Parse `"yield" expr?`.
1178 fn parse_yield_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1179 let lo = self.prev_token.span;
1180 let kind = ExprKind::Yield(self.parse_expr_opt()?);
1181 let span = lo.to(self.prev_token.span);
1182 self.sess.gated_spans.gate(sym::generators, span);
1183 let expr = self.mk_expr(span, kind, attrs);
1184 self.maybe_recover_from_bad_qpath(expr, true)
1187 /// Returns a string literal if the next token is a string literal.
1188 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1189 /// and returns `None` if the next token is not literal at all.
1190 pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
1191 match self.parse_opt_lit() {
1192 Some(lit) => match lit.kind {
1193 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1195 symbol: lit.token.symbol,
1196 suffix: lit.token.suffix,
1200 _ => Err(Some(lit)),
1206 pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> {
1207 self.parse_opt_lit().ok_or_else(|| {
1208 let msg = format!("unexpected token: {}", super::token_descr(&self.token));
1209 self.struct_span_err(self.token.span, &msg)
1213 /// Matches `lit = true | false | token_lit`.
1214 /// Returns `None` if the next token is not a literal.
1215 pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
1216 let mut recovered = None;
1217 if self.token == token::Dot {
1218 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1219 // dot would follow an optional literal, so we do this unconditionally.
1220 recovered = self.look_ahead(1, |next_token| {
1221 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1224 if self.token.span.hi() == next_token.span.lo() {
1225 let s = String::from("0.") + &symbol.as_str();
1226 let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1227 return Some(Token::new(kind, self.token.span.to(next_token.span)));
1232 if let Some(token) = &recovered {
1234 self.error_float_lits_must_have_int_part(&token);
1238 let token = recovered.as_ref().unwrap_or(&self.token);
1239 match Lit::from_token(token) {
1244 Err(LitError::NotLiteral) => None,
1246 let span = token.span;
1247 let lit = match token.kind {
1248 token::Literal(lit) => lit,
1249 _ => unreachable!(),
1252 self.report_lit_error(err, lit, span);
1253 // Pack possible quotes and prefixes from the original literal into
1254 // the error literal's symbol so they can be pretty-printed faithfully.
1255 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1256 let symbol = Symbol::intern(&suffixless_lit.to_string());
1257 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1258 Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!()))
1263 fn error_float_lits_must_have_int_part(&self, token: &Token) {
1264 self.struct_span_err(token.span, "float literals must have an integer part")
1267 "must have an integer part",
1268 pprust::token_to_string(token),
1269 Applicability::MachineApplicable,
1274 fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) {
1275 // Checks if `s` looks like i32 or u1234 etc.
1276 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1277 s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
1280 let token::Lit { kind, suffix, .. } = lit;
1282 // `NotLiteral` is not an error by itself, so we don't report
1283 // it and give the parser opportunity to try something else.
1284 LitError::NotLiteral => {}
1285 // `LexerError` *is* an error, but it was already reported
1286 // by lexer, so here we don't report it the second time.
1287 LitError::LexerError => {}
1288 LitError::InvalidSuffix => {
1289 self.expect_no_suffix(
1291 &format!("{} {} literal", kind.article(), kind.descr()),
1295 LitError::InvalidIntSuffix => {
1296 let suf = suffix.expect("suffix error with no suffix").as_str();
1297 if looks_like_width_suffix(&['i', 'u'], &suf) {
1298 // If it looks like a width, try to be helpful.
1299 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
1300 self.struct_span_err(span, &msg)
1301 .help("valid widths are 8, 16, 32, 64 and 128")
1304 let msg = format!("invalid suffix `{}` for integer literal", suf);
1305 self.struct_span_err(span, &msg)
1306 .span_label(span, format!("invalid suffix `{}`", suf))
1307 .help("the suffix must be one of the integral types (`u32`, `isize`, etc)")
1311 LitError::InvalidFloatSuffix => {
1312 let suf = suffix.expect("suffix error with no suffix").as_str();
1313 if looks_like_width_suffix(&['f'], &suf) {
1314 // If it looks like a width, try to be helpful.
1315 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
1316 self.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit();
1318 let msg = format!("invalid suffix `{}` for float literal", suf);
1319 self.struct_span_err(span, &msg)
1320 .span_label(span, format!("invalid suffix `{}`", suf))
1321 .help("valid suffixes are `f32` and `f64`")
1325 LitError::NonDecimalFloat(base) => {
1326 let descr = match base {
1327 16 => "hexadecimal",
1330 _ => unreachable!(),
1332 self.struct_span_err(span, &format!("{} float literal is not supported", descr))
1333 .span_label(span, "not supported")
1336 LitError::IntTooLarge => {
1337 self.struct_span_err(span, "integer literal is too large").emit();
1342 pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) {
1343 if let Some(suf) = suffix {
1344 let mut err = if kind == "a tuple index"
1345 && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf)
1347 // #59553: warn instead of reject out of hand to allow the fix to percolate
1348 // through the ecosystem when people fix their macros
1352 .struct_span_warn(sp, &format!("suffixes on {} are invalid", kind));
1354 "`{}` is *temporarily* accepted on tuple index fields as it was \
1355 incorrectly accepted on stable for a few releases",
1359 "on proc macros, you'll want to use `syn::Index::from` or \
1360 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1361 to tuple field access",
1364 "see issue #60210 <https://github.com/rust-lang/rust/issues/60210> \
1365 for more information",
1369 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1371 err.span_label(sp, format!("invalid suffix `{}`", suf));
1376 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1377 pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1378 maybe_whole_expr!(self);
1380 let lo = self.token.span;
1381 let minus_present = self.eat(&token::BinOp(token::Minus));
1382 let lit = self.parse_lit()?;
1383 let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new());
1387 lo.to(self.prev_token.span),
1388 self.mk_unary(UnOp::Neg, expr),
1396 /// Parses a block or unsafe block.
1397 pub(super) fn parse_block_expr(
1399 opt_label: Option<Label>,
1401 blk_mode: BlockCheckMode,
1403 ) -> PResult<'a, P<Expr>> {
1404 if let Some(label) = opt_label {
1405 self.sess.gated_spans.gate(sym::label_break_value, label.ident.span);
1408 if self.token.is_whole_block() {
1409 self.struct_span_err(self.token.span, "cannot use a `block` macro fragment here")
1410 .span_label(lo.to(self.token.span), "the `block` fragment is within this context")
1414 let (inner_attrs, blk) = self.parse_block_common(lo, blk_mode)?;
1415 attrs.extend(inner_attrs);
1416 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs))
1419 /// Parses a closure expression (e.g., `move |args| expr`).
1420 fn parse_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1421 let lo = self.token.span;
1424 if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
1426 let asyncness = if self.token.uninterpolated_span().rust_2018() {
1427 self.parse_asyncness()
1431 if let Async::Yes { span, .. } = asyncness {
1432 // Feature-gate `async ||` closures.
1433 self.sess.gated_spans.gate(sym::async_closure, span);
1436 let capture_clause = self.parse_capture_clause();
1437 let decl = self.parse_fn_block_decl()?;
1438 let decl_hi = self.prev_token.span;
1439 let body = match decl.output {
1440 FnRetTy::Default(_) => {
1441 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
1442 self.parse_expr_res(restrictions, None)?
1445 // If an explicit return type is given, require a block to appear (RFC 968).
1446 let body_lo = self.token.span;
1447 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, AttrVec::new())?
1453 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
1458 /// Parses an optional `move` prefix to a closure-like construct.
1459 fn parse_capture_clause(&mut self) -> CaptureBy {
1460 if self.eat_keyword(kw::Move) { CaptureBy::Value } else { CaptureBy::Ref }
1463 /// Parses the `|arg, arg|` header of a closure.
1464 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
1465 let inputs = if self.eat(&token::OrOr) {
1468 self.expect(&token::BinOp(token::Or))?;
1470 .parse_seq_to_before_tokens(
1471 &[&token::BinOp(token::Or), &token::OrOr],
1472 SeqSep::trailing_allowed(token::Comma),
1473 TokenExpectType::NoExpect,
1474 |p| p.parse_fn_block_param(),
1480 let output = self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes)?;
1482 Ok(P(FnDecl { inputs, output }))
1485 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1486 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
1487 let lo = self.token.span;
1488 let attrs = self.parse_outer_attributes()?;
1489 let pat = self.parse_pat(PARAM_EXPECTED)?;
1490 let ty = if self.eat(&token::Colon) {
1493 self.mk_ty(self.prev_token.span, TyKind::Infer)
1496 attrs: attrs.into(),
1499 span: lo.to(self.token.span),
1501 is_placeholder: false,
1505 /// Parses an `if` expression (`if` token already eaten).
1506 fn parse_if_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1507 let lo = self.prev_token.span;
1508 let cond = self.parse_cond_expr()?;
1510 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1511 // verify that the last statement is either an implicit return (no `;`) or an explicit
1512 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1513 // the dead code lint.
1514 let thn = if self.eat_keyword(kw::Else) || !cond.returns() {
1515 self.error_missing_if_cond(lo, cond.span)
1517 let attrs = self.parse_outer_attributes()?; // For recovery.
1518 let not_block = self.token != token::OpenDelim(token::Brace);
1519 let block = self.parse_block().map_err(|mut err| {
1521 err.span_label(lo, "this `if` expression has a condition, but no block");
1525 self.error_on_if_block_attrs(lo, false, block.span, &attrs);
1528 let els = if self.eat_keyword(kw::Else) { Some(self.parse_else_expr()?) } else { None };
1529 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els), attrs))
1532 fn error_missing_if_cond(&self, lo: Span, span: Span) -> P<ast::Block> {
1533 let sp = self.sess.source_map().next_point(lo);
1534 self.struct_span_err(sp, "missing condition for `if` expression")
1535 .span_label(sp, "expected if condition here")
1537 self.mk_block_err(span)
1540 /// Parses the condition of a `if` or `while` expression.
1541 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
1542 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1544 if let ExprKind::Let(..) = cond.kind {
1545 // Remove the last feature gating of a `let` expression since it's stable.
1546 self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
1552 /// Parses a `let $pat = $expr` pseudo-expression.
1553 /// The `let` token has already been eaten.
1554 fn parse_let_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1555 let lo = self.prev_token.span;
1556 let pat = self.parse_top_pat(GateOr::No)?;
1557 self.expect(&token::Eq)?;
1558 let expr = self.with_res(Restrictions::NO_STRUCT_LITERAL, |this| {
1559 this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
1561 let span = lo.to(expr.span);
1562 self.sess.gated_spans.gate(sym::let_chains, span);
1563 Ok(self.mk_expr(span, ExprKind::Let(pat, expr), attrs))
1566 /// Parses an `else { ... }` expression (`else` token already eaten).
1567 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
1568 let ctx_span = self.prev_token.span; // `else`
1569 let attrs = self.parse_outer_attributes()?; // For recovery.
1570 let expr = if self.eat_keyword(kw::If) {
1571 self.parse_if_expr(AttrVec::new())?
1573 let blk = self.parse_block()?;
1574 self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new())
1576 self.error_on_if_block_attrs(ctx_span, true, expr.span, &attrs);
1580 fn error_on_if_block_attrs(
1585 attrs: &[ast::Attribute],
1587 let (span, last) = match attrs {
1589 [x0 @ xn] | [x0, .., xn] => (x0.span.to(xn.span), xn.span),
1591 let ctx = if is_ctx_else { "else" } else { "if" };
1592 self.struct_span_err(last, "outer attributes are not allowed on `if` and `else` branches")
1593 .span_label(branch_span, "the attributes are attached to this branch")
1594 .span_label(ctx_span, format!("the branch belongs to this `{}`", ctx))
1597 "remove the attributes",
1599 Applicability::MachineApplicable,
1604 /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
1607 opt_label: Option<Label>,
1610 ) -> PResult<'a, P<Expr>> {
1611 // Record whether we are about to parse `for (`.
1612 // This is used below for recovery in case of `for ( $stuff ) $block`
1613 // in which case we will suggest `for $stuff $block`.
1614 let begin_paren = match self.token.kind {
1615 token::OpenDelim(token::Paren) => Some(self.token.span),
1619 let pat = self.parse_top_pat(GateOr::Yes)?;
1620 if !self.eat_keyword(kw::In) {
1621 self.error_missing_in_for_loop();
1623 self.check_for_for_in_in_typo(self.prev_token.span);
1624 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1626 let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
1628 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
1629 attrs.extend(iattrs);
1631 let kind = ExprKind::ForLoop(pat, expr, loop_block, opt_label);
1632 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1635 fn error_missing_in_for_loop(&self) {
1636 let in_span = self.prev_token.span.between(self.token.span);
1637 self.struct_span_err(in_span, "missing `in` in `for` loop")
1638 .span_suggestion_short(
1640 "try adding `in` here",
1642 // Has been misleading, at least in the past (closed Issue #48492).
1643 Applicability::MaybeIncorrect,
1648 /// Parses a `while` or `while let` expression (`while` token already eaten).
1649 fn parse_while_expr(
1651 opt_label: Option<Label>,
1654 ) -> PResult<'a, P<Expr>> {
1655 let cond = self.parse_cond_expr()?;
1656 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1657 attrs.extend(iattrs);
1658 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::While(cond, body, opt_label), attrs))
1661 /// Parses `loop { ... }` (`loop` token already eaten).
1664 opt_label: Option<Label>,
1667 ) -> PResult<'a, P<Expr>> {
1668 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1669 attrs.extend(iattrs);
1670 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::Loop(body, opt_label), attrs))
1673 fn eat_label(&mut self) -> Option<Label> {
1674 self.token.lifetime().map(|ident| {
1680 /// Parses a `match ... { ... }` expression (`match` token already eaten).
1681 fn parse_match_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1682 let match_span = self.prev_token.span;
1683 let lo = self.prev_token.span;
1684 let scrutinee = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1685 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
1686 if self.token == token::Semi {
1687 e.span_suggestion_short(
1689 "try removing this `match`",
1691 Applicability::MaybeIncorrect, // speculative
1696 attrs.extend(self.parse_inner_attributes()?);
1698 let mut arms: Vec<Arm> = Vec::new();
1699 while self.token != token::CloseDelim(token::Brace) {
1700 match self.parse_arm() {
1701 Ok(arm) => arms.push(arm),
1703 // Recover by skipping to the end of the block.
1705 self.recover_stmt();
1706 let span = lo.to(self.token.span);
1707 if self.token == token::CloseDelim(token::Brace) {
1710 return Ok(self.mk_expr(span, ExprKind::Match(scrutinee, arms), attrs));
1714 let hi = self.token.span;
1716 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(scrutinee, arms), attrs));
1719 pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
1720 let attrs = self.parse_outer_attributes()?;
1721 let lo = self.token.span;
1722 let pat = self.parse_top_pat(GateOr::No)?;
1723 let guard = if self.eat_keyword(kw::If) { Some(self.parse_expr()?) } else { None };
1724 let arrow_span = self.token.span;
1725 self.expect(&token::FatArrow)?;
1726 let arm_start_span = self.token.span;
1728 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| {
1729 err.span_label(arrow_span, "while parsing the `match` arm starting here");
1733 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
1734 && self.token != token::CloseDelim(token::Brace);
1736 let hi = self.token.span;
1739 let sm = self.sess.source_map();
1740 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]).map_err(
1742 match (sm.span_to_lines(expr.span), sm.span_to_lines(arm_start_span)) {
1743 (Ok(ref expr_lines), Ok(ref arm_start_lines))
1744 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
1745 && expr_lines.lines.len() == 2
1746 && self.token == token::FatArrow =>
1748 // We check whether there's any trailing code in the parse span,
1749 // if there isn't, we very likely have the following:
1752 // | -- - missing comma
1756 // | - ^^ self.token.span
1758 // | parsed until here as `"y" & X`
1759 err.span_suggestion_short(
1760 arm_start_span.shrink_to_hi(),
1761 "missing a comma here to end this `match` arm",
1763 Applicability::MachineApplicable,
1769 "while parsing the `match` arm starting here",
1777 self.eat(&token::Comma);
1787 is_placeholder: false,
1791 /// Parses a `try {...}` expression (`try` token already eaten).
1792 fn parse_try_block(&mut self, span_lo: Span, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1793 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1794 attrs.extend(iattrs);
1795 if self.eat_keyword(kw::Catch) {
1796 let mut error = self.struct_span_err(
1797 self.prev_token.span,
1798 "keyword `catch` cannot follow a `try` block",
1800 error.help("try using `match` on the result of the `try` block instead");
1804 let span = span_lo.to(body.span);
1805 self.sess.gated_spans.gate(sym::try_blocks, span);
1806 Ok(self.mk_expr(span, ExprKind::TryBlock(body), attrs))
1810 fn is_do_catch_block(&self) -> bool {
1811 self.token.is_keyword(kw::Do)
1812 && self.is_keyword_ahead(1, &[kw::Catch])
1813 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
1814 && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1817 fn is_try_block(&self) -> bool {
1818 self.token.is_keyword(kw::Try) &&
1819 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
1820 self.token.uninterpolated_span().rust_2018() &&
1821 // Prevent `while try {} {}`, `if try {} {} else {}`, etc.
1822 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1825 /// Parses an `async move? {...}` expression.
1826 fn parse_async_block(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1827 let lo = self.token.span;
1828 self.expect_keyword(kw::Async)?;
1829 let capture_clause = self.parse_capture_clause();
1830 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1831 attrs.extend(iattrs);
1832 let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);
1833 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1836 fn is_async_block(&self) -> bool {
1837 self.token.is_keyword(kw::Async)
1840 self.is_keyword_ahead(1, &[kw::Move])
1841 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
1844 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
1848 fn is_certainly_not_a_block(&self) -> bool {
1849 self.look_ahead(1, |t| t.is_ident())
1851 // `{ ident, ` cannot start a block.
1852 self.look_ahead(2, |t| t == &token::Comma)
1853 || self.look_ahead(2, |t| t == &token::Colon)
1855 // `{ ident: token, ` cannot start a block.
1856 self.look_ahead(4, |t| t == &token::Comma) ||
1857 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
1858 self.look_ahead(3, |t| !t.can_begin_type())
1863 fn maybe_parse_struct_expr(
1868 ) -> Option<PResult<'a, P<Expr>>> {
1869 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
1870 if struct_allowed || self.is_certainly_not_a_block() {
1871 // This is a struct literal, but we don't can't accept them here.
1872 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
1873 if let (Ok(expr), false) = (&expr, struct_allowed) {
1874 self.error_struct_lit_not_allowed_here(lo, expr.span);
1881 fn error_struct_lit_not_allowed_here(&self, lo: Span, sp: Span) {
1882 self.struct_span_err(sp, "struct literals are not allowed here")
1883 .multipart_suggestion(
1884 "surround the struct literal with parentheses",
1885 vec![(lo.shrink_to_lo(), "(".to_string()), (sp.shrink_to_hi(), ")".to_string())],
1886 Applicability::MachineApplicable,
1891 pub(super) fn parse_struct_expr(
1896 ) -> PResult<'a, P<Expr>> {
1897 let struct_sp = lo.to(self.prev_token.span);
1899 let mut fields = Vec::new();
1900 let mut base = None;
1902 attrs.extend(self.parse_inner_attributes()?);
1904 while self.token != token::CloseDelim(token::Brace) {
1905 if self.eat(&token::DotDot) {
1906 let exp_span = self.prev_token.span;
1907 match self.parse_expr() {
1908 Ok(e) => base = Some(e),
1911 self.recover_stmt();
1914 self.recover_struct_comma_after_dotdot(exp_span);
1918 let recovery_field = self.find_struct_error_after_field_looking_code();
1919 let parsed_field = match self.parse_field() {
1922 e.span_label(struct_sp, "while parsing this struct");
1925 // If the next token is a comma, then try to parse
1926 // what comes next as additional fields, rather than
1927 // bailing out until next `}`.
1928 if self.token != token::Comma {
1929 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
1930 if self.token != token::Comma {
1938 match self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]) {
1940 if let Some(f) = parsed_field.or(recovery_field) {
1941 // Only include the field if there's no parse error for the field name.
1946 e.span_label(struct_sp, "while parsing this struct");
1947 if let Some(f) = recovery_field {
1950 self.prev_token.span.shrink_to_hi(),
1951 "try adding a comma",
1953 Applicability::MachineApplicable,
1957 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
1958 self.eat(&token::Comma);
1963 let span = lo.to(self.token.span);
1964 self.expect(&token::CloseDelim(token::Brace))?;
1965 Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs))
1968 /// Use in case of error after field-looking code: `S { foo: () with a }`.
1969 fn find_struct_error_after_field_looking_code(&self) -> Option<Field> {
1970 match self.token.ident() {
1971 Some((ident, is_raw))
1972 if (is_raw || !ident.is_reserved())
1973 && self.look_ahead(1, |t| *t == token::Colon) =>
1977 span: self.token.span,
1978 expr: self.mk_expr_err(self.token.span),
1979 is_shorthand: false,
1980 attrs: AttrVec::new(),
1982 is_placeholder: false,
1989 fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
1990 if self.token != token::Comma {
1993 self.struct_span_err(
1994 span.to(self.prev_token.span),
1995 "cannot use a comma after the base struct",
1997 .span_suggestion_short(
1999 "remove this comma",
2001 Applicability::MachineApplicable,
2003 .note("the base struct must always be the last field")
2005 self.recover_stmt();
2008 /// Parses `ident (COLON expr)?`.
2009 fn parse_field(&mut self) -> PResult<'a, Field> {
2010 let attrs = self.parse_outer_attributes()?.into();
2011 let lo = self.token.span;
2013 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2014 let is_shorthand = !self.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
2015 let (ident, expr) = if is_shorthand {
2016 // Mimic `x: x` for the `x` field shorthand.
2017 let ident = self.parse_ident_common(false)?;
2018 let path = ast::Path::from_ident(ident);
2019 (ident, self.mk_expr(ident.span, ExprKind::Path(None, path), AttrVec::new()))
2021 let ident = self.parse_field_name()?;
2022 self.error_on_eq_field_init(ident);
2024 (ident, self.parse_expr()?)
2028 span: lo.to(expr.span),
2033 is_placeholder: false,
2037 /// Check for `=`. This means the source incorrectly attempts to
2038 /// initialize a field with an eq rather than a colon.
2039 fn error_on_eq_field_init(&self, field_name: Ident) {
2040 if self.token != token::Eq {
2044 self.struct_span_err(self.token.span, "expected `:`, found `=`")
2046 field_name.span.shrink_to_hi().to(self.token.span),
2047 "replace equals symbol with a colon",
2049 Applicability::MachineApplicable,
2054 fn err_dotdotdot_syntax(&self, span: Span) {
2055 self.struct_span_err(span, "unexpected token: `...`")
2058 "use `..` for an exclusive range",
2060 Applicability::MaybeIncorrect,
2064 "or `..=` for an inclusive range",
2066 Applicability::MaybeIncorrect,
2071 fn err_larrow_operator(&self, span: Span) {
2072 self.struct_span_err(span, "unexpected token: `<-`")
2075 "if you meant to write a comparison against a negative value, add a \
2076 space in between `<` and `-`",
2078 Applicability::MaybeIncorrect,
2083 fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2084 ExprKind::AssignOp(binop, lhs, rhs)
2089 start: Option<P<Expr>>,
2090 end: Option<P<Expr>>,
2091 limits: RangeLimits,
2092 ) -> PResult<'a, ExprKind> {
2093 if end.is_none() && limits == RangeLimits::Closed {
2094 self.error_inclusive_range_with_no_end(self.prev_token.span);
2097 Ok(ExprKind::Range(start, end, limits))
2101 fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
2102 ExprKind::Unary(unop, expr)
2105 fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2106 ExprKind::Binary(binop, lhs, rhs)
2109 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
2110 ExprKind::Index(expr, idx)
2113 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
2114 ExprKind::Call(f, args)
2117 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2118 let span = lo.to(self.prev_token.span);
2119 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), AttrVec::new());
2120 self.recover_from_await_method_call();
2124 crate fn mk_expr(&self, span: Span, kind: ExprKind, attrs: AttrVec) -> P<Expr> {
2125 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID })
2128 pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
2129 self.mk_expr(span, ExprKind::Err, AttrVec::new())