1 use super::pat
::{RecoverColon, RecoverComma, PARAM_EXPECTED}
;
2 use super::ty
::{AllowPlus, RecoverQPath, RecoverReturnSign}
;
3 use super::{AttrWrapper, BlockMode, ForceCollect, Parser, PathStyle, Restrictions, TokenType}
;
4 use super::{SemiColonMode, SeqSep, TokenExpectType, TrailingToken}
;
5 use crate::maybe_recover_from_interpolated_ty_qpath
;
8 use rustc_ast
::token
::{self, Token, TokenKind}
;
9 use rustc_ast
::tokenstream
::Spacing
;
10 use rustc_ast
::util
::classify
;
11 use rustc_ast
::util
::literal
::LitError
;
12 use rustc_ast
::util
::parser
::{prec_let_scrutinee_needs_par, AssocOp, Fixity}
;
13 use rustc_ast
::{self as ast, AttrStyle, AttrVec, CaptureBy, ExprField, Lit, UnOp, DUMMY_NODE_ID}
;
14 use rustc_ast
::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty, TyKind}
;
15 use rustc_ast
::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits}
;
16 use rustc_ast_pretty
::pprust
;
17 use rustc_errors
::{Applicability, DiagnosticBuilder, PResult}
;
18 use rustc_session
::lint
::builtin
::BREAK_WITH_LABEL_AND_LOOP
;
19 use rustc_session
::lint
::BuiltinLintDiagnostics
;
20 use rustc_span
::edition
::LATEST_STABLE_EDITION
;
21 use rustc_span
::source_map
::{self, Span, Spanned}
;
22 use rustc_span
::symbol
::{kw, sym, Ident, Symbol}
;
23 use rustc_span
::{BytePos, Pos}
;
26 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
27 /// dropped into the token stream, which happens while parsing the result of
28 /// macro expansion). Placement of these is not as complex as I feared it would
29 /// be. The important thing is to make sure that lookahead doesn't balk at
30 /// `token::Interpolated` tokens.
31 macro_rules
! maybe_whole_expr
{
33 if let token
::Interpolated(nt
) = &$p
.token
.kind
{
35 token
::NtExpr(e
) | token
::NtLiteral(e
) => {
40 token
::NtPath(path
) => {
41 let path
= path
.clone();
45 ExprKind
::Path(None
, path
),
49 token
::NtBlock(block
) => {
50 let block
= block
.clone();
54 ExprKind
::Block(block
, None
),
65 pub(super) enum LhsExpr
{
67 AttributesParsed(AttrWrapper
),
68 AlreadyParsed(P
<Expr
>),
71 impl From
<Option
<AttrWrapper
>> for LhsExpr
{
72 /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
73 /// and `None` into `LhsExpr::NotYetParsed`.
75 /// This conversion does not allocate.
76 fn from(o
: Option
<AttrWrapper
>) -> Self {
77 if let Some(attrs
) = o { LhsExpr::AttributesParsed(attrs) }
else { LhsExpr::NotYetParsed }
81 impl From
<P
<Expr
>> for LhsExpr
{
82 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
84 /// This conversion does not allocate.
85 fn from(expr
: P
<Expr
>) -> Self {
86 LhsExpr
::AlreadyParsed(expr
)
91 /// Parses an expression.
93 pub fn parse_expr(&mut self) -> PResult
<'a
, P
<Expr
>> {
94 self.parse_expr_res(Restrictions
::empty(), None
)
97 /// Parses an expression, forcing tokens to be collected
98 pub fn parse_expr_force_collect(&mut self) -> PResult
<'a
, P
<Expr
>> {
99 self.collect_tokens_no_attrs(|this
| this
.parse_expr())
102 pub fn parse_anon_const_expr(&mut self) -> PResult
<'a
, AnonConst
> {
103 self.parse_expr().map(|value
| AnonConst { id: DUMMY_NODE_ID, value }
)
106 fn parse_expr_catch_underscore(&mut self) -> PResult
<'a
, P
<Expr
>> {
107 match self.parse_expr() {
108 Ok(expr
) => Ok(expr
),
109 Err(mut err
) => match self.token
.ident() {
110 Some((Ident { name: kw::Underscore, .. }
, false))
111 if self.look_ahead(1, |t
| t
== &token
::Comma
) =>
113 // Special-case handling of `foo(_, _, _)`
116 Ok(self.mk_expr(self.prev_token
.span
, ExprKind
::Err
, AttrVec
::new()))
123 /// Parses a sequence of expressions delimited by parentheses.
124 fn parse_paren_expr_seq(&mut self) -> PResult
<'a
, Vec
<P
<Expr
>>> {
125 self.parse_paren_comma_seq(|p
| p
.parse_expr_catch_underscore()).map(|(r
, _
)| r
)
128 /// Parses an expression, subject to the given restrictions.
130 pub(super) fn parse_expr_res(
133 already_parsed_attrs
: Option
<AttrWrapper
>,
134 ) -> PResult
<'a
, P
<Expr
>> {
135 self.with_res(r
, |this
| this
.parse_assoc_expr(already_parsed_attrs
))
138 /// Parses an associative expression.
140 /// This parses an expression accounting for associativity and precedence of the operators in
145 already_parsed_attrs
: Option
<AttrWrapper
>,
146 ) -> PResult
<'a
, P
<Expr
>> {
147 self.parse_assoc_expr_with(0, already_parsed_attrs
.into())
150 /// Parses an associative expression with operators of at least `min_prec` precedence.
151 pub(super) fn parse_assoc_expr_with(
155 ) -> PResult
<'a
, P
<Expr
>> {
156 let mut lhs
= if let LhsExpr
::AlreadyParsed(expr
) = lhs
{
159 let attrs
= match lhs
{
160 LhsExpr
::AttributesParsed(attrs
) => Some(attrs
),
163 if [token
::DotDot
, token
::DotDotDot
, token
::DotDotEq
].contains(&self.token
.kind
) {
164 return self.parse_prefix_range_expr(attrs
);
166 self.parse_prefix_expr(attrs
)?
169 let last_type_ascription_set
= self.last_type_ascription
.is_some();
171 if !self.should_continue_as_assoc_expr(&lhs
) {
172 self.last_type_ascription
= None
;
176 self.expected_tokens
.push(TokenType
::Operator
);
177 while let Some(op
) = self.check_assoc_op() {
178 // Adjust the span for interpolated LHS to point to the `$lhs` token
179 // and not to what it refers to.
180 let lhs_span
= match self.prev_token
.kind
{
181 TokenKind
::Interpolated(..) => self.prev_token
.span
,
185 let cur_op_span
= self.token
.span
;
186 let restrictions
= if op
.node
.is_assign_like() {
187 self.restrictions
& Restrictions
::NO_STRUCT_LITERAL
191 let prec
= op
.node
.precedence();
195 // Check for deprecated `...` syntax
196 if self.token
== token
::DotDotDot
&& op
.node
== AssocOp
::DotDotEq
{
197 self.err_dotdotdot_syntax(self.token
.span
);
200 if self.token
== token
::LArrow
{
201 self.err_larrow_operator(self.token
.span
);
205 if op
.node
.is_comparison() {
206 if let Some(expr
) = self.check_no_chained_comparison(&lhs
, &op
)?
{
211 if (op
.node
== AssocOp
::Equal
|| op
.node
== AssocOp
::NotEqual
)
212 && self.token
.kind
== token
::Eq
213 && self.prev_token
.span
.hi() == self.token
.span
.lo()
215 // Look for JS' `===` and `!==` and recover 😇
216 let sp
= op
.span
.to(self.token
.span
);
217 let sugg
= match op
.node
{
218 AssocOp
::Equal
=> "==",
219 AssocOp
::NotEqual
=> "!=",
222 self.struct_span_err(sp
, &format
!("invalid comparison operator `{}=`", sugg
))
223 .span_suggestion_short(
225 &format
!("`{s}=` is not a valid comparison operator, use `{s}`", s
= sugg
),
227 Applicability
::MachineApplicable
,
235 if op
== AssocOp
::As
{
236 lhs
= self.parse_assoc_op_cast(lhs
, lhs_span
, ExprKind
::Cast
)?
;
238 } else if op
== AssocOp
::Colon
{
239 lhs
= self.parse_assoc_op_ascribe(lhs
, lhs_span
)?
;
241 } else if op
== AssocOp
::DotDot
|| op
== AssocOp
::DotDotEq
{
242 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
243 // generalise it to the Fixity::None code.
244 lhs
= self.parse_range_expr(prec
, lhs
, op
, cur_op_span
)?
;
248 let fixity
= op
.fixity();
249 let prec_adjustment
= match fixity
{
252 // We currently have no non-associative operators that are not handled above by
253 // the special cases. The code is here only for future convenience.
256 let rhs
= self.with_res(restrictions
- Restrictions
::STMT_EXPR
, |this
| {
257 this
.parse_assoc_expr_with(prec
+ prec_adjustment
, LhsExpr
::NotYetParsed
)
260 let span
= self.mk_expr_sp(&lhs
, lhs_span
, rhs
.span
);
273 | AssocOp
::ShiftRight
279 | AssocOp
::GreaterEqual
=> {
280 let ast_op
= op
.to_ast_binop().unwrap();
281 let binary
= self.mk_binary(source_map
::respan(cur_op_span
, ast_op
), lhs
, rhs
);
282 self.mk_expr(span
, binary
, AttrVec
::new())
285 self.mk_expr(span
, ExprKind
::Assign(lhs
, rhs
, cur_op_span
), AttrVec
::new())
287 AssocOp
::AssignOp(k
) => {
289 token
::Plus
=> BinOpKind
::Add
,
290 token
::Minus
=> BinOpKind
::Sub
,
291 token
::Star
=> BinOpKind
::Mul
,
292 token
::Slash
=> BinOpKind
::Div
,
293 token
::Percent
=> BinOpKind
::Rem
,
294 token
::Caret
=> BinOpKind
::BitXor
,
295 token
::And
=> BinOpKind
::BitAnd
,
296 token
::Or
=> BinOpKind
::BitOr
,
297 token
::Shl
=> BinOpKind
::Shl
,
298 token
::Shr
=> BinOpKind
::Shr
,
300 let aopexpr
= self.mk_assign_op(source_map
::respan(cur_op_span
, aop
), lhs
, rhs
);
301 self.mk_expr(span
, aopexpr
, AttrVec
::new())
303 AssocOp
::As
| AssocOp
::Colon
| AssocOp
::DotDot
| AssocOp
::DotDotEq
=> {
304 self.span_bug(span
, "AssocOp should have been handled by special case")
308 if let Fixity
::None
= fixity
{
312 if last_type_ascription_set
{
313 self.last_type_ascription
= None
;
318 fn should_continue_as_assoc_expr(&mut self, lhs
: &Expr
) -> bool
{
319 match (self.expr_is_complete(lhs
), AssocOp
::from_token(&self.token
)) {
320 // Semi-statement forms are odd:
321 // See https://github.com/rust-lang/rust/issues/29071
322 (true, None
) => false,
323 (false, _
) => true, // Continue parsing the expression.
324 // An exhaustive check is done in the following block, but these are checked first
325 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
326 // want to keep their span info to improve diagnostics in these cases in a later stage.
327 (true, Some(AssocOp
::Multiply
)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
328 (true, Some(AssocOp
::Subtract
)) | // `{ 42 } -5`
329 (true, Some(AssocOp
::Add
)) // `{ 42 } + 42
330 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
331 // `if x { a } else { b } && if y { c } else { d }`
332 if !self.look_ahead(1, |t
| t
.is_used_keyword()) => {
333 // These cases are ambiguous and can't be identified in the parser alone.
334 let sp
= self.sess
.source_map().start_point(self.token
.span
);
335 self.sess
.ambiguous_block_expr_parse
.borrow_mut().insert(sp
, lhs
.span
);
338 (true, Some(AssocOp
::LAnd
)) => {
339 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`. Separated from the
340 // above due to #74233.
341 // These cases are ambiguous and can't be identified in the parser alone.
342 let sp
= self.sess
.source_map().start_point(self.token
.span
);
343 self.sess
.ambiguous_block_expr_parse
.borrow_mut().insert(sp
, lhs
.span
);
346 (true, Some(ref op
)) if !op
.can_continue_expr_unambiguously() => false,
348 self.error_found_expr_would_be_stmt(lhs
);
354 /// We've found an expression that would be parsed as a statement,
355 /// but the next token implies this should be parsed as an expression.
356 /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
357 fn error_found_expr_would_be_stmt(&self, lhs
: &Expr
) {
358 let mut err
= self.struct_span_err(
360 &format
!("expected expression, found `{}`", pprust
::token_to_string(&self.token
),),
362 err
.span_label(self.token
.span
, "expected expression");
363 self.sess
.expr_parentheses_needed(&mut err
, lhs
.span
);
367 /// Possibly translate the current token to an associative operator.
368 /// The method does not advance the current token.
370 /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
371 fn check_assoc_op(&self) -> Option
<Spanned
<AssocOp
>> {
372 let (op
, span
) = match (AssocOp
::from_token(&self.token
), self.token
.ident()) {
373 // When parsing const expressions, stop parsing when encountering `>`.
378 | AssocOp
::GreaterEqual
379 | AssocOp
::AssignOp(token
::BinOpToken
::Shr
),
382 ) if self.restrictions
.contains(Restrictions
::CONST_EXPR
) => {
385 (Some(op
), _
) => (op
, self.token
.span
),
386 (None
, Some((Ident { name: sym::and, span }
, false))) => {
387 self.error_bad_logical_op("and", "&&", "conjunction");
388 (AssocOp
::LAnd
, span
)
390 (None
, Some((Ident { name: sym::or, span }
, false))) => {
391 self.error_bad_logical_op("or", "||", "disjunction");
396 Some(source_map
::respan(span
, op
))
399 /// Error on `and` and `or` suggesting `&&` and `||` respectively.
400 fn error_bad_logical_op(&self, bad
: &str, good
: &str, english
: &str) {
401 self.struct_span_err(self.token
.span
, &format
!("`{}` is not a logical operator", bad
))
402 .span_suggestion_short(
404 &format
!("use `{}` to perform logical {}", good
, english
),
406 Applicability
::MachineApplicable
,
408 .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators")
412 /// Checks if this expression is a successfully parsed statement.
413 fn expr_is_complete(&self, e
: &Expr
) -> bool
{
414 self.restrictions
.contains(Restrictions
::STMT_EXPR
)
415 && !classify
::expr_requires_semi_to_be_stmt(e
)
418 /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
419 /// The other two variants are handled in `parse_prefix_range_expr` below.
426 ) -> PResult
<'a
, P
<Expr
>> {
427 let rhs
= if self.is_at_start_of_range_notation_rhs() {
428 Some(self.parse_assoc_expr_with(prec
+ 1, LhsExpr
::NotYetParsed
)?
)
432 let rhs_span
= rhs
.as_ref().map_or(cur_op_span
, |x
| x
.span
);
433 let span
= self.mk_expr_sp(&lhs
, lhs
.span
, rhs_span
);
435 if op
== AssocOp
::DotDot { RangeLimits::HalfOpen }
else { RangeLimits::Closed }
;
436 let range
= self.mk_range(Some(lhs
), rhs
, limits
);
437 Ok(self.mk_expr(span
, range
, AttrVec
::new()))
440 fn is_at_start_of_range_notation_rhs(&self) -> bool
{
441 if self.token
.can_begin_expr() {
442 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
443 if self.token
== token
::OpenDelim(token
::Brace
) {
444 return !self.restrictions
.contains(Restrictions
::NO_STRUCT_LITERAL
);
452 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
453 fn parse_prefix_range_expr(&mut self, attrs
: Option
<AttrWrapper
>) -> PResult
<'a
, P
<Expr
>> {
454 // Check for deprecated `...` syntax.
455 if self.token
== token
::DotDotDot
{
456 self.err_dotdotdot_syntax(self.token
.span
);
460 [token
::DotDot
, token
::DotDotDot
, token
::DotDotEq
].contains(&self.token
.kind
),
461 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
465 let limits
= match self.token
.kind
{
466 token
::DotDot
=> RangeLimits
::HalfOpen
,
467 _
=> RangeLimits
::Closed
,
469 let op
= AssocOp
::from_token(&self.token
);
470 // FIXME: `parse_prefix_range_expr` is called when the current
471 // token is `DotDot`, `DotDotDot`, or `DotDotEq`. If we haven't already
472 // parsed attributes, then trying to parse them here will always fail.
473 // We should figure out how we want attributes on range expressions to work.
474 let attrs
= self.parse_or_use_outer_attributes(attrs
)?
;
475 self.collect_tokens_for_expr(attrs
, |this
, attrs
| {
476 let lo
= this
.token
.span
;
478 let (span
, opt_end
) = if this
.is_at_start_of_range_notation_rhs() {
479 // RHS must be parsed with more associativity than the dots.
480 this
.parse_assoc_expr_with(op
.unwrap().precedence() + 1, LhsExpr
::NotYetParsed
)
481 .map(|x
| (lo
.to(x
.span
), Some(x
)))?
485 let range
= this
.mk_range(None
, opt_end
, limits
);
486 Ok(this
.mk_expr(span
, range
, attrs
.into()))
490 /// Parses a prefix-unary-operator expr.
491 fn parse_prefix_expr(&mut self, attrs
: Option
<AttrWrapper
>) -> PResult
<'a
, P
<Expr
>> {
492 let attrs
= self.parse_or_use_outer_attributes(attrs
)?
;
493 let lo
= self.token
.span
;
495 macro_rules
! make_it
{
496 ($this
:ident
, $attrs
:expr
, |this
, _
| $body
:expr
) => {
497 $this
.collect_tokens_for_expr($attrs
, |$this
, attrs
| {
498 let (hi
, ex
) = $body?
;
499 Ok($this
.mk_expr(lo
.to(hi
), ex
, attrs
.into()))
506 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
507 match this
.token
.uninterpolate().kind
{
508 token
::Not
=> make_it
!(this
, attrs
, |this
, _
| this
.parse_unary_expr(lo
, UnOp
::Not
)), // `!expr`
509 token
::Tilde
=> make_it
!(this
, attrs
, |this
, _
| this
.recover_tilde_expr(lo
)), // `~expr`
510 token
::BinOp(token
::Minus
) => {
511 make_it
!(this
, attrs
, |this
, _
| this
.parse_unary_expr(lo
, UnOp
::Neg
))
513 token
::BinOp(token
::Star
) => {
514 make_it
!(this
, attrs
, |this
, _
| this
.parse_unary_expr(lo
, UnOp
::Deref
))
516 token
::BinOp(token
::And
) | token
::AndAnd
=> {
517 make_it
!(this
, attrs
, |this
, _
| this
.parse_borrow_expr(lo
))
519 token
::Ident(..) if this
.token
.is_keyword(kw
::Box
) => {
520 make_it
!(this
, attrs
, |this
, _
| this
.parse_box_expr(lo
))
522 token
::Ident(..) if this
.is_mistaken_not_ident_negation() => {
523 make_it
!(this
, attrs
, |this
, _
| this
.recover_not_expr(lo
))
525 _
=> return this
.parse_dot_or_call_expr(Some(attrs
)),
529 fn parse_prefix_expr_common(&mut self, lo
: Span
) -> PResult
<'a
, (Span
, P
<Expr
>)> {
531 let expr
= self.parse_prefix_expr(None
);
532 let (span
, expr
) = self.interpolated_or_expr_span(expr
)?
;
533 Ok((lo
.to(span
), expr
))
536 fn parse_unary_expr(&mut self, lo
: Span
, op
: UnOp
) -> PResult
<'a
, (Span
, ExprKind
)> {
537 let (span
, expr
) = self.parse_prefix_expr_common(lo
)?
;
538 Ok((span
, self.mk_unary(op
, expr
)))
541 // Recover on `!` suggesting for bitwise negation instead.
542 fn recover_tilde_expr(&mut self, lo
: Span
) -> PResult
<'a
, (Span
, ExprKind
)> {
543 self.struct_span_err(lo
, "`~` cannot be used as a unary operator")
544 .span_suggestion_short(
546 "use `!` to perform bitwise not",
548 Applicability
::MachineApplicable
,
552 self.parse_unary_expr(lo
, UnOp
::Not
)
555 /// Parse `box expr`.
556 fn parse_box_expr(&mut self, lo
: Span
) -> PResult
<'a
, (Span
, ExprKind
)> {
557 let (span
, expr
) = self.parse_prefix_expr_common(lo
)?
;
558 self.sess
.gated_spans
.gate(sym
::box_syntax
, span
);
559 Ok((span
, ExprKind
::Box(expr
)))
562 fn is_mistaken_not_ident_negation(&self) -> bool
{
563 let token_cannot_continue_expr
= |t
: &Token
| match t
.uninterpolate().kind
{
564 // These tokens can start an expression after `!`, but
565 // can't continue an expression after an ident
566 token
::Ident(name
, is_raw
) => token
::ident_can_begin_expr(name
, t
.span
, is_raw
),
567 token
::Literal(..) | token
::Pound
=> true,
568 _
=> t
.is_whole_expr(),
570 self.token
.is_ident_named(sym
::not
) && self.look_ahead(1, token_cannot_continue_expr
)
573 /// Recover on `not expr` in favor of `!expr`.
574 fn recover_not_expr(&mut self, lo
: Span
) -> PResult
<'a
, (Span
, ExprKind
)> {
576 let not_token
= self.look_ahead(1, |t
| t
.clone());
577 self.struct_span_err(
579 &format
!("unexpected {} after identifier", super::token_descr(¬_token
)),
581 .span_suggestion_short(
582 // Span the `not` plus trailing whitespace to avoid
583 // trailing whitespace after the `!` in our suggestion
584 self.sess
.source_map().span_until_non_whitespace(lo
.to(not_token
.span
)),
585 "use `!` to perform logical negation",
587 Applicability
::MachineApplicable
,
592 self.parse_unary_expr(lo
, UnOp
::Not
)
595 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
596 fn interpolated_or_expr_span(
598 expr
: PResult
<'a
, P
<Expr
>>,
599 ) -> PResult
<'a
, (Span
, P
<Expr
>)> {
602 match self.prev_token
.kind
{
603 TokenKind
::Interpolated(..) => self.prev_token
.span
,
611 fn parse_assoc_op_cast(
615 expr_kind
: fn(P
<Expr
>, P
<Ty
>) -> ExprKind
,
616 ) -> PResult
<'a
, P
<Expr
>> {
617 let mk_expr
= |this
: &mut Self, lhs
: P
<Expr
>, rhs
: P
<Ty
>| {
619 this
.mk_expr_sp(&lhs
, lhs_span
, rhs
.span
),
625 // Save the state of the parser before parsing type normally, in case there is a
626 // LessThan comparison after this cast.
627 let parser_snapshot_before_type
= self.clone();
628 let cast_expr
= match self.parse_ty_no_plus() {
629 Ok(rhs
) => mk_expr(self, lhs
, rhs
),
630 Err(mut type_err
) => {
631 // Rewind to before attempting to parse the type with generics, to recover
632 // from situations like `x as usize < y` in which we first tried to parse
633 // `usize < y` as a type with generic arguments.
634 let parser_snapshot_after_type
= mem
::replace(self, parser_snapshot_before_type
);
636 // Check for typo of `'a: loop { break 'a }` with a missing `'`.
637 match (&lhs
.kind
, &self.token
.kind
) {
640 ExprKind
::Path(None
, ast
::Path { segments, .. }
),
641 TokenKind
::Ident(kw
::For
| kw
::Loop
| kw
::While
, false),
642 ) if segments
.len() == 1 => {
643 let snapshot
= self.clone();
645 ident
: Ident
::from_str_and_span(
646 &format
!("'{}", segments
[0].ident
),
647 segments
[0].ident
.span
,
650 match self.parse_labeled_expr(label
, AttrVec
::new(), false) {
653 self.struct_span_err(label
.ident
.span
, "malformed loop label")
656 "use the correct loop label format",
657 label
.ident
.to_string(),
658 Applicability
::MachineApplicable
,
672 match self.parse_path(PathStyle
::Expr
) {
674 let (op_noun
, op_verb
) = match self.token
.kind
{
675 token
::Lt
=> ("comparison", "comparing"),
676 token
::BinOp(token
::Shl
) => ("shift", "shifting"),
678 // We can end up here even without `<` being the next token, for
679 // example because `parse_ty_no_plus` returns `Err` on keywords,
680 // but `parse_path` returns `Ok` on them due to error recovery.
681 // Return original error and parser state.
682 *self = parser_snapshot_after_type
;
683 return Err(type_err
);
687 // Successfully parsed the type path leaving a `<` yet to parse.
690 // Report non-fatal diagnostics, keep `x as usize` as an expression
691 // in AST and continue parsing.
693 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
694 pprust
::path_to_string(&path
),
697 let span_after_type
= parser_snapshot_after_type
.token
.span
;
699 mk_expr(self, lhs
, self.mk_ty(path
.span
, TyKind
::Path(None
, path
)));
701 self.struct_span_err(self.token
.span
, &msg
)
703 self.look_ahead(1, |t
| t
.span
).to(span_after_type
),
704 "interpreted as generic arguments",
706 .span_label(self.token
.span
, format
!("not interpreted as {}", op_noun
))
707 .multipart_suggestion(
708 &format
!("try {} the cast value", op_verb
),
710 (expr
.span
.shrink_to_lo(), "(".to_string()),
711 (expr
.span
.shrink_to_hi(), ")".to_string()),
713 Applicability
::MachineApplicable
,
719 Err(mut path_err
) => {
720 // Couldn't parse as a path, return original error and parser state.
722 *self = parser_snapshot_after_type
;
723 return Err(type_err
);
729 self.parse_and_disallow_postfix_after_cast(cast_expr
)
732 /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
733 /// then emits an error and returns the newly parsed tree.
734 /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
735 fn parse_and_disallow_postfix_after_cast(
738 ) -> PResult
<'a
, P
<Expr
>> {
739 // Save the memory location of expr before parsing any following postfix operators.
740 // This will be compared with the memory location of the output expression.
741 // If they different we can assume we parsed another expression because the existing expression is not reallocated.
742 let addr_before
= &*cast_expr
as *const _
as usize;
743 let span
= cast_expr
.span
;
744 let with_postfix
= self.parse_dot_or_call_expr_with_(cast_expr
, span
)?
;
745 let changed
= addr_before
!= &*with_postfix
as *const _
as usize;
747 // Check if an illegal postfix operator has been added after the cast.
748 // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator.
749 if !matches
!(with_postfix
.kind
, ExprKind
::Cast(_
, _
) | ExprKind
::Type(_
, _
)) || changed
{
751 "casts cannot be followed by {}",
752 match with_postfix
.kind
{
753 ExprKind
::Index(_
, _
) => "indexing",
754 ExprKind
::Try(_
) => "?",
755 ExprKind
::Field(_
, _
) => "a field access",
756 ExprKind
::MethodCall(_
, _
, _
) => "a method call",
757 ExprKind
::Call(_
, _
) => "a function call",
758 ExprKind
::Await(_
) => "`.await`",
759 ExprKind
::Err
=> return Ok(with_postfix
),
760 _
=> unreachable
!("parse_dot_or_call_expr_with_ shouldn't produce this"),
763 let mut err
= self.struct_span_err(span
, &msg
);
764 // If type ascription is "likely an error", the user will already be getting a useful
765 // help message, and doesn't need a second.
766 if self.last_type_ascription
.map_or(false, |last_ascription
| last_ascription
.1) {
767 self.maybe_annotate_with_ascription(&mut err
, false);
769 let suggestions
= vec
![
770 (span
.shrink_to_lo(), "(".to_string()),
771 (span
.shrink_to_hi(), ")".to_string()),
773 err
.multipart_suggestion(
774 "try surrounding the expression in parentheses",
776 Applicability
::MachineApplicable
,
784 fn parse_assoc_op_ascribe(&mut self, lhs
: P
<Expr
>, lhs_span
: Span
) -> PResult
<'a
, P
<Expr
>> {
785 let maybe_path
= self.could_ascription_be_path(&lhs
.kind
);
786 self.last_type_ascription
= Some((self.prev_token
.span
, maybe_path
));
787 let lhs
= self.parse_assoc_op_cast(lhs
, lhs_span
, ExprKind
::Type
)?
;
788 self.sess
.gated_spans
.gate(sym
::type_ascription
, lhs
.span
);
792 /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
793 fn parse_borrow_expr(&mut self, lo
: Span
) -> PResult
<'a
, (Span
, ExprKind
)> {
795 let has_lifetime
= self.token
.is_lifetime() && self.look_ahead(1, |t
| t
!= &token
::Colon
);
796 let lifetime
= has_lifetime
.then(|| self.expect_lifetime()); // For recovery, see below.
797 let (borrow_kind
, mutbl
) = self.parse_borrow_modifiers(lo
);
798 let expr
= self.parse_prefix_expr(None
);
799 let (hi
, expr
) = self.interpolated_or_expr_span(expr
)?
;
800 let span
= lo
.to(hi
);
801 if let Some(lt
) = lifetime
{
802 self.error_remove_borrow_lifetime(span
, lt
.ident
.span
);
804 Ok((span
, ExprKind
::AddrOf(borrow_kind
, mutbl
, expr
)))
807 fn error_remove_borrow_lifetime(&self, span
: Span
, lt_span
: Span
) {
808 self.struct_span_err(span
, "borrow expressions cannot be annotated with lifetimes")
809 .span_label(lt_span
, "annotated with lifetime here")
812 "remove the lifetime annotation",
814 Applicability
::MachineApplicable
,
819 /// Parse `mut?` or `raw [ const | mut ]`.
820 fn parse_borrow_modifiers(&mut self, lo
: Span
) -> (ast
::BorrowKind
, ast
::Mutability
) {
821 if self.check_keyword(kw
::Raw
) && self.look_ahead(1, Token
::is_mutability
) {
822 // `raw [ const | mut ]`.
823 let found_raw
= self.eat_keyword(kw
::Raw
);
825 let mutability
= self.parse_const_or_mut().unwrap();
826 self.sess
.gated_spans
.gate(sym
::raw_ref_op
, lo
.to(self.prev_token
.span
));
827 (ast
::BorrowKind
::Raw
, mutability
)
830 (ast
::BorrowKind
::Ref
, self.parse_mutability())
834 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
835 fn parse_dot_or_call_expr(&mut self, attrs
: Option
<AttrWrapper
>) -> PResult
<'a
, P
<Expr
>> {
836 let attrs
= self.parse_or_use_outer_attributes(attrs
)?
;
837 self.collect_tokens_for_expr(attrs
, |this
, attrs
| {
838 let base
= this
.parse_bottom_expr();
839 let (span
, base
) = this
.interpolated_or_expr_span(base
)?
;
840 this
.parse_dot_or_call_expr_with(base
, span
, attrs
)
844 pub(super) fn parse_dot_or_call_expr_with(
848 mut attrs
: Vec
<ast
::Attribute
>,
849 ) -> PResult
<'a
, P
<Expr
>> {
850 // Stitch the list of outer attributes onto the return value.
851 // A little bit ugly, but the best way given the current code
853 self.parse_dot_or_call_expr_with_(e0
, lo
).map(|expr
| {
854 expr
.map(|mut expr
| {
855 attrs
.extend
::<Vec
<_
>>(expr
.attrs
.into());
856 expr
.attrs
= attrs
.into();
862 fn parse_dot_or_call_expr_with_(&mut self, mut e
: P
<Expr
>, lo
: Span
) -> PResult
<'a
, P
<Expr
>> {
864 if self.eat(&token
::Question
) {
866 e
= self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::Try(e
), AttrVec
::new());
869 if self.eat(&token
::Dot
) {
871 e
= self.parse_dot_suffix_expr(lo
, e
)?
;
874 if self.expr_is_complete(&e
) {
877 e
= match self.token
.kind
{
878 token
::OpenDelim(token
::Paren
) => self.parse_fn_call_expr(lo
, e
),
879 token
::OpenDelim(token
::Bracket
) => self.parse_index_expr(lo
, e
)?
,
885 fn parse_dot_suffix_expr(&mut self, lo
: Span
, base
: P
<Expr
>) -> PResult
<'a
, P
<Expr
>> {
886 match self.token
.uninterpolate().kind
{
887 token
::Ident(..) => self.parse_dot_suffix(base
, lo
),
888 token
::Literal(token
::Lit { kind: token::Integer, symbol, suffix }
) => {
889 Ok(self.parse_tuple_field_access_expr(lo
, base
, symbol
, suffix
, None
))
891 token
::Literal(token
::Lit { kind: token::Float, symbol, suffix }
) => {
892 Ok(self.parse_tuple_field_access_expr_float(lo
, base
, symbol
, suffix
))
895 self.error_unexpected_after_dot();
901 fn error_unexpected_after_dot(&self) {
902 // FIXME Could factor this out into non_fatal_unexpected or something.
903 let actual
= pprust
::token_to_string(&self.token
);
904 self.struct_span_err(self.token
.span
, &format
!("unexpected token: `{}`", actual
)).emit();
907 // We need an identifier or integer, but the next token is a float.
908 // Break the float into components to extract the identifier or integer.
909 // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
910 // parts unless those parts are processed immediately. `TokenCursor` should either
911 // support pushing "future tokens" (would be also helpful to `break_and_eat`), or
912 // we should break everything including floats into more basic proc-macro style
913 // tokens in the lexer (probably preferable).
914 fn parse_tuple_field_access_expr_float(
919 suffix
: Option
<Symbol
>,
922 enum FloatComponent
{
926 use FloatComponent
::*;
928 let float_str
= float
.as_str();
929 let mut components
= Vec
::new();
930 let mut ident_like
= String
::new();
931 for c
in float_str
.chars() {
932 if c
== '_'
|| c
.is_ascii_alphanumeric() {
934 } else if matches
!(c
, '
.'
| '
+'
| '
-'
) {
935 if !ident_like
.is_empty() {
936 components
.push(IdentLike(mem
::take(&mut ident_like
)));
938 components
.push(Punct(c
));
940 panic
!("unexpected character in a float token: {:?}", c
)
943 if !ident_like
.is_empty() {
944 components
.push(IdentLike(ident_like
));
947 // With proc macros the span can refer to anything, the source may be too short,
948 // or too long, or non-ASCII. It only makes sense to break our span into components
949 // if its underlying text is identical to our float literal.
950 let span
= self.token
.span
;
951 let can_take_span_apart
=
952 || self.span_to_snippet(span
).as_deref() == Ok(float_str
).as_deref();
957 self.parse_tuple_field_access_expr(lo
, base
, Symbol
::intern(&i
), suffix
, None
)
960 [IdentLike(i
), Punct('
.'
)] => {
961 let (ident_span
, dot_span
) = if can_take_span_apart() {
962 let (span
, ident_len
) = (span
.data(), BytePos
::from_usize(i
.len()));
963 let ident_span
= span
.with_hi(span
.lo
+ ident_len
);
964 let dot_span
= span
.with_lo(span
.lo
+ ident_len
);
965 (ident_span
, dot_span
)
969 assert
!(suffix
.is_none());
970 let symbol
= Symbol
::intern(&i
);
971 self.token
= Token
::new(token
::Ident(symbol
, false), ident_span
);
972 let next_token
= (Token
::new(token
::Dot
, dot_span
), self.token_spacing
);
973 self.parse_tuple_field_access_expr(lo
, base
, symbol
, None
, Some(next_token
))
976 [IdentLike(i1
), Punct('
.'
), IdentLike(i2
)] => {
977 let (ident1_span
, dot_span
, ident2_span
) = if can_take_span_apart() {
978 let (span
, ident1_len
) = (span
.data(), BytePos
::from_usize(i1
.len()));
979 let ident1_span
= span
.with_hi(span
.lo
+ ident1_len
);
981 .with_lo(span
.lo
+ ident1_len
)
982 .with_hi(span
.lo
+ ident1_len
+ BytePos(1));
983 let ident2_span
= self.token
.span
.with_lo(span
.lo
+ ident1_len
+ BytePos(1));
984 (ident1_span
, dot_span
, ident2_span
)
988 let symbol1
= Symbol
::intern(&i1
);
989 self.token
= Token
::new(token
::Ident(symbol1
, false), ident1_span
);
990 // This needs to be `Spacing::Alone` to prevent regressions.
991 // See issue #76399 and PR #76285 for more details
992 let next_token1
= (Token
::new(token
::Dot
, dot_span
), Spacing
::Alone
);
994 self.parse_tuple_field_access_expr(lo
, base
, symbol1
, None
, Some(next_token1
));
995 let symbol2
= Symbol
::intern(&i2
);
996 let next_token2
= Token
::new(token
::Ident(symbol2
, false), ident2_span
);
997 self.bump_with((next_token2
, self.token_spacing
)); // `.`
998 self.parse_tuple_field_access_expr(lo
, base1
, symbol2
, suffix
, None
)
1000 // 1e+ | 1e- (recovered)
1001 [IdentLike(_
), Punct('
+'
| '
-'
)] |
1003 [IdentLike(_
), Punct('
+'
| '
-'
), IdentLike(_
)] |
1005 [IdentLike(_
), Punct('
.'
), IdentLike(_
), Punct('
+'
| '
-'
), IdentLike(_
)] => {
1006 // See the FIXME about `TokenCursor` above.
1007 self.error_unexpected_after_dot();
1010 _
=> panic
!("unexpected components in a float token: {:?}", components
),
1014 fn parse_tuple_field_access_expr(
1019 suffix
: Option
<Symbol
>,
1020 next_token
: Option
<(Token
, Spacing
)>,
1023 Some(next_token
) => self.bump_with(next_token
),
1024 None
=> self.bump(),
1026 let span
= self.prev_token
.span
;
1027 let field
= ExprKind
::Field(base
, Ident
::new(field
, span
));
1028 self.expect_no_suffix(span
, "a tuple index", suffix
);
1029 self.mk_expr(lo
.to(span
), field
, AttrVec
::new())
1032 /// Parse a function call expression, `expr(...)`.
1033 fn parse_fn_call_expr(&mut self, lo
: Span
, fun
: P
<Expr
>) -> P
<Expr
> {
1034 let seq
= self.parse_paren_expr_seq().map(|args
| {
1035 self.mk_expr(lo
.to(self.prev_token
.span
), self.mk_call(fun
, args
), AttrVec
::new())
1037 self.recover_seq_parse_error(token
::Paren
, lo
, seq
)
1040 /// Parse an indexing expression `expr[...]`.
1041 fn parse_index_expr(&mut self, lo
: Span
, base
: P
<Expr
>) -> PResult
<'a
, P
<Expr
>> {
1043 let index
= self.parse_expr()?
;
1044 self.expect(&token
::CloseDelim(token
::Bracket
))?
;
1045 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), self.mk_index(base
, index
), AttrVec
::new()))
1048 /// Assuming we have just parsed `.`, continue parsing into an expression.
1049 fn parse_dot_suffix(&mut self, self_arg
: P
<Expr
>, lo
: Span
) -> PResult
<'a
, P
<Expr
>> {
1050 if self.token
.uninterpolated_span().rust_2018() && self.eat_keyword(kw
::Await
) {
1051 return Ok(self.mk_await_expr(self_arg
, lo
));
1054 let fn_span_lo
= self.token
.span
;
1055 let mut segment
= self.parse_path_segment(PathStyle
::Expr
)?
;
1056 self.check_trailing_angle_brackets(&segment
, &[&token
::OpenDelim(token
::Paren
)]);
1057 self.check_turbofish_missing_angle_brackets(&mut segment
);
1059 if self.check(&token
::OpenDelim(token
::Paren
)) {
1060 // Method call `expr.f()`
1061 let mut args
= self.parse_paren_expr_seq()?
;
1062 args
.insert(0, self_arg
);
1064 let fn_span
= fn_span_lo
.to(self.prev_token
.span
);
1065 let span
= lo
.to(self.prev_token
.span
);
1066 Ok(self.mk_expr(span
, ExprKind
::MethodCall(segment
, args
, fn_span
), AttrVec
::new()))
1068 // Field access `expr.f`
1069 if let Some(args
) = segment
.args
{
1070 self.struct_span_err(
1072 "field expressions cannot have generic arguments",
1077 let span
= lo
.to(self.prev_token
.span
);
1078 Ok(self.mk_expr(span
, ExprKind
::Field(self_arg
, segment
.ident
), AttrVec
::new()))
1082 /// At the bottom (top?) of the precedence hierarchy,
1083 /// Parses things like parenthesized exprs, macros, `return`, etc.
1085 /// N.B., this does not parse outer attributes, and is private because it only works
1086 /// correctly if called from `parse_dot_or_call_expr()`.
1087 fn parse_bottom_expr(&mut self) -> PResult
<'a
, P
<Expr
>> {
1088 maybe_recover_from_interpolated_ty_qpath
!(self, true);
1089 maybe_whole_expr
!(self);
1091 // Outer attributes are already parsed and will be
1092 // added to the return value after the fact.
1094 // Therefore, prevent sub-parser from parsing
1095 // attributes by giving them an empty "already-parsed" list.
1096 let attrs
= AttrVec
::new();
1098 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
1099 let lo
= self.token
.span
;
1100 if let token
::Literal(_
) = self.token
.kind
{
1101 // This match arm is a special-case of the `_` match arm below and
1102 // could be removed without changing functionality, but it's faster
1103 // to have it here, especially for programs with large constants.
1104 self.parse_lit_expr(attrs
)
1105 } else if self.check(&token
::OpenDelim(token
::Paren
)) {
1106 self.parse_tuple_parens_expr(attrs
)
1107 } else if self.check(&token
::OpenDelim(token
::Brace
)) {
1108 self.parse_block_expr(None
, lo
, BlockCheckMode
::Default
, attrs
)
1109 } else if self.check(&token
::BinOp(token
::Or
)) || self.check(&token
::OrOr
) {
1110 self.parse_closure_expr(attrs
)
1111 } else if self.check(&token
::OpenDelim(token
::Bracket
)) {
1112 self.parse_array_or_repeat_expr(attrs
)
1113 } else if self.check_path() {
1114 self.parse_path_start_expr(attrs
)
1115 } else if self.check_keyword(kw
::Move
) || self.check_keyword(kw
::Static
) {
1116 self.parse_closure_expr(attrs
)
1117 } else if self.eat_keyword(kw
::If
) {
1118 self.parse_if_expr(attrs
)
1119 } else if self.check_keyword(kw
::For
) {
1120 if self.choose_generics_over_qpath(1) {
1121 // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery,
1122 // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns.
1123 // When `for <Foo as Bar>::Proj in $expr $block` is wanted,
1124 // you can disambiguate in favor of a pattern with `(...)`.
1125 self.recover_quantified_closure_expr(attrs
)
1127 assert
!(self.eat_keyword(kw
::For
));
1128 self.parse_for_expr(None
, self.prev_token
.span
, attrs
)
1130 } else if self.eat_keyword(kw
::While
) {
1131 self.parse_while_expr(None
, self.prev_token
.span
, attrs
)
1132 } else if let Some(label
) = self.eat_label() {
1133 self.parse_labeled_expr(label
, attrs
, true)
1134 } else if self.eat_keyword(kw
::Loop
) {
1135 self.parse_loop_expr(None
, self.prev_token
.span
, attrs
)
1136 } else if self.eat_keyword(kw
::Continue
) {
1137 let kind
= ExprKind
::Continue(self.eat_label());
1138 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
))
1139 } else if self.eat_keyword(kw
::Match
) {
1140 let match_sp
= self.prev_token
.span
;
1141 self.parse_match_expr(attrs
).map_err(|mut err
| {
1142 err
.span_label(match_sp
, "while parsing this match expression");
1145 } else if self.eat_keyword(kw
::Unsafe
) {
1146 self.parse_block_expr(None
, lo
, BlockCheckMode
::Unsafe(ast
::UserProvided
), attrs
)
1147 } else if self.check_inline_const(0) {
1148 self.parse_const_block(lo
.to(self.token
.span
))
1149 } else if self.is_do_catch_block() {
1150 self.recover_do_catch(attrs
)
1151 } else if self.is_try_block() {
1152 self.expect_keyword(kw
::Try
)?
;
1153 self.parse_try_block(lo
, attrs
)
1154 } else if self.eat_keyword(kw
::Return
) {
1155 self.parse_return_expr(attrs
)
1156 } else if self.eat_keyword(kw
::Break
) {
1157 self.parse_break_expr(attrs
)
1158 } else if self.eat_keyword(kw
::Yield
) {
1159 self.parse_yield_expr(attrs
)
1160 } else if self.eat_keyword(kw
::Let
) {
1161 self.parse_let_expr(attrs
)
1162 } else if self.eat_keyword(kw
::Underscore
) {
1163 self.sess
.gated_spans
.gate(sym
::destructuring_assignment
, self.prev_token
.span
);
1164 Ok(self.mk_expr(self.prev_token
.span
, ExprKind
::Underscore
, attrs
))
1165 } else if !self.unclosed_delims
.is_empty() && self.check(&token
::Semi
) {
1166 // Don't complain about bare semicolons after unclosed braces
1167 // recovery in order to keep the error count down. Fixing the
1168 // delimiters will possibly also fix the bare semicolon found in
1169 // expression context. For example, silence the following error:
1171 // error: expected expression, found `;`
1175 // | ^ expected expression
1177 Ok(self.mk_expr_err(self.token
.span
))
1178 } else if self.token
.uninterpolated_span().rust_2018() {
1179 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1180 if self.check_keyword(kw
::Async
) {
1181 if self.is_async_block() {
1182 // Check for `async {` and `async move {`.
1183 self.parse_async_block(attrs
)
1185 self.parse_closure_expr(attrs
)
1187 } else if self.eat_keyword(kw
::Await
) {
1188 self.recover_incorrect_await_syntax(lo
, self.prev_token
.span
, attrs
)
1190 self.parse_lit_expr(attrs
)
1193 self.parse_lit_expr(attrs
)
1197 fn parse_lit_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1198 let lo
= self.token
.span
;
1199 match self.parse_opt_lit() {
1201 let expr
= self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::Lit(literal
), attrs
);
1202 self.maybe_recover_from_bad_qpath(expr
, true)
1204 None
=> self.try_macro_suggestion(),
1208 fn parse_tuple_parens_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1209 let lo
= self.token
.span
;
1210 self.expect(&token
::OpenDelim(token
::Paren
))?
;
1211 let (es
, trailing_comma
) = match self.parse_seq_to_end(
1212 &token
::CloseDelim(token
::Paren
),
1213 SeqSep
::trailing_allowed(token
::Comma
),
1214 |p
| p
.parse_expr_catch_underscore(),
1217 Err(err
) => return Ok(self.recover_seq_parse_error(token
::Paren
, lo
, Err(err
))),
1219 let kind
= if es
.len() == 1 && !trailing_comma
{
1220 // `(e)` is parenthesized `e`.
1221 ExprKind
::Paren(es
.into_iter().next().unwrap())
1223 // `(e,)` is a tuple with only one field, `e`.
1226 let expr
= self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
);
1227 self.maybe_recover_from_bad_qpath(expr
, true)
1230 fn parse_array_or_repeat_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1231 let lo
= self.token
.span
;
1234 let close
= &token
::CloseDelim(token
::Bracket
);
1235 let kind
= if self.eat(close
) {
1237 ExprKind
::Array(Vec
::new())
1240 let first_expr
= self.parse_expr()?
;
1241 if self.eat(&token
::Semi
) {
1242 // Repeating array syntax: `[ 0; 512 ]`
1243 let count
= self.parse_anon_const_expr()?
;
1244 self.expect(close
)?
;
1245 ExprKind
::Repeat(first_expr
, count
)
1246 } else if self.eat(&token
::Comma
) {
1247 // Vector with two or more elements.
1248 let sep
= SeqSep
::trailing_allowed(token
::Comma
);
1249 let (remaining_exprs
, _
) = self.parse_seq_to_end(close
, sep
, |p
| p
.parse_expr())?
;
1250 let mut exprs
= vec
![first_expr
];
1251 exprs
.extend(remaining_exprs
);
1252 ExprKind
::Array(exprs
)
1254 // Vector with one element
1255 self.expect(close
)?
;
1256 ExprKind
::Array(vec
![first_expr
])
1259 let expr
= self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
);
1260 self.maybe_recover_from_bad_qpath(expr
, true)
1263 fn parse_path_start_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1264 let (qself
, path
) = if self.eat_lt() {
1265 let (qself
, path
) = self.parse_qpath(PathStyle
::Expr
)?
;
1268 (None
, self.parse_path(PathStyle
::Expr
)?
)
1272 // `!`, as an operator, is prefix, so we know this isn't that.
1273 let (hi
, kind
) = if self.eat(&token
::Not
) {
1274 // MACRO INVOCATION expression
1275 if qself
.is_some() {
1276 self.struct_span_err(path
.span
, "macros cannot use qualified paths").emit();
1280 args
: self.parse_mac_args()?
,
1281 prior_type_ascription
: self.last_type_ascription
,
1283 (self.prev_token
.span
, ExprKind
::MacCall(mac
))
1284 } else if self.check(&token
::OpenDelim(token
::Brace
)) {
1285 if let Some(expr
) = self.maybe_parse_struct_expr(qself
.as_ref(), &path
, &attrs
) {
1286 if qself
.is_some() {
1287 self.sess
.gated_spans
.gate(sym
::more_qualified_paths
, path
.span
);
1291 (path
.span
, ExprKind
::Path(qself
, path
))
1294 (path
.span
, ExprKind
::Path(qself
, path
))
1297 let expr
= self.mk_expr(lo
.to(hi
), kind
, attrs
);
1298 self.maybe_recover_from_bad_qpath(expr
, true)
1301 /// Parse `'label: $expr`. The label is already parsed.
1302 fn parse_labeled_expr(
1306 consume_colon
: bool
,
1307 ) -> PResult
<'a
, P
<Expr
>> {
1308 let lo
= label
.ident
.span
;
1309 let label
= Some(label
);
1310 let ate_colon
= self.eat(&token
::Colon
);
1311 let expr
= if self.eat_keyword(kw
::While
) {
1312 self.parse_while_expr(label
, lo
, attrs
)
1313 } else if self.eat_keyword(kw
::For
) {
1314 self.parse_for_expr(label
, lo
, attrs
)
1315 } else if self.eat_keyword(kw
::Loop
) {
1316 self.parse_loop_expr(label
, lo
, attrs
)
1317 } else if self.check(&token
::OpenDelim(token
::Brace
)) || self.token
.is_whole_block() {
1318 self.parse_block_expr(label
, lo
, BlockCheckMode
::Default
, attrs
)
1320 let msg
= "expected `while`, `for`, `loop` or `{` after a label";
1321 self.struct_span_err(self.token
.span
, msg
).span_label(self.token
.span
, msg
).emit();
1322 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1326 if !ate_colon
&& consume_colon
{
1327 self.error_labeled_expr_must_be_followed_by_colon(lo
, expr
.span
);
1333 fn error_labeled_expr_must_be_followed_by_colon(&self, lo
: Span
, span
: Span
) {
1334 self.struct_span_err(span
, "labeled expression must be followed by `:`")
1335 .span_label(lo
, "the label")
1336 .span_suggestion_short(
1338 "add `:` after the label",
1340 Applicability
::MachineApplicable
,
1342 .note("labels are used before loops and blocks, allowing e.g., `break 'label` to them")
1346 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1347 fn recover_do_catch(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1348 let lo
= self.token
.span
;
1350 self.bump(); // `do`
1351 self.bump(); // `catch`
1353 let span_dc
= lo
.to(self.prev_token
.span
);
1354 self.struct_span_err(span_dc
, "found removed `do catch` syntax")
1357 "replace with the new syntax",
1359 Applicability
::MachineApplicable
,
1361 .note("following RFC #2388, the new non-placeholder syntax is `try`")
1364 self.parse_try_block(lo
, attrs
)
1367 /// Parse an expression if the token can begin one.
1368 fn parse_expr_opt(&mut self) -> PResult
<'a
, Option
<P
<Expr
>>> {
1369 Ok(if self.token
.can_begin_expr() { Some(self.parse_expr()?) }
else { None }
)
1372 /// Parse `"return" expr?`.
1373 fn parse_return_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1374 let lo
= self.prev_token
.span
;
1375 let kind
= ExprKind
::Ret(self.parse_expr_opt()?
);
1376 let expr
= self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
);
1377 self.maybe_recover_from_bad_qpath(expr
, true)
1380 /// Parse `"break" (('label (:? expr)?) | expr?)` with `"break"` token already eaten.
1381 /// If the label is followed immediately by a `:` token, the label and `:` are
1382 /// parsed as part of the expression (i.e. a labeled loop). The language team has
1383 /// decided in #87026 to require parentheses as a visual aid to avoid confusion if
1384 /// the break expression of an unlabeled break is a labeled loop (as in
1385 /// `break 'lbl: loop {}`); a labeled break with an unlabeled loop as its value
1386 /// expression only gets a warning for compatibility reasons; and a labeled break
1387 /// with a labeled loop does not even get a warning because there is no ambiguity.
1388 fn parse_break_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1389 let lo
= self.prev_token
.span
;
1390 let mut label
= self.eat_label();
1391 let kind
= if label
.is_some() && self.token
== token
::Colon
{
1392 // The value expression can be a labeled loop, see issue #86948, e.g.:
1393 // `loop { break 'label: loop { break 'label 42; }; }`
1394 let lexpr
= self.parse_labeled_expr(label
.take().unwrap(), AttrVec
::new(), true)?
;
1395 self.struct_span_err(
1397 "parentheses are required around this expression to avoid confusion with a labeled break expression",
1399 .multipart_suggestion(
1400 "wrap the expression in parentheses",
1402 (lexpr
.span
.shrink_to_lo(), "(".to_string()),
1403 (lexpr
.span
.shrink_to_hi(), ")".to_string()),
1405 Applicability
::MachineApplicable
,
1409 } else if self.token
!= token
::OpenDelim(token
::Brace
)
1410 || !self.restrictions
.contains(Restrictions
::NO_STRUCT_LITERAL
)
1412 let expr
= self.parse_expr_opt()?
;
1413 if let Some(ref expr
) = expr
{
1417 ExprKind
::While(_
, _
, None
)
1418 | ExprKind
::ForLoop(_
, _
, _
, None
)
1419 | ExprKind
::Loop(_
, None
)
1420 | ExprKind
::Block(_
, None
)
1423 self.sess
.buffer_lint_with_diagnostic(
1424 BREAK_WITH_LABEL_AND_LOOP
,
1427 "this labeled break expression is easy to confuse with an unlabeled break with a labeled value expression",
1428 BuiltinLintDiagnostics
::BreakWithLabelAndLoop(expr
.span
),
1436 let expr
= self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::Break(label
, kind
), attrs
);
1437 self.maybe_recover_from_bad_qpath(expr
, true)
1440 /// Parse `"yield" expr?`.
1441 fn parse_yield_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1442 let lo
= self.prev_token
.span
;
1443 let kind
= ExprKind
::Yield(self.parse_expr_opt()?
);
1444 let span
= lo
.to(self.prev_token
.span
);
1445 self.sess
.gated_spans
.gate(sym
::generators
, span
);
1446 let expr
= self.mk_expr(span
, kind
, attrs
);
1447 self.maybe_recover_from_bad_qpath(expr
, true)
1450 /// Returns a string literal if the next token is a string literal.
1451 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1452 /// and returns `None` if the next token is not literal at all.
1453 pub fn parse_str_lit(&mut self) -> Result
<ast
::StrLit
, Option
<Lit
>> {
1454 match self.parse_opt_lit() {
1455 Some(lit
) => match lit
.kind
{
1456 ast
::LitKind
::Str(symbol_unescaped
, style
) => Ok(ast
::StrLit
{
1458 symbol
: lit
.token
.symbol
,
1459 suffix
: lit
.token
.suffix
,
1463 _
=> Err(Some(lit
)),
1469 pub(super) fn parse_lit(&mut self) -> PResult
<'a
, Lit
> {
1470 self.parse_opt_lit().ok_or_else(|| {
1471 let msg
= format
!("unexpected token: {}", super::token_descr(&self.token
));
1472 self.struct_span_err(self.token
.span
, &msg
)
1476 /// Matches `lit = true | false | token_lit`.
1477 /// Returns `None` if the next token is not a literal.
1478 pub(super) fn parse_opt_lit(&mut self) -> Option
<Lit
> {
1479 let mut recovered
= None
;
1480 if self.token
== token
::Dot
{
1481 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1482 // dot would follow an optional literal, so we do this unconditionally.
1483 recovered
= self.look_ahead(1, |next_token
| {
1484 if let token
::Literal(token
::Lit { kind: token::Integer, symbol, suffix }
) =
1487 if self.token
.span
.hi() == next_token
.span
.lo() {
1488 let s
= String
::from("0.") + &symbol
.as_str();
1489 let kind
= TokenKind
::lit(token
::Float
, Symbol
::intern(&s
), suffix
);
1490 return Some(Token
::new(kind
, self.token
.span
.to(next_token
.span
)));
1495 if let Some(token
) = &recovered
{
1497 self.error_float_lits_must_have_int_part(&token
);
1501 let token
= recovered
.as_ref().unwrap_or(&self.token
);
1502 match Lit
::from_token(token
) {
1507 Err(LitError
::NotLiteral
) => None
,
1509 let span
= token
.span
;
1510 let lit
= match token
.kind
{
1511 token
::Literal(lit
) => lit
,
1512 _
=> unreachable
!(),
1515 self.report_lit_error(err
, lit
, span
);
1516 // Pack possible quotes and prefixes from the original literal into
1517 // the error literal's symbol so they can be pretty-printed faithfully.
1518 let suffixless_lit
= token
::Lit
::new(lit
.kind
, lit
.symbol
, None
);
1519 let symbol
= Symbol
::intern(&suffixless_lit
.to_string());
1520 let lit
= token
::Lit
::new(token
::Err
, symbol
, lit
.suffix
);
1521 Some(Lit
::from_lit_token(lit
, span
).unwrap_or_else(|_
| unreachable
!()))
1526 fn error_float_lits_must_have_int_part(&self, token
: &Token
) {
1527 self.struct_span_err(token
.span
, "float literals must have an integer part")
1530 "must have an integer part",
1531 pprust
::token_to_string(token
).into(),
1532 Applicability
::MachineApplicable
,
1537 fn report_lit_error(&self, err
: LitError
, lit
: token
::Lit
, span
: Span
) {
1538 // Checks if `s` looks like i32 or u1234 etc.
1539 fn looks_like_width_suffix(first_chars
: &[char], s
: &str) -> bool
{
1540 s
.len() > 1 && s
.starts_with(first_chars
) && s
[1..].chars().all(|c
| c
.is_ascii_digit())
1543 let token
::Lit { kind, suffix, .. }
= lit
;
1545 // `NotLiteral` is not an error by itself, so we don't report
1546 // it and give the parser opportunity to try something else.
1547 LitError
::NotLiteral
=> {}
1548 // `LexerError` *is* an error, but it was already reported
1549 // by lexer, so here we don't report it the second time.
1550 LitError
::LexerError
=> {}
1551 LitError
::InvalidSuffix
=> {
1552 self.expect_no_suffix(
1554 &format
!("{} {} literal", kind
.article(), kind
.descr()),
1558 LitError
::InvalidIntSuffix
=> {
1559 let suf
= suffix
.expect("suffix error with no suffix").as_str();
1560 if looks_like_width_suffix(&['i'
, 'u'
], &suf
) {
1561 // If it looks like a width, try to be helpful.
1562 let msg
= format
!("invalid width `{}` for integer literal", &suf
[1..]);
1563 self.struct_span_err(span
, &msg
)
1564 .help("valid widths are 8, 16, 32, 64 and 128")
1567 let msg
= format
!("invalid suffix `{}` for number literal", suf
);
1568 self.struct_span_err(span
, &msg
)
1569 .span_label(span
, format
!("invalid suffix `{}`", suf
))
1570 .help("the suffix must be one of the numeric types (`u32`, `isize`, `f32`, etc.)")
1574 LitError
::InvalidFloatSuffix
=> {
1575 let suf
= suffix
.expect("suffix error with no suffix").as_str();
1576 if looks_like_width_suffix(&['f'
], &suf
) {
1577 // If it looks like a width, try to be helpful.
1578 let msg
= format
!("invalid width `{}` for float literal", &suf
[1..]);
1579 self.struct_span_err(span
, &msg
).help("valid widths are 32 and 64").emit();
1581 let msg
= format
!("invalid suffix `{}` for float literal", suf
);
1582 self.struct_span_err(span
, &msg
)
1583 .span_label(span
, format
!("invalid suffix `{}`", suf
))
1584 .help("valid suffixes are `f32` and `f64`")
1588 LitError
::NonDecimalFloat(base
) => {
1589 let descr
= match base
{
1590 16 => "hexadecimal",
1593 _
=> unreachable
!(),
1595 self.struct_span_err(span
, &format
!("{} float literal is not supported", descr
))
1596 .span_label(span
, "not supported")
1599 LitError
::IntTooLarge
=> {
1600 self.struct_span_err(span
, "integer literal is too large").emit();
1605 pub(super) fn expect_no_suffix(&self, sp
: Span
, kind
: &str, suffix
: Option
<Symbol
>) {
1606 if let Some(suf
) = suffix
{
1607 let mut err
= if kind
== "a tuple index"
1608 && [sym
::i32, sym
::u32, sym
::isize, sym
::usize].contains(&suf
)
1610 // #59553: warn instead of reject out of hand to allow the fix to percolate
1611 // through the ecosystem when people fix their macros
1615 .struct_span_warn(sp
, &format
!("suffixes on {} are invalid", kind
));
1617 "`{}` is *temporarily* accepted on tuple index fields as it was \
1618 incorrectly accepted on stable for a few releases",
1622 "on proc macros, you'll want to use `syn::Index::from` or \
1623 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1624 to tuple field access",
1627 "see issue #60210 <https://github.com/rust-lang/rust/issues/60210> \
1628 for more information",
1632 self.struct_span_err(sp
, &format
!("suffixes on {} are invalid", kind
))
1634 err
.span_label(sp
, format
!("invalid suffix `{}`", suf
));
1639 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1640 /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
1641 pub fn parse_literal_maybe_minus(&mut self) -> PResult
<'a
, P
<Expr
>> {
1642 maybe_whole_expr
!(self);
1644 let lo
= self.token
.span
;
1645 let minus_present
= self.eat(&token
::BinOp(token
::Minus
));
1646 let lit
= self.parse_lit()?
;
1647 let expr
= self.mk_expr(lit
.span
, ExprKind
::Lit(lit
), AttrVec
::new());
1651 lo
.to(self.prev_token
.span
),
1652 self.mk_unary(UnOp
::Neg
, expr
),
1660 /// Parses a block or unsafe block.
1661 pub(super) fn parse_block_expr(
1663 opt_label
: Option
<Label
>,
1665 blk_mode
: BlockCheckMode
,
1667 ) -> PResult
<'a
, P
<Expr
>> {
1668 if let Some(label
) = opt_label
{
1669 self.sess
.gated_spans
.gate(sym
::label_break_value
, label
.ident
.span
);
1672 if self.token
.is_whole_block() {
1673 self.struct_span_err(self.token
.span
, "cannot use a `block` macro fragment here")
1674 .span_label(lo
.to(self.token
.span
), "the `block` fragment is within this context")
1678 let (inner_attrs
, blk
) = self.parse_block_common(lo
, blk_mode
)?
;
1679 attrs
.extend(inner_attrs
);
1680 Ok(self.mk_expr(blk
.span
, ExprKind
::Block(blk
, opt_label
), attrs
))
1683 /// Recover on an explicitly quantified closure expression, e.g., `for<'a> |x: &'a u8| *x + 1`.
1684 fn recover_quantified_closure_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1685 let lo
= self.token
.span
;
1686 let _
= self.parse_late_bound_lifetime_defs()?
;
1687 let span_for
= lo
.to(self.prev_token
.span
);
1688 let closure
= self.parse_closure_expr(attrs
)?
;
1690 self.struct_span_err(span_for
, "cannot introduce explicit parameters for a closure")
1691 .span_label(closure
.span
, "the parameters are attached to this closure")
1694 "remove the parameters",
1696 Applicability
::MachineApplicable
,
1700 Ok(self.mk_expr_err(lo
.to(closure
.span
)))
1703 /// Parses a closure expression (e.g., `move |args| expr`).
1704 fn parse_closure_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1705 let lo
= self.token
.span
;
1708 if self.eat_keyword(kw
::Static
) { Movability::Static }
else { Movability::Movable }
;
1710 let asyncness
= if self.token
.uninterpolated_span().rust_2018() {
1711 self.parse_asyncness()
1716 let capture_clause
= self.parse_capture_clause()?
;
1717 let decl
= self.parse_fn_block_decl()?
;
1718 let decl_hi
= self.prev_token
.span
;
1719 let body
= match decl
.output
{
1720 FnRetTy
::Default(_
) => {
1721 let restrictions
= self.restrictions
- Restrictions
::STMT_EXPR
;
1722 self.parse_expr_res(restrictions
, None
)?
1725 // If an explicit return type is given, require a block to appear (RFC 968).
1726 let body_lo
= self.token
.span
;
1727 self.parse_block_expr(None
, body_lo
, BlockCheckMode
::Default
, AttrVec
::new())?
1731 if let Async
::Yes { span, .. }
= asyncness
{
1732 // Feature-gate `async ||` closures.
1733 self.sess
.gated_spans
.gate(sym
::async_closure
, span
);
1738 ExprKind
::Closure(capture_clause
, asyncness
, movability
, decl
, body
, lo
.to(decl_hi
)),
1743 /// Parses an optional `move` prefix to a closure-like construct.
1744 fn parse_capture_clause(&mut self) -> PResult
<'a
, CaptureBy
> {
1745 if self.eat_keyword(kw
::Move
) {
1746 // Check for `move async` and recover
1747 if self.check_keyword(kw
::Async
) {
1748 let move_async_span
= self.token
.span
.with_lo(self.prev_token
.span
.data().lo
);
1749 Err(self.incorrect_move_async_order_found(move_async_span
))
1751 Ok(CaptureBy
::Value
)
1758 /// Parses the `|arg, arg|` header of a closure.
1759 fn parse_fn_block_decl(&mut self) -> PResult
<'a
, P
<FnDecl
>> {
1760 let inputs
= if self.eat(&token
::OrOr
) {
1763 self.expect(&token
::BinOp(token
::Or
))?
;
1765 .parse_seq_to_before_tokens(
1766 &[&token
::BinOp(token
::Or
), &token
::OrOr
],
1767 SeqSep
::trailing_allowed(token
::Comma
),
1768 TokenExpectType
::NoExpect
,
1769 |p
| p
.parse_fn_block_param(),
1776 self.parse_ret_ty(AllowPlus
::Yes
, RecoverQPath
::Yes
, RecoverReturnSign
::Yes
)?
;
1778 Ok(P(FnDecl { inputs, output }
))
1781 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1782 fn parse_fn_block_param(&mut self) -> PResult
<'a
, Param
> {
1783 let lo
= self.token
.span
;
1784 let attrs
= self.parse_outer_attributes()?
;
1785 self.collect_tokens_trailing_token(attrs
, ForceCollect
::No
, |this
, attrs
| {
1786 let pat
= this
.parse_pat_no_top_alt(PARAM_EXPECTED
)?
;
1787 let ty
= if this
.eat(&token
::Colon
) {
1790 this
.mk_ty(this
.prev_token
.span
, TyKind
::Infer
)
1795 attrs
: attrs
.into(),
1798 span
: lo
.to(this
.token
.span
),
1800 is_placeholder
: false,
1802 TrailingToken
::MaybeComma
,
1807 /// Parses an `if` expression (`if` token already eaten).
1808 fn parse_if_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1809 let lo
= self.prev_token
.span
;
1810 let cond
= self.parse_cond_expr()?
;
1812 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1813 // verify that the last statement is either an implicit return (no `;`) or an explicit
1814 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1815 // the dead code lint.
1816 let thn
= if self.eat_keyword(kw
::Else
) || !cond
.returns() {
1817 self.error_missing_if_cond(lo
, cond
.span
)
1819 let attrs
= self.parse_outer_attributes()?
.take_for_recovery(); // For recovery.
1820 let not_block
= self.token
!= token
::OpenDelim(token
::Brace
);
1821 let block
= self.parse_block().map_err(|mut err
| {
1823 err
.span_label(lo
, "this `if` expression has a condition, but no block");
1824 if let ExprKind
::Binary(_
, _
, ref right
) = cond
.kind
{
1825 if let ExprKind
::Block(_
, _
) = right
.kind
{
1826 err
.help("maybe you forgot the right operand of the condition?");
1832 self.error_on_if_block_attrs(lo
, false, block
.span
, &attrs
);
1835 let els
= if self.eat_keyword(kw
::Else
) { Some(self.parse_else_expr()?) }
else { None }
;
1836 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::If(cond
, thn
, els
), attrs
))
1839 fn error_missing_if_cond(&self, lo
: Span
, span
: Span
) -> P
<ast
::Block
> {
1840 let sp
= self.sess
.source_map().next_point(lo
);
1841 self.struct_span_err(sp
, "missing condition for `if` expression")
1842 .span_label(sp
, "expected if condition here")
1844 self.mk_block_err(span
)
1847 /// Parses the condition of a `if` or `while` expression.
1848 fn parse_cond_expr(&mut self) -> PResult
<'a
, P
<Expr
>> {
1849 let cond
= self.parse_expr_res(Restrictions
::NO_STRUCT_LITERAL
, None
)?
;
1851 if let ExprKind
::Let(..) = cond
.kind
{
1852 // Remove the last feature gating of a `let` expression since it's stable.
1853 self.sess
.gated_spans
.ungate_last(sym
::let_chains
, cond
.span
);
1859 /// Parses a `let $pat = $expr` pseudo-expression.
1860 /// The `let` token has already been eaten.
1861 fn parse_let_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1862 let lo
= self.prev_token
.span
;
1863 let pat
= self.parse_pat_allow_top_alt(None
, RecoverComma
::Yes
, RecoverColon
::Yes
)?
;
1864 self.expect(&token
::Eq
)?
;
1865 let expr
= self.with_res(self.restrictions
| Restrictions
::NO_STRUCT_LITERAL
, |this
| {
1866 this
.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None
.into())
1868 let span
= lo
.to(expr
.span
);
1869 self.sess
.gated_spans
.gate(sym
::let_chains
, span
);
1870 Ok(self.mk_expr(span
, ExprKind
::Let(pat
, expr
, span
), attrs
))
1873 /// Parses an `else { ... }` expression (`else` token already eaten).
1874 fn parse_else_expr(&mut self) -> PResult
<'a
, P
<Expr
>> {
1875 let ctx_span
= self.prev_token
.span
; // `else`
1876 let attrs
= self.parse_outer_attributes()?
.take_for_recovery(); // For recovery.
1877 let expr
= if self.eat_keyword(kw
::If
) {
1878 self.parse_if_expr(AttrVec
::new())?
1880 let blk
= self.parse_block()?
;
1881 self.mk_expr(blk
.span
, ExprKind
::Block(blk
, None
), AttrVec
::new())
1883 self.error_on_if_block_attrs(ctx_span
, true, expr
.span
, &attrs
);
1887 fn error_on_if_block_attrs(
1892 attrs
: &[ast
::Attribute
],
1894 let (span
, last
) = match attrs
{
1896 [x0 @ xn
] | [x0
, .., xn
] => (x0
.span
.to(xn
.span
), xn
.span
),
1898 let ctx
= if is_ctx_else { "else" }
else { "if" }
;
1899 self.struct_span_err(last
, "outer attributes are not allowed on `if` and `else` branches")
1900 .span_label(branch_span
, "the attributes are attached to this branch")
1901 .span_label(ctx_span
, format
!("the branch belongs to this `{}`", ctx
))
1904 "remove the attributes",
1906 Applicability
::MachineApplicable
,
1911 /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
1914 opt_label
: Option
<Label
>,
1917 ) -> PResult
<'a
, P
<Expr
>> {
1918 // Record whether we are about to parse `for (`.
1919 // This is used below for recovery in case of `for ( $stuff ) $block`
1920 // in which case we will suggest `for $stuff $block`.
1921 let begin_paren
= match self.token
.kind
{
1922 token
::OpenDelim(token
::Paren
) => Some(self.token
.span
),
1926 let pat
= self.parse_pat_allow_top_alt(None
, RecoverComma
::Yes
, RecoverColon
::Yes
)?
;
1927 if !self.eat_keyword(kw
::In
) {
1928 self.error_missing_in_for_loop();
1930 self.check_for_for_in_in_typo(self.prev_token
.span
);
1931 let expr
= self.parse_expr_res(Restrictions
::NO_STRUCT_LITERAL
, None
)?
;
1933 let pat
= self.recover_parens_around_for_head(pat
, &expr
, begin_paren
);
1935 let (iattrs
, loop_block
) = self.parse_inner_attrs_and_block()?
;
1936 attrs
.extend(iattrs
);
1938 let kind
= ExprKind
::ForLoop(pat
, expr
, loop_block
, opt_label
);
1939 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
))
1942 fn error_missing_in_for_loop(&mut self) {
1943 let (span
, msg
, sugg
) = if self.token
.is_ident_named(sym
::of
) {
1944 // Possibly using JS syntax (#75311).
1945 let span
= self.token
.span
;
1947 (span
, "try using `in` here instead", "in")
1949 (self.prev_token
.span
.between(self.token
.span
), "try adding `in` here", " in ")
1951 self.struct_span_err(span
, "missing `in` in `for` loop")
1952 .span_suggestion_short(
1956 // Has been misleading, at least in the past (closed Issue #48492).
1957 Applicability
::MaybeIncorrect
,
1962 /// Parses a `while` or `while let` expression (`while` token already eaten).
1963 fn parse_while_expr(
1965 opt_label
: Option
<Label
>,
1968 ) -> PResult
<'a
, P
<Expr
>> {
1969 let cond
= self.parse_cond_expr()?
;
1970 let (iattrs
, body
) = self.parse_inner_attrs_and_block()?
;
1971 attrs
.extend(iattrs
);
1972 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::While(cond
, body
, opt_label
), attrs
))
1975 /// Parses `loop { ... }` (`loop` token already eaten).
1978 opt_label
: Option
<Label
>,
1981 ) -> PResult
<'a
, P
<Expr
>> {
1982 let (iattrs
, body
) = self.parse_inner_attrs_and_block()?
;
1983 attrs
.extend(iattrs
);
1984 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::Loop(body
, opt_label
), attrs
))
1987 fn eat_label(&mut self) -> Option
<Label
> {
1988 self.token
.lifetime().map(|ident
| {
1994 /// Parses a `match ... { ... }` expression (`match` token already eaten).
1995 fn parse_match_expr(&mut self, mut attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1996 let match_span
= self.prev_token
.span
;
1997 let lo
= self.prev_token
.span
;
1998 let scrutinee
= self.parse_expr_res(Restrictions
::NO_STRUCT_LITERAL
, None
)?
;
1999 if let Err(mut e
) = self.expect(&token
::OpenDelim(token
::Brace
)) {
2000 if self.token
== token
::Semi
{
2001 e
.span_suggestion_short(
2003 "try removing this `match`",
2005 Applicability
::MaybeIncorrect
, // speculative
2010 attrs
.extend(self.parse_inner_attributes()?
);
2012 let mut arms
: Vec
<Arm
> = Vec
::new();
2013 while self.token
!= token
::CloseDelim(token
::Brace
) {
2014 match self.parse_arm() {
2015 Ok(arm
) => arms
.push(arm
),
2017 // Recover by skipping to the end of the block.
2019 self.recover_stmt();
2020 let span
= lo
.to(self.token
.span
);
2021 if self.token
== token
::CloseDelim(token
::Brace
) {
2024 return Ok(self.mk_expr(span
, ExprKind
::Match(scrutinee
, arms
), attrs
));
2028 let hi
= self.token
.span
;
2030 Ok(self.mk_expr(lo
.to(hi
), ExprKind
::Match(scrutinee
, arms
), attrs
))
2033 /// Attempt to recover from match arm body with statements and no surrounding braces.
2034 fn parse_arm_body_missing_braces(
2036 first_expr
: &P
<Expr
>,
2038 ) -> Option
<P
<Expr
>> {
2039 if self.token
.kind
!= token
::Semi
{
2042 let start_snapshot
= self.clone();
2043 let semi_sp
= self.token
.span
;
2046 vec
![self.mk_stmt(first_expr
.span
, ast
::StmtKind
::Expr(first_expr
.clone()))];
2047 let err
= |this
: &mut Parser
<'_
>, stmts
: Vec
<ast
::Stmt
>| {
2048 let span
= stmts
[0].span
.to(stmts
[stmts
.len() - 1].span
);
2049 let mut err
= this
.struct_span_err(span
, "`match` arm body without braces");
2050 let (these
, s
, are
) =
2051 if stmts
.len() > 1 { ("these", "s", "are") }
else { ("this", "", "is") }
;
2055 "{these} statement{s} {are} not surrounded by a body",
2061 err
.span_label(arrow_span
, "while parsing the `match` arm starting here");
2062 if stmts
.len() > 1 {
2063 err
.multipart_suggestion(
2064 &format
!("surround the statement{} with a body", s
),
2066 (span
.shrink_to_lo(), "{ ".to_string()),
2067 (span
.shrink_to_hi(), " }".to_string()),
2069 Applicability
::MachineApplicable
,
2072 err
.span_suggestion(
2074 "use a comma to end a `match` arm expression",
2076 Applicability
::MachineApplicable
,
2080 this
.mk_expr_err(span
)
2082 // We might have either a `,` -> `;` typo, or a block without braces. We need
2083 // a more subtle parsing strategy.
2085 if self.token
.kind
== token
::CloseDelim(token
::Brace
) {
2086 // We have reached the closing brace of the `match` expression.
2087 return Some(err(self, stmts
));
2089 if self.token
.kind
== token
::Comma
{
2090 *self = start_snapshot
;
2093 let pre_pat_snapshot
= self.clone();
2094 match self.parse_pat_no_top_alt(None
) {
2096 if self.token
.kind
== token
::FatArrow
{
2098 *self = pre_pat_snapshot
;
2099 return Some(err(self, stmts
));
2107 *self = pre_pat_snapshot
;
2108 match self.parse_stmt_without_recovery(true, ForceCollect
::No
) {
2109 // Consume statements for as long as possible.
2114 *self = start_snapshot
;
2117 // We couldn't parse either yet another statement missing it's
2118 // enclosing block nor the next arm's pattern or closing brace.
2119 Err(mut stmt_err
) => {
2121 *self = start_snapshot
;
2129 pub(super) fn parse_arm(&mut self) -> PResult
<'a
, Arm
> {
2130 let attrs
= self.parse_outer_attributes()?
;
2131 self.collect_tokens_trailing_token(attrs
, ForceCollect
::No
, |this
, attrs
| {
2132 let lo
= this
.token
.span
;
2133 let pat
= this
.parse_pat_allow_top_alt(None
, RecoverComma
::Yes
, RecoverColon
::Yes
)?
;
2134 let guard
= if this
.eat_keyword(kw
::If
) {
2135 let if_span
= this
.prev_token
.span
;
2136 let cond
= this
.parse_expr()?
;
2137 if let ExprKind
::Let(..) = cond
.kind
{
2138 // Remove the last feature gating of a `let` expression since it's stable.
2139 this
.sess
.gated_spans
.ungate_last(sym
::let_chains
, cond
.span
);
2140 let span
= if_span
.to(cond
.span
);
2141 this
.sess
.gated_spans
.gate(sym
::if_let_guard
, span
);
2147 let arrow_span
= this
.token
.span
;
2148 this
.expect(&token
::FatArrow
)?
;
2149 let arm_start_span
= this
.token
.span
;
2151 let expr
= this
.parse_expr_res(Restrictions
::STMT_EXPR
, None
).map_err(|mut err
| {
2152 err
.span_label(arrow_span
, "while parsing the `match` arm starting here");
2156 let require_comma
= classify
::expr_requires_semi_to_be_stmt(&expr
)
2157 && this
.token
!= token
::CloseDelim(token
::Brace
);
2159 let hi
= this
.prev_token
.span
;
2162 let sm
= this
.sess
.source_map();
2163 if let Some(body
) = this
.parse_arm_body_missing_braces(&expr
, arrow_span
) {
2164 let span
= body
.span
;
2167 attrs
: attrs
.into(),
2173 is_placeholder
: false,
2175 TrailingToken
::None
,
2178 this
.expect_one_of(&[token
::Comma
], &[token
::CloseDelim(token
::Brace
)]).map_err(
2180 match (sm
.span_to_lines(expr
.span
), sm
.span_to_lines(arm_start_span
)) {
2181 (Ok(ref expr_lines
), Ok(ref arm_start_lines
))
2182 if arm_start_lines
.lines
[0].end_col
2183 == expr_lines
.lines
[0].end_col
2184 && expr_lines
.lines
.len() == 2
2185 && this
.token
== token
::FatArrow
=>
2187 // We check whether there's any trailing code in the parse span,
2188 // if there isn't, we very likely have the following:
2191 // | -- - missing comma
2195 // | - ^^ self.token.span
2197 // | parsed until here as `"y" & X`
2198 err
.span_suggestion_short(
2199 arm_start_span
.shrink_to_hi(),
2200 "missing a comma here to end this `match` arm",
2202 Applicability
::MachineApplicable
,
2208 "while parsing the `match` arm starting here",
2216 this
.eat(&token
::Comma
);
2221 attrs
: attrs
.into(),
2227 is_placeholder
: false,
2229 TrailingToken
::None
,
2234 /// Parses a `try {...}` expression (`try` token already eaten).
2235 fn parse_try_block(&mut self, span_lo
: Span
, mut attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
2236 let (iattrs
, body
) = self.parse_inner_attrs_and_block()?
;
2237 attrs
.extend(iattrs
);
2238 if self.eat_keyword(kw
::Catch
) {
2239 let mut error
= self.struct_span_err(
2240 self.prev_token
.span
,
2241 "keyword `catch` cannot follow a `try` block",
2243 error
.help("try using `match` on the result of the `try` block instead");
2247 let span
= span_lo
.to(body
.span
);
2248 self.sess
.gated_spans
.gate(sym
::try_blocks
, span
);
2249 Ok(self.mk_expr(span
, ExprKind
::TryBlock(body
), attrs
))
2253 fn is_do_catch_block(&self) -> bool
{
2254 self.token
.is_keyword(kw
::Do
)
2255 && self.is_keyword_ahead(1, &[kw
::Catch
])
2256 && self.look_ahead(2, |t
| *t
== token
::OpenDelim(token
::Brace
))
2257 && !self.restrictions
.contains(Restrictions
::NO_STRUCT_LITERAL
)
2260 fn is_try_block(&self) -> bool
{
2261 self.token
.is_keyword(kw
::Try
)
2262 && self.look_ahead(1, |t
| *t
== token
::OpenDelim(token
::Brace
))
2263 && self.token
.uninterpolated_span().rust_2018()
2266 /// Parses an `async move? {...}` expression.
2267 fn parse_async_block(&mut self, mut attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
2268 let lo
= self.token
.span
;
2269 self.expect_keyword(kw
::Async
)?
;
2270 let capture_clause
= self.parse_capture_clause()?
;
2271 let (iattrs
, body
) = self.parse_inner_attrs_and_block()?
;
2272 attrs
.extend(iattrs
);
2273 let kind
= ExprKind
::Async(capture_clause
, DUMMY_NODE_ID
, body
);
2274 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
))
2277 fn is_async_block(&self) -> bool
{
2278 self.token
.is_keyword(kw
::Async
)
2281 self.is_keyword_ahead(1, &[kw
::Move
])
2282 && self.look_ahead(2, |t
| *t
== token
::OpenDelim(token
::Brace
))
2285 self.look_ahead(1, |t
| *t
== token
::OpenDelim(token
::Brace
))
2289 fn is_certainly_not_a_block(&self) -> bool
{
2290 self.look_ahead(1, |t
| t
.is_ident())
2292 // `{ ident, ` cannot start a block.
2293 self.look_ahead(2, |t
| t
== &token
::Comma
)
2294 || self.look_ahead(2, |t
| t
== &token
::Colon
)
2296 // `{ ident: token, ` cannot start a block.
2297 self.look_ahead(4, |t
| t
== &token
::Comma
) ||
2298 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
2299 self.look_ahead(3, |t
| !t
.can_begin_type())
2304 fn maybe_parse_struct_expr(
2306 qself
: Option
<&ast
::QSelf
>,
2309 ) -> Option
<PResult
<'a
, P
<Expr
>>> {
2310 let struct_allowed
= !self.restrictions
.contains(Restrictions
::NO_STRUCT_LITERAL
);
2311 if struct_allowed
|| self.is_certainly_not_a_block() {
2312 if let Err(err
) = self.expect(&token
::OpenDelim(token
::Brace
)) {
2313 return Some(Err(err
));
2315 let expr
= self.parse_struct_expr(qself
.cloned(), path
.clone(), attrs
.clone(), true);
2316 if let (Ok(expr
), false) = (&expr
, struct_allowed
) {
2317 // This is a struct literal, but we don't can't accept them here.
2318 self.error_struct_lit_not_allowed_here(path
.span
, expr
.span
);
2325 fn error_struct_lit_not_allowed_here(&self, lo
: Span
, sp
: Span
) {
2326 self.struct_span_err(sp
, "struct literals are not allowed here")
2327 .multipart_suggestion(
2328 "surround the struct literal with parentheses",
2329 vec
![(lo
.shrink_to_lo(), "(".to_string()), (sp
.shrink_to_hi(), ")".to_string())],
2330 Applicability
::MachineApplicable
,
2335 /// Precondition: already parsed the '{'.
2336 pub(super) fn parse_struct_expr(
2338 qself
: Option
<ast
::QSelf
>,
2342 ) -> PResult
<'a
, P
<Expr
>> {
2343 let mut fields
= Vec
::new();
2344 let mut base
= ast
::StructRest
::None
;
2345 let mut recover_async
= false;
2347 let mut async_block_err
= |e
: &mut DiagnosticBuilder
<'_
>, span
: Span
| {
2348 recover_async
= true;
2349 e
.span_label(span
, "`async` blocks are only allowed in Rust 2018 or later");
2350 e
.help(&format
!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION
));
2351 e
.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
2354 while self.token
!= token
::CloseDelim(token
::Brace
) {
2355 if self.eat(&token
::DotDot
) {
2356 let exp_span
= self.prev_token
.span
;
2357 // We permit `.. }` on the left-hand side of a destructuring assignment.
2358 if self.check(&token
::CloseDelim(token
::Brace
)) {
2359 self.sess
.gated_spans
.gate(sym
::destructuring_assignment
, self.prev_token
.span
);
2360 base
= ast
::StructRest
::Rest(self.prev_token
.span
.shrink_to_hi());
2363 match self.parse_expr() {
2364 Ok(e
) => base
= ast
::StructRest
::Base(e
),
2365 Err(mut e
) if recover
=> {
2367 self.recover_stmt();
2369 Err(e
) => return Err(e
),
2371 self.recover_struct_comma_after_dotdot(exp_span
);
2375 let recovery_field
= self.find_struct_error_after_field_looking_code();
2376 let parsed_field
= match self.parse_expr_field() {
2379 if pth
== kw
::Async
{
2380 async_block_err(&mut e
, pth
.span
);
2382 e
.span_label(pth
.span
, "while parsing this struct");
2386 // If the next token is a comma, then try to parse
2387 // what comes next as additional fields, rather than
2388 // bailing out until next `}`.
2389 if self.token
!= token
::Comma
{
2390 self.recover_stmt_(SemiColonMode
::Comma
, BlockMode
::Ignore
);
2391 if self.token
!= token
::Comma
{
2399 match self.expect_one_of(&[token
::Comma
], &[token
::CloseDelim(token
::Brace
)]) {
2401 if let Some(f
) = parsed_field
.or(recovery_field
) {
2402 // Only include the field if there's no parse error for the field name.
2407 if pth
== kw
::Async
{
2408 async_block_err(&mut e
, pth
.span
);
2410 e
.span_label(pth
.span
, "while parsing this struct");
2411 if let Some(f
) = recovery_field
{
2414 self.prev_token
.span
.shrink_to_hi(),
2415 "try adding a comma",
2417 Applicability
::MachineApplicable
,
2425 self.recover_stmt_(SemiColonMode
::Comma
, BlockMode
::Ignore
);
2426 self.eat(&token
::Comma
);
2431 let span
= pth
.span
.to(self.token
.span
);
2432 self.expect(&token
::CloseDelim(token
::Brace
))?
;
2433 let expr
= if recover_async
{
2436 ExprKind
::Struct(P(ast
::StructExpr { qself, path: pth, fields, rest: base }
))
2438 Ok(self.mk_expr(span
, expr
, attrs
))
2441 /// Use in case of error after field-looking code: `S { foo: () with a }`.
2442 fn find_struct_error_after_field_looking_code(&self) -> Option
<ExprField
> {
2443 match self.token
.ident() {
2444 Some((ident
, is_raw
))
2445 if (is_raw
|| !ident
.is_reserved())
2446 && self.look_ahead(1, |t
| *t
== token
::Colon
) =>
2448 Some(ast
::ExprField
{
2450 span
: self.token
.span
,
2451 expr
: self.mk_expr_err(self.token
.span
),
2452 is_shorthand
: false,
2453 attrs
: AttrVec
::new(),
2455 is_placeholder
: false,
2462 fn recover_struct_comma_after_dotdot(&mut self, span
: Span
) {
2463 if self.token
!= token
::Comma
{
2466 self.struct_span_err(
2467 span
.to(self.prev_token
.span
),
2468 "cannot use a comma after the base struct",
2470 .span_suggestion_short(
2472 "remove this comma",
2474 Applicability
::MachineApplicable
,
2476 .note("the base struct must always be the last field")
2478 self.recover_stmt();
2481 /// Parses `ident (COLON expr)?`.
2482 fn parse_expr_field(&mut self) -> PResult
<'a
, ExprField
> {
2483 let attrs
= self.parse_outer_attributes()?
;
2484 self.collect_tokens_trailing_token(attrs
, ForceCollect
::No
, |this
, attrs
| {
2485 let lo
= this
.token
.span
;
2487 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2488 let is_shorthand
= !this
.look_ahead(1, |t
| t
== &token
::Colon
|| t
== &token
::Eq
);
2489 let (ident
, expr
) = if is_shorthand
{
2490 // Mimic `x: x` for the `x` field shorthand.
2491 let ident
= this
.parse_ident_common(false)?
;
2492 let path
= ast
::Path
::from_ident(ident
);
2493 (ident
, this
.mk_expr(ident
.span
, ExprKind
::Path(None
, path
), AttrVec
::new()))
2495 let ident
= this
.parse_field_name()?
;
2496 this
.error_on_eq_field_init(ident
);
2498 (ident
, this
.parse_expr()?
)
2504 span
: lo
.to(expr
.span
),
2507 attrs
: attrs
.into(),
2509 is_placeholder
: false,
2511 TrailingToken
::MaybeComma
,
2516 /// Check for `=`. This means the source incorrectly attempts to
2517 /// initialize a field with an eq rather than a colon.
2518 fn error_on_eq_field_init(&self, field_name
: Ident
) {
2519 if self.token
!= token
::Eq
{
2523 self.struct_span_err(self.token
.span
, "expected `:`, found `=`")
2525 field_name
.span
.shrink_to_hi().to(self.token
.span
),
2526 "replace equals symbol with a colon",
2528 Applicability
::MachineApplicable
,
2533 fn err_dotdotdot_syntax(&self, span
: Span
) {
2534 self.struct_span_err(span
, "unexpected token: `...`")
2537 "use `..` for an exclusive range",
2539 Applicability
::MaybeIncorrect
,
2543 "or `..=` for an inclusive range",
2545 Applicability
::MaybeIncorrect
,
2550 fn err_larrow_operator(&self, span
: Span
) {
2551 self.struct_span_err(span
, "unexpected token: `<-`")
2554 "if you meant to write a comparison against a negative value, add a \
2555 space in between `<` and `-`",
2557 Applicability
::MaybeIncorrect
,
2562 fn mk_assign_op(&self, binop
: BinOp
, lhs
: P
<Expr
>, rhs
: P
<Expr
>) -> ExprKind
{
2563 ExprKind
::AssignOp(binop
, lhs
, rhs
)
2568 start
: Option
<P
<Expr
>>,
2569 end
: Option
<P
<Expr
>>,
2570 limits
: RangeLimits
,
2572 if end
.is_none() && limits
== RangeLimits
::Closed
{
2573 self.inclusive_range_with_incorrect_end(self.prev_token
.span
);
2576 ExprKind
::Range(start
, end
, limits
)
2580 fn mk_unary(&self, unop
: UnOp
, expr
: P
<Expr
>) -> ExprKind
{
2581 ExprKind
::Unary(unop
, expr
)
2584 fn mk_binary(&self, binop
: BinOp
, lhs
: P
<Expr
>, rhs
: P
<Expr
>) -> ExprKind
{
2585 ExprKind
::Binary(binop
, lhs
, rhs
)
2588 fn mk_index(&self, expr
: P
<Expr
>, idx
: P
<Expr
>) -> ExprKind
{
2589 ExprKind
::Index(expr
, idx
)
2592 fn mk_call(&self, f
: P
<Expr
>, args
: Vec
<P
<Expr
>>) -> ExprKind
{
2593 ExprKind
::Call(f
, args
)
2596 fn mk_await_expr(&mut self, self_arg
: P
<Expr
>, lo
: Span
) -> P
<Expr
> {
2597 let span
= lo
.to(self.prev_token
.span
);
2598 let await_expr
= self.mk_expr(span
, ExprKind
::Await(self_arg
), AttrVec
::new());
2599 self.recover_from_await_method_call();
2603 crate fn mk_expr(&self, span
: Span
, kind
: ExprKind
, attrs
: AttrVec
) -> P
<Expr
> {
2604 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None }
)
2607 pub(super) fn mk_expr_err(&self, span
: Span
) -> P
<Expr
> {
2608 self.mk_expr(span
, ExprKind
::Err
, AttrVec
::new())
2611 /// Create expression span ensuring the span of the parent node
2612 /// is larger than the span of lhs and rhs, including the attributes.
2613 fn mk_expr_sp(&self, lhs
: &P
<Expr
>, lhs_span
: Span
, rhs_span
: Span
) -> Span
{
2616 .find(|a
| a
.style
== AttrStyle
::Outer
)
2617 .map_or(lhs_span
, |a
| a
.span
)
2621 fn collect_tokens_for_expr(
2624 f
: impl FnOnce(&mut Self, Vec
<ast
::Attribute
>) -> PResult
<'a
, P
<Expr
>>,
2625 ) -> PResult
<'a
, P
<Expr
>> {
2626 self.collect_tokens_trailing_token(attrs
, ForceCollect
::No
, |this
, attrs
| {
2627 let res
= f(this
, attrs
)?
;
2628 let trailing
= if this
.restrictions
.contains(Restrictions
::STMT_EXPR
)
2629 && this
.token
.kind
== token
::Semi
2633 // FIXME - pass this through from the place where we know
2634 // we need a comma, rather than assuming that `#[attr] expr,`
2635 // always captures a trailing comma
2636 TrailingToken
::MaybeComma