1 use super::pat
::{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_span
::edition
::LATEST_STABLE_EDITION
;
19 use rustc_span
::source_map
::{self, Span, Spanned}
;
20 use rustc_span
::symbol
::{kw, sym, Ident, Symbol}
;
21 use rustc_span
::{BytePos, Pos}
;
24 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
25 /// dropped into the token stream, which happens while parsing the result of
26 /// macro expansion). Placement of these is not as complex as I feared it would
27 /// be. The important thing is to make sure that lookahead doesn't balk at
28 /// `token::Interpolated` tokens.
29 macro_rules
! maybe_whole_expr
{
31 if let token
::Interpolated(nt
) = &$p
.token
.kind
{
33 token
::NtExpr(e
) | token
::NtLiteral(e
) => {
38 token
::NtPath(path
) => {
39 let path
= path
.clone();
43 ExprKind
::Path(None
, path
),
47 token
::NtBlock(block
) => {
48 let block
= block
.clone();
52 ExprKind
::Block(block
, None
),
63 pub(super) enum LhsExpr
{
65 AttributesParsed(AttrWrapper
),
66 AlreadyParsed(P
<Expr
>),
69 impl From
<Option
<AttrWrapper
>> for LhsExpr
{
70 /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
71 /// and `None` into `LhsExpr::NotYetParsed`.
73 /// This conversion does not allocate.
74 fn from(o
: Option
<AttrWrapper
>) -> Self {
75 if let Some(attrs
) = o { LhsExpr::AttributesParsed(attrs) }
else { LhsExpr::NotYetParsed }
79 impl From
<P
<Expr
>> for LhsExpr
{
80 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
82 /// This conversion does not allocate.
83 fn from(expr
: P
<Expr
>) -> Self {
84 LhsExpr
::AlreadyParsed(expr
)
89 /// Parses an expression.
91 pub fn parse_expr(&mut self) -> PResult
<'a
, P
<Expr
>> {
92 self.parse_expr_res(Restrictions
::empty(), None
)
95 /// Parses an expression, forcing tokens to be collected
96 pub fn parse_expr_force_collect(&mut self) -> PResult
<'a
, P
<Expr
>> {
97 // If we have outer attributes, then the call to `collect_tokens_trailing_token`
98 // will be made for us.
99 if matches
!(self.token
.kind
, TokenKind
::Pound
| TokenKind
::DocComment(..)) {
102 // If we don't have outer attributes, then we need to ensure
103 // that collection happens by using `collect_tokens_no_attrs`.
104 // Expression don't support custom inner attributes, so `parse_expr`
105 // will never try to collect tokens if we don't have outer attributes.
106 self.collect_tokens_no_attrs(|this
| this
.parse_expr())
110 pub fn parse_anon_const_expr(&mut self) -> PResult
<'a
, AnonConst
> {
111 self.parse_expr().map(|value
| AnonConst { id: DUMMY_NODE_ID, value }
)
114 fn parse_expr_catch_underscore(&mut self) -> PResult
<'a
, P
<Expr
>> {
115 match self.parse_expr() {
116 Ok(expr
) => Ok(expr
),
117 Err(mut err
) => match self.token
.ident() {
118 Some((Ident { name: kw::Underscore, .. }
, false))
119 if self.look_ahead(1, |t
| t
== &token
::Comma
) =>
121 // Special-case handling of `foo(_, _, _)`
124 Ok(self.mk_expr(self.prev_token
.span
, ExprKind
::Err
, AttrVec
::new()))
131 /// Parses a sequence of expressions delimited by parentheses.
132 fn parse_paren_expr_seq(&mut self) -> PResult
<'a
, Vec
<P
<Expr
>>> {
133 self.parse_paren_comma_seq(|p
| p
.parse_expr_catch_underscore()).map(|(r
, _
)| r
)
136 /// Parses an expression, subject to the given restrictions.
138 pub(super) fn parse_expr_res(
141 already_parsed_attrs
: Option
<AttrWrapper
>,
142 ) -> PResult
<'a
, P
<Expr
>> {
143 self.with_res(r
, |this
| this
.parse_assoc_expr(already_parsed_attrs
))
146 /// Parses an associative expression.
148 /// This parses an expression accounting for associativity and precedence of the operators in
153 already_parsed_attrs
: Option
<AttrWrapper
>,
154 ) -> PResult
<'a
, P
<Expr
>> {
155 self.parse_assoc_expr_with(0, already_parsed_attrs
.into())
158 /// Parses an associative expression with operators of at least `min_prec` precedence.
159 pub(super) fn parse_assoc_expr_with(
163 ) -> PResult
<'a
, P
<Expr
>> {
164 let mut lhs
= if let LhsExpr
::AlreadyParsed(expr
) = lhs
{
167 let attrs
= match lhs
{
168 LhsExpr
::AttributesParsed(attrs
) => Some(attrs
),
171 if [token
::DotDot
, token
::DotDotDot
, token
::DotDotEq
].contains(&self.token
.kind
) {
172 return self.parse_prefix_range_expr(attrs
);
174 self.parse_prefix_expr(attrs
)?
177 let last_type_ascription_set
= self.last_type_ascription
.is_some();
179 if !self.should_continue_as_assoc_expr(&lhs
) {
180 self.last_type_ascription
= None
;
184 self.expected_tokens
.push(TokenType
::Operator
);
185 while let Some(op
) = self.check_assoc_op() {
186 // Adjust the span for interpolated LHS to point to the `$lhs` token
187 // and not to what it refers to.
188 let lhs_span
= match self.prev_token
.kind
{
189 TokenKind
::Interpolated(..) => self.prev_token
.span
,
193 let cur_op_span
= self.token
.span
;
194 let restrictions
= if op
.node
.is_assign_like() {
195 self.restrictions
& Restrictions
::NO_STRUCT_LITERAL
199 let prec
= op
.node
.precedence();
203 // Check for deprecated `...` syntax
204 if self.token
== token
::DotDotDot
&& op
.node
== AssocOp
::DotDotEq
{
205 self.err_dotdotdot_syntax(self.token
.span
);
208 if self.token
== token
::LArrow
{
209 self.err_larrow_operator(self.token
.span
);
213 if op
.node
.is_comparison() {
214 if let Some(expr
) = self.check_no_chained_comparison(&lhs
, &op
)?
{
219 if (op
.node
== AssocOp
::Equal
|| op
.node
== AssocOp
::NotEqual
)
220 && self.token
.kind
== token
::Eq
221 && self.prev_token
.span
.hi() == self.token
.span
.lo()
223 // Look for JS' `===` and `!==` and recover 😇
224 let sp
= op
.span
.to(self.token
.span
);
225 let sugg
= match op
.node
{
226 AssocOp
::Equal
=> "==",
227 AssocOp
::NotEqual
=> "!=",
230 self.struct_span_err(sp
, &format
!("invalid comparison operator `{}=`", sugg
))
231 .span_suggestion_short(
233 &format
!("`{s}=` is not a valid comparison operator, use `{s}`", s
= sugg
),
235 Applicability
::MachineApplicable
,
243 if op
== AssocOp
::As
{
244 lhs
= self.parse_assoc_op_cast(lhs
, lhs_span
, ExprKind
::Cast
)?
;
246 } else if op
== AssocOp
::Colon
{
247 lhs
= self.parse_assoc_op_ascribe(lhs
, lhs_span
)?
;
249 } else if op
== AssocOp
::DotDot
|| op
== AssocOp
::DotDotEq
{
250 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
251 // generalise it to the Fixity::None code.
252 lhs
= self.parse_range_expr(prec
, lhs
, op
, cur_op_span
)?
;
256 let fixity
= op
.fixity();
257 let prec_adjustment
= match fixity
{
260 // We currently have no non-associative operators that are not handled above by
261 // the special cases. The code is here only for future convenience.
264 let rhs
= self.with_res(restrictions
- Restrictions
::STMT_EXPR
, |this
| {
265 this
.parse_assoc_expr_with(prec
+ prec_adjustment
, LhsExpr
::NotYetParsed
)
268 let span
= self.mk_expr_sp(&lhs
, lhs_span
, rhs
.span
);
281 | AssocOp
::ShiftRight
287 | AssocOp
::GreaterEqual
=> {
288 let ast_op
= op
.to_ast_binop().unwrap();
289 let binary
= self.mk_binary(source_map
::respan(cur_op_span
, ast_op
), lhs
, rhs
);
290 self.mk_expr(span
, binary
, AttrVec
::new())
293 self.mk_expr(span
, ExprKind
::Assign(lhs
, rhs
, cur_op_span
), AttrVec
::new())
295 AssocOp
::AssignOp(k
) => {
297 token
::Plus
=> BinOpKind
::Add
,
298 token
::Minus
=> BinOpKind
::Sub
,
299 token
::Star
=> BinOpKind
::Mul
,
300 token
::Slash
=> BinOpKind
::Div
,
301 token
::Percent
=> BinOpKind
::Rem
,
302 token
::Caret
=> BinOpKind
::BitXor
,
303 token
::And
=> BinOpKind
::BitAnd
,
304 token
::Or
=> BinOpKind
::BitOr
,
305 token
::Shl
=> BinOpKind
::Shl
,
306 token
::Shr
=> BinOpKind
::Shr
,
308 let aopexpr
= self.mk_assign_op(source_map
::respan(cur_op_span
, aop
), lhs
, rhs
);
309 self.mk_expr(span
, aopexpr
, AttrVec
::new())
311 AssocOp
::As
| AssocOp
::Colon
| AssocOp
::DotDot
| AssocOp
::DotDotEq
=> {
312 self.span_bug(span
, "AssocOp should have been handled by special case")
316 if let Fixity
::None
= fixity
{
320 if last_type_ascription_set
{
321 self.last_type_ascription
= None
;
326 fn should_continue_as_assoc_expr(&mut self, lhs
: &Expr
) -> bool
{
327 match (self.expr_is_complete(lhs
), AssocOp
::from_token(&self.token
)) {
328 // Semi-statement forms are odd:
329 // See https://github.com/rust-lang/rust/issues/29071
330 (true, None
) => false,
331 (false, _
) => true, // Continue parsing the expression.
332 // An exhaustive check is done in the following block, but these are checked first
333 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
334 // want to keep their span info to improve diagnostics in these cases in a later stage.
335 (true, Some(AssocOp
::Multiply
)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
336 (true, Some(AssocOp
::Subtract
)) | // `{ 42 } -5`
337 (true, Some(AssocOp
::Add
)) // `{ 42 } + 42
338 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
339 // `if x { a } else { b } && if y { c } else { d }`
340 if !self.look_ahead(1, |t
| t
.is_used_keyword()) => {
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(AssocOp
::LAnd
)) => {
347 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`. Separated from the
348 // above due to #74233.
349 // These cases are ambiguous and can't be identified in the parser alone.
350 let sp
= self.sess
.source_map().start_point(self.token
.span
);
351 self.sess
.ambiguous_block_expr_parse
.borrow_mut().insert(sp
, lhs
.span
);
354 (true, Some(ref op
)) if !op
.can_continue_expr_unambiguously() => false,
356 self.error_found_expr_would_be_stmt(lhs
);
362 /// We've found an expression that would be parsed as a statement,
363 /// but the next token implies this should be parsed as an expression.
364 /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
365 fn error_found_expr_would_be_stmt(&self, lhs
: &Expr
) {
366 let mut err
= self.struct_span_err(
368 &format
!("expected expression, found `{}`", pprust
::token_to_string(&self.token
),),
370 err
.span_label(self.token
.span
, "expected expression");
371 self.sess
.expr_parentheses_needed(&mut err
, lhs
.span
, Some(pprust
::expr_to_string(&lhs
)));
375 /// Possibly translate the current token to an associative operator.
376 /// The method does not advance the current token.
378 /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
379 fn check_assoc_op(&self) -> Option
<Spanned
<AssocOp
>> {
380 let (op
, span
) = match (AssocOp
::from_token(&self.token
), self.token
.ident()) {
381 // When parsing const expressions, stop parsing when encountering `>`.
386 | AssocOp
::GreaterEqual
387 | AssocOp
::AssignOp(token
::BinOpToken
::Shr
),
390 ) if self.restrictions
.contains(Restrictions
::CONST_EXPR
) => {
393 (Some(op
), _
) => (op
, self.token
.span
),
394 (None
, Some((Ident { name: sym::and, span }
, false))) => {
395 self.error_bad_logical_op("and", "&&", "conjunction");
396 (AssocOp
::LAnd
, span
)
398 (None
, Some((Ident { name: sym::or, span }
, false))) => {
399 self.error_bad_logical_op("or", "||", "disjunction");
404 Some(source_map
::respan(span
, op
))
407 /// Error on `and` and `or` suggesting `&&` and `||` respectively.
408 fn error_bad_logical_op(&self, bad
: &str, good
: &str, english
: &str) {
409 self.struct_span_err(self.token
.span
, &format
!("`{}` is not a logical operator", bad
))
410 .span_suggestion_short(
412 &format
!("use `{}` to perform logical {}", good
, english
),
414 Applicability
::MachineApplicable
,
416 .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators")
420 /// Checks if this expression is a successfully parsed statement.
421 fn expr_is_complete(&self, e
: &Expr
) -> bool
{
422 self.restrictions
.contains(Restrictions
::STMT_EXPR
)
423 && !classify
::expr_requires_semi_to_be_stmt(e
)
426 /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
427 /// The other two variants are handled in `parse_prefix_range_expr` below.
434 ) -> PResult
<'a
, P
<Expr
>> {
435 let rhs
= if self.is_at_start_of_range_notation_rhs() {
436 Some(self.parse_assoc_expr_with(prec
+ 1, LhsExpr
::NotYetParsed
)?
)
440 let rhs_span
= rhs
.as_ref().map_or(cur_op_span
, |x
| x
.span
);
441 let span
= self.mk_expr_sp(&lhs
, lhs
.span
, rhs_span
);
443 if op
== AssocOp
::DotDot { RangeLimits::HalfOpen }
else { RangeLimits::Closed }
;
444 Ok(self.mk_expr(span
, self.mk_range(Some(lhs
), rhs
, limits
), AttrVec
::new()))
447 fn is_at_start_of_range_notation_rhs(&self) -> bool
{
448 if self.token
.can_begin_expr() {
449 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
450 if self.token
== token
::OpenDelim(token
::Brace
) {
451 return !self.restrictions
.contains(Restrictions
::NO_STRUCT_LITERAL
);
459 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
460 fn parse_prefix_range_expr(&mut self, attrs
: Option
<AttrWrapper
>) -> PResult
<'a
, P
<Expr
>> {
461 // Check for deprecated `...` syntax.
462 if self.token
== token
::DotDotDot
{
463 self.err_dotdotdot_syntax(self.token
.span
);
467 [token
::DotDot
, token
::DotDotDot
, token
::DotDotEq
].contains(&self.token
.kind
),
468 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
472 let limits
= match self.token
.kind
{
473 token
::DotDot
=> RangeLimits
::HalfOpen
,
474 _
=> RangeLimits
::Closed
,
476 let op
= AssocOp
::from_token(&self.token
);
477 // FIXME: `parse_prefix_range_expr` is called when the current
478 // token is `DotDot`, `DotDotDot`, or `DotDotEq`. If we haven't already
479 // parsed attributes, then trying to parse them here will always fail.
480 // We should figure out how we want attributes on range expressions to work.
481 let attrs
= self.parse_or_use_outer_attributes(attrs
)?
;
482 self.collect_tokens_for_expr(attrs
, |this
, attrs
| {
483 let lo
= this
.token
.span
;
485 let (span
, opt_end
) = if this
.is_at_start_of_range_notation_rhs() {
486 // RHS must be parsed with more associativity than the dots.
487 this
.parse_assoc_expr_with(op
.unwrap().precedence() + 1, LhsExpr
::NotYetParsed
)
488 .map(|x
| (lo
.to(x
.span
), Some(x
)))?
492 Ok(this
.mk_expr(span
, this
.mk_range(None
, opt_end
, limits
), attrs
.into()))
496 /// Parses a prefix-unary-operator expr.
497 fn parse_prefix_expr(&mut self, attrs
: Option
<AttrWrapper
>) -> PResult
<'a
, P
<Expr
>> {
498 let attrs
= self.parse_or_use_outer_attributes(attrs
)?
;
499 let lo
= self.token
.span
;
501 macro_rules
! make_it
{
502 ($this
:ident
, $attrs
:expr
, |this
, _
| $body
:expr
) => {
503 $this
.collect_tokens_for_expr($attrs
, |$this
, attrs
| {
504 let (hi
, ex
) = $body?
;
505 Ok($this
.mk_expr(lo
.to(hi
), ex
, attrs
.into()))
512 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
513 match this
.token
.uninterpolate().kind
{
514 token
::Not
=> make_it
!(this
, attrs
, |this
, _
| this
.parse_unary_expr(lo
, UnOp
::Not
)), // `!expr`
515 token
::Tilde
=> make_it
!(this
, attrs
, |this
, _
| this
.recover_tilde_expr(lo
)), // `~expr`
516 token
::BinOp(token
::Minus
) => {
517 make_it
!(this
, attrs
, |this
, _
| this
.parse_unary_expr(lo
, UnOp
::Neg
))
519 token
::BinOp(token
::Star
) => {
520 make_it
!(this
, attrs
, |this
, _
| this
.parse_unary_expr(lo
, UnOp
::Deref
))
522 token
::BinOp(token
::And
) | token
::AndAnd
=> {
523 make_it
!(this
, attrs
, |this
, _
| this
.parse_borrow_expr(lo
))
525 token
::Ident(..) if this
.token
.is_keyword(kw
::Box
) => {
526 make_it
!(this
, attrs
, |this
, _
| this
.parse_box_expr(lo
))
528 token
::Ident(..) if this
.is_mistaken_not_ident_negation() => {
529 make_it
!(this
, attrs
, |this
, _
| this
.recover_not_expr(lo
))
531 _
=> return this
.parse_dot_or_call_expr(Some(attrs
)),
535 fn parse_prefix_expr_common(&mut self, lo
: Span
) -> PResult
<'a
, (Span
, P
<Expr
>)> {
537 let expr
= self.parse_prefix_expr(None
);
538 let (span
, expr
) = self.interpolated_or_expr_span(expr
)?
;
539 Ok((lo
.to(span
), expr
))
542 fn parse_unary_expr(&mut self, lo
: Span
, op
: UnOp
) -> PResult
<'a
, (Span
, ExprKind
)> {
543 let (span
, expr
) = self.parse_prefix_expr_common(lo
)?
;
544 Ok((span
, self.mk_unary(op
, expr
)))
547 // Recover on `!` suggesting for bitwise negation instead.
548 fn recover_tilde_expr(&mut self, lo
: Span
) -> PResult
<'a
, (Span
, ExprKind
)> {
549 self.struct_span_err(lo
, "`~` cannot be used as a unary operator")
550 .span_suggestion_short(
552 "use `!` to perform bitwise not",
554 Applicability
::MachineApplicable
,
558 self.parse_unary_expr(lo
, UnOp
::Not
)
561 /// Parse `box expr`.
562 fn parse_box_expr(&mut self, lo
: Span
) -> PResult
<'a
, (Span
, ExprKind
)> {
563 let (span
, expr
) = self.parse_prefix_expr_common(lo
)?
;
564 self.sess
.gated_spans
.gate(sym
::box_syntax
, span
);
565 Ok((span
, ExprKind
::Box(expr
)))
568 fn is_mistaken_not_ident_negation(&self) -> bool
{
569 let token_cannot_continue_expr
= |t
: &Token
| match t
.uninterpolate().kind
{
570 // These tokens can start an expression after `!`, but
571 // can't continue an expression after an ident
572 token
::Ident(name
, is_raw
) => token
::ident_can_begin_expr(name
, t
.span
, is_raw
),
573 token
::Literal(..) | token
::Pound
=> true,
574 _
=> t
.is_whole_expr(),
576 self.token
.is_ident_named(sym
::not
) && self.look_ahead(1, token_cannot_continue_expr
)
579 /// Recover on `not expr` in favor of `!expr`.
580 fn recover_not_expr(&mut self, lo
: Span
) -> PResult
<'a
, (Span
, ExprKind
)> {
582 let not_token
= self.look_ahead(1, |t
| t
.clone());
583 self.struct_span_err(
585 &format
!("unexpected {} after identifier", super::token_descr(¬_token
)),
587 .span_suggestion_short(
588 // Span the `not` plus trailing whitespace to avoid
589 // trailing whitespace after the `!` in our suggestion
590 self.sess
.source_map().span_until_non_whitespace(lo
.to(not_token
.span
)),
591 "use `!` to perform logical negation",
593 Applicability
::MachineApplicable
,
598 self.parse_unary_expr(lo
, UnOp
::Not
)
601 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
602 fn interpolated_or_expr_span(
604 expr
: PResult
<'a
, P
<Expr
>>,
605 ) -> PResult
<'a
, (Span
, P
<Expr
>)> {
608 match self.prev_token
.kind
{
609 TokenKind
::Interpolated(..) => self.prev_token
.span
,
617 fn parse_assoc_op_cast(
621 expr_kind
: fn(P
<Expr
>, P
<Ty
>) -> ExprKind
,
622 ) -> PResult
<'a
, P
<Expr
>> {
623 let mk_expr
= |this
: &mut Self, lhs
: P
<Expr
>, rhs
: P
<Ty
>| {
625 this
.mk_expr_sp(&lhs
, lhs_span
, rhs
.span
),
631 // Save the state of the parser before parsing type normally, in case there is a
632 // LessThan comparison after this cast.
633 let parser_snapshot_before_type
= self.clone();
634 let cast_expr
= match self.parse_ty_no_plus() {
635 Ok(rhs
) => mk_expr(self, lhs
, rhs
),
636 Err(mut type_err
) => {
637 // Rewind to before attempting to parse the type with generics, to recover
638 // from situations like `x as usize < y` in which we first tried to parse
639 // `usize < y` as a type with generic arguments.
640 let parser_snapshot_after_type
= mem
::replace(self, parser_snapshot_before_type
);
642 // Check for typo of `'a: loop { break 'a }` with a missing `'`.
643 match (&lhs
.kind
, &self.token
.kind
) {
646 ExprKind
::Path(None
, ast
::Path { segments, .. }
),
647 TokenKind
::Ident(kw
::For
| kw
::Loop
| kw
::While
, false),
648 ) if segments
.len() == 1 => {
649 let snapshot
= self.clone();
651 ident
: Ident
::from_str_and_span(
652 &format
!("'{}", segments
[0].ident
),
653 segments
[0].ident
.span
,
656 match self.parse_labeled_expr(label
, AttrVec
::new(), false) {
659 self.struct_span_err(label
.ident
.span
, "malformed loop label")
662 "use the correct loop label format",
663 label
.ident
.to_string(),
664 Applicability
::MachineApplicable
,
678 match self.parse_path(PathStyle
::Expr
) {
680 let (op_noun
, op_verb
) = match self.token
.kind
{
681 token
::Lt
=> ("comparison", "comparing"),
682 token
::BinOp(token
::Shl
) => ("shift", "shifting"),
684 // We can end up here even without `<` being the next token, for
685 // example because `parse_ty_no_plus` returns `Err` on keywords,
686 // but `parse_path` returns `Ok` on them due to error recovery.
687 // Return original error and parser state.
688 *self = parser_snapshot_after_type
;
689 return Err(type_err
);
693 // Successfully parsed the type path leaving a `<` yet to parse.
696 // Report non-fatal diagnostics, keep `x as usize` as an expression
697 // in AST and continue parsing.
699 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
700 pprust
::path_to_string(&path
),
703 let span_after_type
= parser_snapshot_after_type
.token
.span
;
705 mk_expr(self, lhs
, self.mk_ty(path
.span
, TyKind
::Path(None
, path
)));
708 .span_to_snippet(expr
.span
)
709 .unwrap_or_else(|_
| pprust
::expr_to_string(&expr
));
711 self.struct_span_err(self.token
.span
, &msg
)
713 self.look_ahead(1, |t
| t
.span
).to(span_after_type
),
714 "interpreted as generic arguments",
716 .span_label(self.token
.span
, format
!("not interpreted as {}", op_noun
))
719 &format
!("try {} the cast value", op_verb
),
720 format
!("({})", expr_str
),
721 Applicability
::MachineApplicable
,
727 Err(mut path_err
) => {
728 // Couldn't parse as a path, return original error and parser state.
730 *self = parser_snapshot_after_type
;
731 return Err(type_err
);
737 self.parse_and_disallow_postfix_after_cast(cast_expr
)
740 /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
741 /// then emits an error and returns the newly parsed tree.
742 /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
743 fn parse_and_disallow_postfix_after_cast(
746 ) -> PResult
<'a
, P
<Expr
>> {
747 // Save the memory location of expr before parsing any following postfix operators.
748 // This will be compared with the memory location of the output expression.
749 // If they different we can assume we parsed another expression because the existing expression is not reallocated.
750 let addr_before
= &*cast_expr
as *const _
as usize;
751 let span
= cast_expr
.span
;
752 let with_postfix
= self.parse_dot_or_call_expr_with_(cast_expr
, span
)?
;
753 let changed
= addr_before
!= &*with_postfix
as *const _
as usize;
755 // Check if an illegal postfix operator has been added after the cast.
756 // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator.
757 if !matches
!(with_postfix
.kind
, ExprKind
::Cast(_
, _
) | ExprKind
::Type(_
, _
)) || changed
{
759 "casts cannot be followed by {}",
760 match with_postfix
.kind
{
761 ExprKind
::Index(_
, _
) => "indexing",
762 ExprKind
::Try(_
) => "?",
763 ExprKind
::Field(_
, _
) => "a field access",
764 ExprKind
::MethodCall(_
, _
, _
) => "a method call",
765 ExprKind
::Call(_
, _
) => "a function call",
766 ExprKind
::Await(_
) => "`.await`",
767 ExprKind
::Err
=> return Ok(with_postfix
),
768 _
=> unreachable
!("parse_dot_or_call_expr_with_ shouldn't produce this"),
771 let mut err
= self.struct_span_err(span
, &msg
);
772 // If type ascription is "likely an error", the user will already be getting a useful
773 // help message, and doesn't need a second.
774 if self.last_type_ascription
.map_or(false, |last_ascription
| last_ascription
.1) {
775 self.maybe_annotate_with_ascription(&mut err
, false);
777 let suggestions
= vec
![
778 (span
.shrink_to_lo(), "(".to_string()),
779 (span
.shrink_to_hi(), ")".to_string()),
781 err
.multipart_suggestion(
782 "try surrounding the expression in parentheses",
784 Applicability
::MachineApplicable
,
792 fn parse_assoc_op_ascribe(&mut self, lhs
: P
<Expr
>, lhs_span
: Span
) -> PResult
<'a
, P
<Expr
>> {
793 let maybe_path
= self.could_ascription_be_path(&lhs
.kind
);
794 self.last_type_ascription
= Some((self.prev_token
.span
, maybe_path
));
795 let lhs
= self.parse_assoc_op_cast(lhs
, lhs_span
, ExprKind
::Type
)?
;
796 self.sess
.gated_spans
.gate(sym
::type_ascription
, lhs
.span
);
800 /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
801 fn parse_borrow_expr(&mut self, lo
: Span
) -> PResult
<'a
, (Span
, ExprKind
)> {
803 let has_lifetime
= self.token
.is_lifetime() && self.look_ahead(1, |t
| t
!= &token
::Colon
);
804 let lifetime
= has_lifetime
.then(|| self.expect_lifetime()); // For recovery, see below.
805 let (borrow_kind
, mutbl
) = self.parse_borrow_modifiers(lo
);
806 let expr
= self.parse_prefix_expr(None
);
807 let (hi
, expr
) = self.interpolated_or_expr_span(expr
)?
;
808 let span
= lo
.to(hi
);
809 if let Some(lt
) = lifetime
{
810 self.error_remove_borrow_lifetime(span
, lt
.ident
.span
);
812 Ok((span
, ExprKind
::AddrOf(borrow_kind
, mutbl
, expr
)))
815 fn error_remove_borrow_lifetime(&self, span
: Span
, lt_span
: Span
) {
816 self.struct_span_err(span
, "borrow expressions cannot be annotated with lifetimes")
817 .span_label(lt_span
, "annotated with lifetime here")
820 "remove the lifetime annotation",
822 Applicability
::MachineApplicable
,
827 /// Parse `mut?` or `raw [ const | mut ]`.
828 fn parse_borrow_modifiers(&mut self, lo
: Span
) -> (ast
::BorrowKind
, ast
::Mutability
) {
829 if self.check_keyword(kw
::Raw
) && self.look_ahead(1, Token
::is_mutability
) {
830 // `raw [ const | mut ]`.
831 let found_raw
= self.eat_keyword(kw
::Raw
);
833 let mutability
= self.parse_const_or_mut().unwrap();
834 self.sess
.gated_spans
.gate(sym
::raw_ref_op
, lo
.to(self.prev_token
.span
));
835 (ast
::BorrowKind
::Raw
, mutability
)
838 (ast
::BorrowKind
::Ref
, self.parse_mutability())
842 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
843 fn parse_dot_or_call_expr(&mut self, attrs
: Option
<AttrWrapper
>) -> PResult
<'a
, P
<Expr
>> {
844 let attrs
= self.parse_or_use_outer_attributes(attrs
)?
;
845 self.collect_tokens_for_expr(attrs
, |this
, attrs
| {
846 let base
= this
.parse_bottom_expr();
847 let (span
, base
) = this
.interpolated_or_expr_span(base
)?
;
848 this
.parse_dot_or_call_expr_with(base
, span
, attrs
)
852 pub(super) fn parse_dot_or_call_expr_with(
856 mut attrs
: Vec
<ast
::Attribute
>,
857 ) -> PResult
<'a
, P
<Expr
>> {
858 // Stitch the list of outer attributes onto the return value.
859 // A little bit ugly, but the best way given the current code
861 self.parse_dot_or_call_expr_with_(e0
, lo
).map(|expr
| {
862 expr
.map(|mut expr
| {
863 attrs
.extend
::<Vec
<_
>>(expr
.attrs
.into());
864 expr
.attrs
= attrs
.into();
870 fn parse_dot_or_call_expr_with_(&mut self, mut e
: P
<Expr
>, lo
: Span
) -> PResult
<'a
, P
<Expr
>> {
872 if self.eat(&token
::Question
) {
874 e
= self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::Try(e
), AttrVec
::new());
877 if self.eat(&token
::Dot
) {
879 e
= self.parse_dot_suffix_expr(lo
, e
)?
;
882 if self.expr_is_complete(&e
) {
885 e
= match self.token
.kind
{
886 token
::OpenDelim(token
::Paren
) => self.parse_fn_call_expr(lo
, e
),
887 token
::OpenDelim(token
::Bracket
) => self.parse_index_expr(lo
, e
)?
,
893 fn parse_dot_suffix_expr(&mut self, lo
: Span
, base
: P
<Expr
>) -> PResult
<'a
, P
<Expr
>> {
894 match self.token
.uninterpolate().kind
{
895 token
::Ident(..) => self.parse_dot_suffix(base
, lo
),
896 token
::Literal(token
::Lit { kind: token::Integer, symbol, suffix }
) => {
897 Ok(self.parse_tuple_field_access_expr(lo
, base
, symbol
, suffix
, None
))
899 token
::Literal(token
::Lit { kind: token::Float, symbol, suffix }
) => {
900 Ok(self.parse_tuple_field_access_expr_float(lo
, base
, symbol
, suffix
))
903 self.error_unexpected_after_dot();
909 fn error_unexpected_after_dot(&self) {
910 // FIXME Could factor this out into non_fatal_unexpected or something.
911 let actual
= pprust
::token_to_string(&self.token
);
912 self.struct_span_err(self.token
.span
, &format
!("unexpected token: `{}`", actual
)).emit();
915 // We need an identifier or integer, but the next token is a float.
916 // Break the float into components to extract the identifier or integer.
917 // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
918 // parts unless those parts are processed immediately. `TokenCursor` should either
919 // support pushing "future tokens" (would be also helpful to `break_and_eat`), or
920 // we should break everything including floats into more basic proc-macro style
921 // tokens in the lexer (probably preferable).
922 fn parse_tuple_field_access_expr_float(
927 suffix
: Option
<Symbol
>,
930 enum FloatComponent
{
934 use FloatComponent
::*;
936 let float_str
= float
.as_str();
937 let mut components
= Vec
::new();
938 let mut ident_like
= String
::new();
939 for c
in float_str
.chars() {
940 if c
== '_'
|| c
.is_ascii_alphanumeric() {
942 } else if matches
!(c
, '
.'
| '
+'
| '
-'
) {
943 if !ident_like
.is_empty() {
944 components
.push(IdentLike(mem
::take(&mut ident_like
)));
946 components
.push(Punct(c
));
948 panic
!("unexpected character in a float token: {:?}", c
)
951 if !ident_like
.is_empty() {
952 components
.push(IdentLike(ident_like
));
955 // With proc macros the span can refer to anything, the source may be too short,
956 // or too long, or non-ASCII. It only makes sense to break our span into components
957 // if its underlying text is identical to our float literal.
958 let span
= self.token
.span
;
959 let can_take_span_apart
=
960 || self.span_to_snippet(span
).as_deref() == Ok(float_str
).as_deref();
965 self.parse_tuple_field_access_expr(lo
, base
, Symbol
::intern(&i
), suffix
, None
)
968 [IdentLike(i
), Punct('
.'
)] => {
969 let (ident_span
, dot_span
) = if can_take_span_apart() {
970 let (span
, ident_len
) = (span
.data(), BytePos
::from_usize(i
.len()));
971 let ident_span
= span
.with_hi(span
.lo
+ ident_len
);
972 let dot_span
= span
.with_lo(span
.lo
+ ident_len
);
973 (ident_span
, dot_span
)
977 assert
!(suffix
.is_none());
978 let symbol
= Symbol
::intern(&i
);
979 self.token
= Token
::new(token
::Ident(symbol
, false), ident_span
);
980 let next_token
= (Token
::new(token
::Dot
, dot_span
), self.token_spacing
);
981 self.parse_tuple_field_access_expr(lo
, base
, symbol
, None
, Some(next_token
))
984 [IdentLike(i1
), Punct('
.'
), IdentLike(i2
)] => {
985 let (ident1_span
, dot_span
, ident2_span
) = if can_take_span_apart() {
986 let (span
, ident1_len
) = (span
.data(), BytePos
::from_usize(i1
.len()));
987 let ident1_span
= span
.with_hi(span
.lo
+ ident1_len
);
989 .with_lo(span
.lo
+ ident1_len
)
990 .with_hi(span
.lo
+ ident1_len
+ BytePos(1));
991 let ident2_span
= self.token
.span
.with_lo(span
.lo
+ ident1_len
+ BytePos(1));
992 (ident1_span
, dot_span
, ident2_span
)
996 let symbol1
= Symbol
::intern(&i1
);
997 self.token
= Token
::new(token
::Ident(symbol1
, false), ident1_span
);
998 // This needs to be `Spacing::Alone` to prevent regressions.
999 // See issue #76399 and PR #76285 for more details
1000 let next_token1
= (Token
::new(token
::Dot
, dot_span
), Spacing
::Alone
);
1002 self.parse_tuple_field_access_expr(lo
, base
, symbol1
, None
, Some(next_token1
));
1003 let symbol2
= Symbol
::intern(&i2
);
1004 let next_token2
= Token
::new(token
::Ident(symbol2
, false), ident2_span
);
1005 self.bump_with((next_token2
, self.token_spacing
)); // `.`
1006 self.parse_tuple_field_access_expr(lo
, base1
, symbol2
, suffix
, None
)
1008 // 1e+ | 1e- (recovered)
1009 [IdentLike(_
), Punct('
+'
| '
-'
)] |
1011 [IdentLike(_
), Punct('
+'
| '
-'
), IdentLike(_
)] |
1013 [IdentLike(_
), Punct('
.'
), IdentLike(_
), Punct('
+'
| '
-'
), IdentLike(_
)] => {
1014 // See the FIXME about `TokenCursor` above.
1015 self.error_unexpected_after_dot();
1018 _
=> panic
!("unexpected components in a float token: {:?}", components
),
1022 fn parse_tuple_field_access_expr(
1027 suffix
: Option
<Symbol
>,
1028 next_token
: Option
<(Token
, Spacing
)>,
1031 Some(next_token
) => self.bump_with(next_token
),
1032 None
=> self.bump(),
1034 let span
= self.prev_token
.span
;
1035 let field
= ExprKind
::Field(base
, Ident
::new(field
, span
));
1036 self.expect_no_suffix(span
, "a tuple index", suffix
);
1037 self.mk_expr(lo
.to(span
), field
, AttrVec
::new())
1040 /// Parse a function call expression, `expr(...)`.
1041 fn parse_fn_call_expr(&mut self, lo
: Span
, fun
: P
<Expr
>) -> P
<Expr
> {
1042 let seq
= self.parse_paren_expr_seq().map(|args
| {
1043 self.mk_expr(lo
.to(self.prev_token
.span
), self.mk_call(fun
, args
), AttrVec
::new())
1045 self.recover_seq_parse_error(token
::Paren
, lo
, seq
)
1048 /// Parse an indexing expression `expr[...]`.
1049 fn parse_index_expr(&mut self, lo
: Span
, base
: P
<Expr
>) -> PResult
<'a
, P
<Expr
>> {
1051 let index
= self.parse_expr()?
;
1052 self.expect(&token
::CloseDelim(token
::Bracket
))?
;
1053 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), self.mk_index(base
, index
), AttrVec
::new()))
1056 /// Assuming we have just parsed `.`, continue parsing into an expression.
1057 fn parse_dot_suffix(&mut self, self_arg
: P
<Expr
>, lo
: Span
) -> PResult
<'a
, P
<Expr
>> {
1058 if self.token
.uninterpolated_span().rust_2018() && self.eat_keyword(kw
::Await
) {
1059 return Ok(self.mk_await_expr(self_arg
, lo
));
1062 let fn_span_lo
= self.token
.span
;
1063 let mut segment
= self.parse_path_segment(PathStyle
::Expr
)?
;
1064 self.check_trailing_angle_brackets(&segment
, &[&token
::OpenDelim(token
::Paren
)]);
1065 self.check_turbofish_missing_angle_brackets(&mut segment
);
1067 if self.check(&token
::OpenDelim(token
::Paren
)) {
1068 // Method call `expr.f()`
1069 let mut args
= self.parse_paren_expr_seq()?
;
1070 args
.insert(0, self_arg
);
1072 let fn_span
= fn_span_lo
.to(self.prev_token
.span
);
1073 let span
= lo
.to(self.prev_token
.span
);
1074 Ok(self.mk_expr(span
, ExprKind
::MethodCall(segment
, args
, fn_span
), AttrVec
::new()))
1076 // Field access `expr.f`
1077 if let Some(args
) = segment
.args
{
1078 self.struct_span_err(
1080 "field expressions cannot have generic arguments",
1085 let span
= lo
.to(self.prev_token
.span
);
1086 Ok(self.mk_expr(span
, ExprKind
::Field(self_arg
, segment
.ident
), AttrVec
::new()))
1090 /// At the bottom (top?) of the precedence hierarchy,
1091 /// Parses things like parenthesized exprs, macros, `return`, etc.
1093 /// N.B., this does not parse outer attributes, and is private because it only works
1094 /// correctly if called from `parse_dot_or_call_expr()`.
1095 fn parse_bottom_expr(&mut self) -> PResult
<'a
, P
<Expr
>> {
1096 maybe_recover_from_interpolated_ty_qpath
!(self, true);
1097 maybe_whole_expr
!(self);
1099 // Outer attributes are already parsed and will be
1100 // added to the return value after the fact.
1102 // Therefore, prevent sub-parser from parsing
1103 // attributes by giving them a empty "already-parsed" list.
1104 let attrs
= AttrVec
::new();
1106 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
1107 let lo
= self.token
.span
;
1108 if let token
::Literal(_
) = self.token
.kind
{
1109 // This match arm is a special-case of the `_` match arm below and
1110 // could be removed without changing functionality, but it's faster
1111 // to have it here, especially for programs with large constants.
1112 self.parse_lit_expr(attrs
)
1113 } else if self.check(&token
::OpenDelim(token
::Paren
)) {
1114 self.parse_tuple_parens_expr(attrs
)
1115 } else if self.check(&token
::OpenDelim(token
::Brace
)) {
1116 self.parse_block_expr(None
, lo
, BlockCheckMode
::Default
, attrs
)
1117 } else if self.check(&token
::BinOp(token
::Or
)) || self.check(&token
::OrOr
) {
1118 self.parse_closure_expr(attrs
)
1119 } else if self.check(&token
::OpenDelim(token
::Bracket
)) {
1120 self.parse_array_or_repeat_expr(attrs
)
1121 } else if self.eat_lt() {
1122 let (qself
, path
) = self.parse_qpath(PathStyle
::Expr
)?
;
1123 Ok(self.mk_expr(lo
.to(path
.span
), ExprKind
::Path(Some(qself
), path
), attrs
))
1124 } else if self.check_path() {
1125 self.parse_path_start_expr(attrs
)
1126 } else if self.check_keyword(kw
::Move
) || self.check_keyword(kw
::Static
) {
1127 self.parse_closure_expr(attrs
)
1128 } else if self.eat_keyword(kw
::If
) {
1129 self.parse_if_expr(attrs
)
1130 } else if self.check_keyword(kw
::For
) {
1131 if self.choose_generics_over_qpath(1) {
1132 // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery,
1133 // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns.
1134 // When `for <Foo as Bar>::Proj in $expr $block` is wanted,
1135 // you can disambiguate in favor of a pattern with `(...)`.
1136 self.recover_quantified_closure_expr(attrs
)
1138 assert
!(self.eat_keyword(kw
::For
));
1139 self.parse_for_expr(None
, self.prev_token
.span
, attrs
)
1141 } else if self.eat_keyword(kw
::While
) {
1142 self.parse_while_expr(None
, self.prev_token
.span
, attrs
)
1143 } else if let Some(label
) = self.eat_label() {
1144 self.parse_labeled_expr(label
, attrs
, true)
1145 } else if self.eat_keyword(kw
::Loop
) {
1146 self.parse_loop_expr(None
, self.prev_token
.span
, attrs
)
1147 } else if self.eat_keyword(kw
::Continue
) {
1148 let kind
= ExprKind
::Continue(self.eat_label());
1149 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
))
1150 } else if self.eat_keyword(kw
::Match
) {
1151 let match_sp
= self.prev_token
.span
;
1152 self.parse_match_expr(attrs
).map_err(|mut err
| {
1153 err
.span_label(match_sp
, "while parsing this match expression");
1156 } else if self.eat_keyword(kw
::Unsafe
) {
1157 self.parse_block_expr(None
, lo
, BlockCheckMode
::Unsafe(ast
::UserProvided
), attrs
)
1158 } else if self.check_inline_const(0) {
1159 self.parse_const_block(lo
.to(self.token
.span
))
1160 } else if self.is_do_catch_block() {
1161 self.recover_do_catch(attrs
)
1162 } else if self.is_try_block() {
1163 self.expect_keyword(kw
::Try
)?
;
1164 self.parse_try_block(lo
, attrs
)
1165 } else if self.eat_keyword(kw
::Return
) {
1166 self.parse_return_expr(attrs
)
1167 } else if self.eat_keyword(kw
::Break
) {
1168 self.parse_break_expr(attrs
)
1169 } else if self.eat_keyword(kw
::Yield
) {
1170 self.parse_yield_expr(attrs
)
1171 } else if self.eat_keyword(kw
::Let
) {
1172 self.parse_let_expr(attrs
)
1173 } else if self.eat_keyword(kw
::Underscore
) {
1174 self.sess
.gated_spans
.gate(sym
::destructuring_assignment
, self.prev_token
.span
);
1175 Ok(self.mk_expr(self.prev_token
.span
, ExprKind
::Underscore
, attrs
))
1176 } else if !self.unclosed_delims
.is_empty() && self.check(&token
::Semi
) {
1177 // Don't complain about bare semicolons after unclosed braces
1178 // recovery in order to keep the error count down. Fixing the
1179 // delimiters will possibly also fix the bare semicolon found in
1180 // expression context. For example, silence the following error:
1182 // error: expected expression, found `;`
1186 // | ^ expected expression
1188 Ok(self.mk_expr_err(self.token
.span
))
1189 } else if self.token
.uninterpolated_span().rust_2018() {
1190 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1191 if self.check_keyword(kw
::Async
) {
1192 if self.is_async_block() {
1193 // Check for `async {` and `async move {`.
1194 self.parse_async_block(attrs
)
1196 self.parse_closure_expr(attrs
)
1198 } else if self.eat_keyword(kw
::Await
) {
1199 self.recover_incorrect_await_syntax(lo
, self.prev_token
.span
, attrs
)
1201 self.parse_lit_expr(attrs
)
1204 self.parse_lit_expr(attrs
)
1208 fn parse_lit_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1209 let lo
= self.token
.span
;
1210 match self.parse_opt_lit() {
1212 let expr
= self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::Lit(literal
), attrs
);
1213 self.maybe_recover_from_bad_qpath(expr
, true)
1215 None
=> self.try_macro_suggestion(),
1219 fn parse_tuple_parens_expr(&mut self, mut attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1220 let lo
= self.token
.span
;
1221 self.expect(&token
::OpenDelim(token
::Paren
))?
;
1222 attrs
.extend(self.parse_inner_attributes()?
); // `(#![foo] a, b, ...)` is OK.
1223 let (es
, trailing_comma
) = match self.parse_seq_to_end(
1224 &token
::CloseDelim(token
::Paren
),
1225 SeqSep
::trailing_allowed(token
::Comma
),
1226 |p
| p
.parse_expr_catch_underscore(),
1229 Err(err
) => return Ok(self.recover_seq_parse_error(token
::Paren
, lo
, Err(err
))),
1231 let kind
= if es
.len() == 1 && !trailing_comma
{
1232 // `(e)` is parenthesized `e`.
1233 ExprKind
::Paren(es
.into_iter().next().unwrap())
1235 // `(e,)` is a tuple with only one field, `e`.
1238 let expr
= self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
);
1239 self.maybe_recover_from_bad_qpath(expr
, true)
1242 fn parse_array_or_repeat_expr(&mut self, mut attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1243 let lo
= self.token
.span
;
1246 attrs
.extend(self.parse_inner_attributes()?
);
1248 let close
= &token
::CloseDelim(token
::Bracket
);
1249 let kind
= if self.eat(close
) {
1251 ExprKind
::Array(Vec
::new())
1254 let first_expr
= self.parse_expr()?
;
1255 if self.eat(&token
::Semi
) {
1256 // Repeating array syntax: `[ 0; 512 ]`
1257 let count
= self.parse_anon_const_expr()?
;
1258 self.expect(close
)?
;
1259 ExprKind
::Repeat(first_expr
, count
)
1260 } else if self.eat(&token
::Comma
) {
1261 // Vector with two or more elements.
1262 let sep
= SeqSep
::trailing_allowed(token
::Comma
);
1263 let (remaining_exprs
, _
) = self.parse_seq_to_end(close
, sep
, |p
| p
.parse_expr())?
;
1264 let mut exprs
= vec
![first_expr
];
1265 exprs
.extend(remaining_exprs
);
1266 ExprKind
::Array(exprs
)
1268 // Vector with one element
1269 self.expect(close
)?
;
1270 ExprKind
::Array(vec
![first_expr
])
1273 let expr
= self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
);
1274 self.maybe_recover_from_bad_qpath(expr
, true)
1277 fn parse_path_start_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1278 let path
= self.parse_path(PathStyle
::Expr
)?
;
1281 // `!`, as an operator, is prefix, so we know this isn't that.
1282 let (hi
, kind
) = if self.eat(&token
::Not
) {
1283 // MACRO INVOCATION expression
1286 args
: self.parse_mac_args()?
,
1287 prior_type_ascription
: self.last_type_ascription
,
1289 (self.prev_token
.span
, ExprKind
::MacCall(mac
))
1290 } else if self.check(&token
::OpenDelim(token
::Brace
)) {
1291 if let Some(expr
) = self.maybe_parse_struct_expr(&path
, &attrs
) {
1294 (path
.span
, ExprKind
::Path(None
, path
))
1297 (path
.span
, ExprKind
::Path(None
, path
))
1300 let expr
= self.mk_expr(lo
.to(hi
), kind
, attrs
);
1301 self.maybe_recover_from_bad_qpath(expr
, true)
1304 /// Parse `'label: $expr`. The label is already parsed.
1305 fn parse_labeled_expr(
1309 consume_colon
: bool
,
1310 ) -> PResult
<'a
, P
<Expr
>> {
1311 let lo
= label
.ident
.span
;
1312 let label
= Some(label
);
1313 let ate_colon
= self.eat(&token
::Colon
);
1314 let expr
= if self.eat_keyword(kw
::While
) {
1315 self.parse_while_expr(label
, lo
, attrs
)
1316 } else if self.eat_keyword(kw
::For
) {
1317 self.parse_for_expr(label
, lo
, attrs
)
1318 } else if self.eat_keyword(kw
::Loop
) {
1319 self.parse_loop_expr(label
, lo
, attrs
)
1320 } else if self.check(&token
::OpenDelim(token
::Brace
)) || self.token
.is_whole_block() {
1321 self.parse_block_expr(label
, lo
, BlockCheckMode
::Default
, attrs
)
1323 let msg
= "expected `while`, `for`, `loop` or `{` after a label";
1324 self.struct_span_err(self.token
.span
, msg
).span_label(self.token
.span
, msg
).emit();
1325 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1329 if !ate_colon
&& consume_colon
{
1330 self.error_labeled_expr_must_be_followed_by_colon(lo
, expr
.span
);
1336 fn error_labeled_expr_must_be_followed_by_colon(&self, lo
: Span
, span
: Span
) {
1337 self.struct_span_err(span
, "labeled expression must be followed by `:`")
1338 .span_label(lo
, "the label")
1339 .span_suggestion_short(
1341 "add `:` after the label",
1343 Applicability
::MachineApplicable
,
1345 .note("labels are used before loops and blocks, allowing e.g., `break 'label` to them")
1349 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1350 fn recover_do_catch(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1351 let lo
= self.token
.span
;
1353 self.bump(); // `do`
1354 self.bump(); // `catch`
1356 let span_dc
= lo
.to(self.prev_token
.span
);
1357 self.struct_span_err(span_dc
, "found removed `do catch` syntax")
1360 "replace with the new syntax",
1362 Applicability
::MachineApplicable
,
1364 .note("following RFC #2388, the new non-placeholder syntax is `try`")
1367 self.parse_try_block(lo
, attrs
)
1370 /// Parse an expression if the token can begin one.
1371 fn parse_expr_opt(&mut self) -> PResult
<'a
, Option
<P
<Expr
>>> {
1372 Ok(if self.token
.can_begin_expr() { Some(self.parse_expr()?) }
else { None }
)
1375 /// Parse `"return" expr?`.
1376 fn parse_return_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1377 let lo
= self.prev_token
.span
;
1378 let kind
= ExprKind
::Ret(self.parse_expr_opt()?
);
1379 let expr
= self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
);
1380 self.maybe_recover_from_bad_qpath(expr
, true)
1383 /// Parse `"('label ":")? break expr?`.
1384 fn parse_break_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1385 let lo
= self.prev_token
.span
;
1386 let label
= self.eat_label();
1387 let kind
= if self.token
!= token
::OpenDelim(token
::Brace
)
1388 || !self.restrictions
.contains(Restrictions
::NO_STRUCT_LITERAL
)
1390 self.parse_expr_opt()?
1394 let expr
= self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::Break(label
, kind
), attrs
);
1395 self.maybe_recover_from_bad_qpath(expr
, true)
1398 /// Parse `"yield" expr?`.
1399 fn parse_yield_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1400 let lo
= self.prev_token
.span
;
1401 let kind
= ExprKind
::Yield(self.parse_expr_opt()?
);
1402 let span
= lo
.to(self.prev_token
.span
);
1403 self.sess
.gated_spans
.gate(sym
::generators
, span
);
1404 let expr
= self.mk_expr(span
, kind
, attrs
);
1405 self.maybe_recover_from_bad_qpath(expr
, true)
1408 /// Returns a string literal if the next token is a string literal.
1409 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1410 /// and returns `None` if the next token is not literal at all.
1411 pub fn parse_str_lit(&mut self) -> Result
<ast
::StrLit
, Option
<Lit
>> {
1412 match self.parse_opt_lit() {
1413 Some(lit
) => match lit
.kind
{
1414 ast
::LitKind
::Str(symbol_unescaped
, style
) => Ok(ast
::StrLit
{
1416 symbol
: lit
.token
.symbol
,
1417 suffix
: lit
.token
.suffix
,
1421 _
=> Err(Some(lit
)),
1427 pub(super) fn parse_lit(&mut self) -> PResult
<'a
, Lit
> {
1428 self.parse_opt_lit().ok_or_else(|| {
1429 let msg
= format
!("unexpected token: {}", super::token_descr(&self.token
));
1430 self.struct_span_err(self.token
.span
, &msg
)
1434 /// Matches `lit = true | false | token_lit`.
1435 /// Returns `None` if the next token is not a literal.
1436 pub(super) fn parse_opt_lit(&mut self) -> Option
<Lit
> {
1437 let mut recovered
= None
;
1438 if self.token
== token
::Dot
{
1439 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1440 // dot would follow an optional literal, so we do this unconditionally.
1441 recovered
= self.look_ahead(1, |next_token
| {
1442 if let token
::Literal(token
::Lit { kind: token::Integer, symbol, suffix }
) =
1445 if self.token
.span
.hi() == next_token
.span
.lo() {
1446 let s
= String
::from("0.") + &symbol
.as_str();
1447 let kind
= TokenKind
::lit(token
::Float
, Symbol
::intern(&s
), suffix
);
1448 return Some(Token
::new(kind
, self.token
.span
.to(next_token
.span
)));
1453 if let Some(token
) = &recovered
{
1455 self.error_float_lits_must_have_int_part(&token
);
1459 let token
= recovered
.as_ref().unwrap_or(&self.token
);
1460 match Lit
::from_token(token
) {
1465 Err(LitError
::NotLiteral
) => None
,
1467 let span
= token
.span
;
1468 let lit
= match token
.kind
{
1469 token
::Literal(lit
) => lit
,
1470 _
=> unreachable
!(),
1473 self.report_lit_error(err
, lit
, span
);
1474 // Pack possible quotes and prefixes from the original literal into
1475 // the error literal's symbol so they can be pretty-printed faithfully.
1476 let suffixless_lit
= token
::Lit
::new(lit
.kind
, lit
.symbol
, None
);
1477 let symbol
= Symbol
::intern(&suffixless_lit
.to_string());
1478 let lit
= token
::Lit
::new(token
::Err
, symbol
, lit
.suffix
);
1479 Some(Lit
::from_lit_token(lit
, span
).unwrap_or_else(|_
| unreachable
!()))
1484 fn error_float_lits_must_have_int_part(&self, token
: &Token
) {
1485 self.struct_span_err(token
.span
, "float literals must have an integer part")
1488 "must have an integer part",
1489 pprust
::token_to_string(token
),
1490 Applicability
::MachineApplicable
,
1495 fn report_lit_error(&self, err
: LitError
, lit
: token
::Lit
, span
: Span
) {
1496 // Checks if `s` looks like i32 or u1234 etc.
1497 fn looks_like_width_suffix(first_chars
: &[char], s
: &str) -> bool
{
1498 s
.len() > 1 && s
.starts_with(first_chars
) && s
[1..].chars().all(|c
| c
.is_ascii_digit())
1501 let token
::Lit { kind, suffix, .. }
= lit
;
1503 // `NotLiteral` is not an error by itself, so we don't report
1504 // it and give the parser opportunity to try something else.
1505 LitError
::NotLiteral
=> {}
1506 // `LexerError` *is* an error, but it was already reported
1507 // by lexer, so here we don't report it the second time.
1508 LitError
::LexerError
=> {}
1509 LitError
::InvalidSuffix
=> {
1510 self.expect_no_suffix(
1512 &format
!("{} {} literal", kind
.article(), kind
.descr()),
1516 LitError
::InvalidIntSuffix
=> {
1517 let suf
= suffix
.expect("suffix error with no suffix").as_str();
1518 if looks_like_width_suffix(&['i'
, 'u'
], &suf
) {
1519 // If it looks like a width, try to be helpful.
1520 let msg
= format
!("invalid width `{}` for integer literal", &suf
[1..]);
1521 self.struct_span_err(span
, &msg
)
1522 .help("valid widths are 8, 16, 32, 64 and 128")
1525 let msg
= format
!("invalid suffix `{}` for number literal", suf
);
1526 self.struct_span_err(span
, &msg
)
1527 .span_label(span
, format
!("invalid suffix `{}`", suf
))
1528 .help("the suffix must be one of the numeric types (`u32`, `isize`, `f32`, etc.)")
1532 LitError
::InvalidFloatSuffix
=> {
1533 let suf
= suffix
.expect("suffix error with no suffix").as_str();
1534 if looks_like_width_suffix(&['f'
], &suf
) {
1535 // If it looks like a width, try to be helpful.
1536 let msg
= format
!("invalid width `{}` for float literal", &suf
[1..]);
1537 self.struct_span_err(span
, &msg
).help("valid widths are 32 and 64").emit();
1539 let msg
= format
!("invalid suffix `{}` for float literal", suf
);
1540 self.struct_span_err(span
, &msg
)
1541 .span_label(span
, format
!("invalid suffix `{}`", suf
))
1542 .help("valid suffixes are `f32` and `f64`")
1546 LitError
::NonDecimalFloat(base
) => {
1547 let descr
= match base
{
1548 16 => "hexadecimal",
1551 _
=> unreachable
!(),
1553 self.struct_span_err(span
, &format
!("{} float literal is not supported", descr
))
1554 .span_label(span
, "not supported")
1557 LitError
::IntTooLarge
=> {
1558 self.struct_span_err(span
, "integer literal is too large").emit();
1563 pub(super) fn expect_no_suffix(&self, sp
: Span
, kind
: &str, suffix
: Option
<Symbol
>) {
1564 if let Some(suf
) = suffix
{
1565 let mut err
= if kind
== "a tuple index"
1566 && [sym
::i32, sym
::u32, sym
::isize, sym
::usize].contains(&suf
)
1568 // #59553: warn instead of reject out of hand to allow the fix to percolate
1569 // through the ecosystem when people fix their macros
1573 .struct_span_warn(sp
, &format
!("suffixes on {} are invalid", kind
));
1575 "`{}` is *temporarily* accepted on tuple index fields as it was \
1576 incorrectly accepted on stable for a few releases",
1580 "on proc macros, you'll want to use `syn::Index::from` or \
1581 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1582 to tuple field access",
1585 "see issue #60210 <https://github.com/rust-lang/rust/issues/60210> \
1586 for more information",
1590 self.struct_span_err(sp
, &format
!("suffixes on {} are invalid", kind
))
1592 err
.span_label(sp
, format
!("invalid suffix `{}`", suf
));
1597 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1598 /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
1599 pub fn parse_literal_maybe_minus(&mut self) -> PResult
<'a
, P
<Expr
>> {
1600 maybe_whole_expr
!(self);
1602 let lo
= self.token
.span
;
1603 let minus_present
= self.eat(&token
::BinOp(token
::Minus
));
1604 let lit
= self.parse_lit()?
;
1605 let expr
= self.mk_expr(lit
.span
, ExprKind
::Lit(lit
), AttrVec
::new());
1609 lo
.to(self.prev_token
.span
),
1610 self.mk_unary(UnOp
::Neg
, expr
),
1618 /// Parses a block or unsafe block.
1619 pub(super) fn parse_block_expr(
1621 opt_label
: Option
<Label
>,
1623 blk_mode
: BlockCheckMode
,
1625 ) -> PResult
<'a
, P
<Expr
>> {
1626 if let Some(label
) = opt_label
{
1627 self.sess
.gated_spans
.gate(sym
::label_break_value
, label
.ident
.span
);
1630 if self.token
.is_whole_block() {
1631 self.struct_span_err(self.token
.span
, "cannot use a `block` macro fragment here")
1632 .span_label(lo
.to(self.token
.span
), "the `block` fragment is within this context")
1636 let (inner_attrs
, blk
) = self.parse_block_common(lo
, blk_mode
)?
;
1637 attrs
.extend(inner_attrs
);
1638 Ok(self.mk_expr(blk
.span
, ExprKind
::Block(blk
, opt_label
), attrs
))
1641 /// Recover on an explicitly quantified closure expression, e.g., `for<'a> |x: &'a u8| *x + 1`.
1642 fn recover_quantified_closure_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1643 let lo
= self.token
.span
;
1644 let _
= self.parse_late_bound_lifetime_defs()?
;
1645 let span_for
= lo
.to(self.prev_token
.span
);
1646 let closure
= self.parse_closure_expr(attrs
)?
;
1648 self.struct_span_err(span_for
, "cannot introduce explicit parameters for a closure")
1649 .span_label(closure
.span
, "the parameters are attached to this closure")
1652 "remove the parameters",
1654 Applicability
::MachineApplicable
,
1658 Ok(self.mk_expr_err(lo
.to(closure
.span
)))
1661 /// Parses a closure expression (e.g., `move |args| expr`).
1662 fn parse_closure_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1663 let lo
= self.token
.span
;
1666 if self.eat_keyword(kw
::Static
) { Movability::Static }
else { Movability::Movable }
;
1668 let asyncness
= if self.token
.uninterpolated_span().rust_2018() {
1669 self.parse_asyncness()
1674 let capture_clause
= self.parse_capture_clause()?
;
1675 let decl
= self.parse_fn_block_decl()?
;
1676 let decl_hi
= self.prev_token
.span
;
1677 let body
= match decl
.output
{
1678 FnRetTy
::Default(_
) => {
1679 let restrictions
= self.restrictions
- Restrictions
::STMT_EXPR
;
1680 self.parse_expr_res(restrictions
, None
)?
1683 // If an explicit return type is given, require a block to appear (RFC 968).
1684 let body_lo
= self.token
.span
;
1685 self.parse_block_expr(None
, body_lo
, BlockCheckMode
::Default
, AttrVec
::new())?
1689 if let Async
::Yes { span, .. }
= asyncness
{
1690 // Feature-gate `async ||` closures.
1691 self.sess
.gated_spans
.gate(sym
::async_closure
, span
);
1696 ExprKind
::Closure(capture_clause
, asyncness
, movability
, decl
, body
, lo
.to(decl_hi
)),
1701 /// Parses an optional `move` prefix to a closure-like construct.
1702 fn parse_capture_clause(&mut self) -> PResult
<'a
, CaptureBy
> {
1703 if self.eat_keyword(kw
::Move
) {
1704 // Check for `move async` and recover
1705 if self.check_keyword(kw
::Async
) {
1706 let move_async_span
= self.token
.span
.with_lo(self.prev_token
.span
.data().lo
);
1707 Err(self.incorrect_move_async_order_found(move_async_span
))
1709 Ok(CaptureBy
::Value
)
1716 /// Parses the `|arg, arg|` header of a closure.
1717 fn parse_fn_block_decl(&mut self) -> PResult
<'a
, P
<FnDecl
>> {
1718 let inputs
= if self.eat(&token
::OrOr
) {
1721 self.expect(&token
::BinOp(token
::Or
))?
;
1723 .parse_seq_to_before_tokens(
1724 &[&token
::BinOp(token
::Or
), &token
::OrOr
],
1725 SeqSep
::trailing_allowed(token
::Comma
),
1726 TokenExpectType
::NoExpect
,
1727 |p
| p
.parse_fn_block_param(),
1734 self.parse_ret_ty(AllowPlus
::Yes
, RecoverQPath
::Yes
, RecoverReturnSign
::Yes
)?
;
1736 Ok(P(FnDecl { inputs, output }
))
1739 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1740 fn parse_fn_block_param(&mut self) -> PResult
<'a
, Param
> {
1741 let lo
= self.token
.span
;
1742 let attrs
= self.parse_outer_attributes()?
;
1743 self.collect_tokens_trailing_token(attrs
, ForceCollect
::No
, |this
, attrs
| {
1744 let pat
= this
.parse_pat_no_top_alt(PARAM_EXPECTED
)?
;
1745 let ty
= if this
.eat(&token
::Colon
) {
1748 this
.mk_ty(this
.prev_token
.span
, TyKind
::Infer
)
1753 attrs
: attrs
.into(),
1756 span
: lo
.to(this
.token
.span
),
1758 is_placeholder
: false,
1760 TrailingToken
::MaybeComma
,
1765 /// Parses an `if` expression (`if` token already eaten).
1766 fn parse_if_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1767 let lo
= self.prev_token
.span
;
1768 let cond
= self.parse_cond_expr()?
;
1770 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1771 // verify that the last statement is either an implicit return (no `;`) or an explicit
1772 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1773 // the dead code lint.
1774 let thn
= if self.eat_keyword(kw
::Else
) || !cond
.returns() {
1775 self.error_missing_if_cond(lo
, cond
.span
)
1777 let attrs
= self.parse_outer_attributes()?
.take_for_recovery(); // For recovery.
1778 let not_block
= self.token
!= token
::OpenDelim(token
::Brace
);
1779 let block
= self.parse_block().map_err(|mut err
| {
1781 err
.span_label(lo
, "this `if` expression has a condition, but no block");
1782 if let ExprKind
::Binary(_
, _
, ref right
) = cond
.kind
{
1783 if let ExprKind
::Block(_
, _
) = right
.kind
{
1784 err
.help("maybe you forgot the right operand of the condition?");
1790 self.error_on_if_block_attrs(lo
, false, block
.span
, &attrs
);
1793 let els
= if self.eat_keyword(kw
::Else
) { Some(self.parse_else_expr()?) }
else { None }
;
1794 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::If(cond
, thn
, els
), attrs
))
1797 fn error_missing_if_cond(&self, lo
: Span
, span
: Span
) -> P
<ast
::Block
> {
1798 let sp
= self.sess
.source_map().next_point(lo
);
1799 self.struct_span_err(sp
, "missing condition for `if` expression")
1800 .span_label(sp
, "expected if condition here")
1802 self.mk_block_err(span
)
1805 /// Parses the condition of a `if` or `while` expression.
1806 fn parse_cond_expr(&mut self) -> PResult
<'a
, P
<Expr
>> {
1807 let cond
= self.parse_expr_res(Restrictions
::NO_STRUCT_LITERAL
, None
)?
;
1809 if let ExprKind
::Let(..) = cond
.kind
{
1810 // Remove the last feature gating of a `let` expression since it's stable.
1811 self.sess
.gated_spans
.ungate_last(sym
::let_chains
, cond
.span
);
1817 /// Parses a `let $pat = $expr` pseudo-expression.
1818 /// The `let` token has already been eaten.
1819 fn parse_let_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1820 let lo
= self.prev_token
.span
;
1821 let pat
= self.parse_pat_allow_top_alt(None
, RecoverComma
::Yes
)?
;
1822 self.expect(&token
::Eq
)?
;
1823 let expr
= self.with_res(self.restrictions
| Restrictions
::NO_STRUCT_LITERAL
, |this
| {
1824 this
.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None
.into())
1826 let span
= lo
.to(expr
.span
);
1827 self.sess
.gated_spans
.gate(sym
::let_chains
, span
);
1828 Ok(self.mk_expr(span
, ExprKind
::Let(pat
, expr
), attrs
))
1831 /// Parses an `else { ... }` expression (`else` token already eaten).
1832 fn parse_else_expr(&mut self) -> PResult
<'a
, P
<Expr
>> {
1833 let ctx_span
= self.prev_token
.span
; // `else`
1834 let attrs
= self.parse_outer_attributes()?
.take_for_recovery(); // For recovery.
1835 let expr
= if self.eat_keyword(kw
::If
) {
1836 self.parse_if_expr(AttrVec
::new())?
1838 let blk
= self.parse_block()?
;
1839 self.mk_expr(blk
.span
, ExprKind
::Block(blk
, None
), AttrVec
::new())
1841 self.error_on_if_block_attrs(ctx_span
, true, expr
.span
, &attrs
);
1845 fn error_on_if_block_attrs(
1850 attrs
: &[ast
::Attribute
],
1852 let (span
, last
) = match attrs
{
1854 [x0 @ xn
] | [x0
, .., xn
] => (x0
.span
.to(xn
.span
), xn
.span
),
1856 let ctx
= if is_ctx_else { "else" }
else { "if" }
;
1857 self.struct_span_err(last
, "outer attributes are not allowed on `if` and `else` branches")
1858 .span_label(branch_span
, "the attributes are attached to this branch")
1859 .span_label(ctx_span
, format
!("the branch belongs to this `{}`", ctx
))
1862 "remove the attributes",
1864 Applicability
::MachineApplicable
,
1869 /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
1872 opt_label
: Option
<Label
>,
1875 ) -> PResult
<'a
, P
<Expr
>> {
1876 // Record whether we are about to parse `for (`.
1877 // This is used below for recovery in case of `for ( $stuff ) $block`
1878 // in which case we will suggest `for $stuff $block`.
1879 let begin_paren
= match self.token
.kind
{
1880 token
::OpenDelim(token
::Paren
) => Some(self.token
.span
),
1884 let pat
= self.parse_pat_allow_top_alt(None
, RecoverComma
::Yes
)?
;
1885 if !self.eat_keyword(kw
::In
) {
1886 self.error_missing_in_for_loop();
1888 self.check_for_for_in_in_typo(self.prev_token
.span
);
1889 let expr
= self.parse_expr_res(Restrictions
::NO_STRUCT_LITERAL
, None
)?
;
1891 let pat
= self.recover_parens_around_for_head(pat
, &expr
, begin_paren
);
1893 let (iattrs
, loop_block
) = self.parse_inner_attrs_and_block()?
;
1894 attrs
.extend(iattrs
);
1896 let kind
= ExprKind
::ForLoop(pat
, expr
, loop_block
, opt_label
);
1897 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
))
1900 fn error_missing_in_for_loop(&mut self) {
1901 let (span
, msg
, sugg
) = if self.token
.is_ident_named(sym
::of
) {
1902 // Possibly using JS syntax (#75311).
1903 let span
= self.token
.span
;
1905 (span
, "try using `in` here instead", "in")
1907 (self.prev_token
.span
.between(self.token
.span
), "try adding `in` here", " in ")
1909 self.struct_span_err(span
, "missing `in` in `for` loop")
1910 .span_suggestion_short(
1914 // Has been misleading, at least in the past (closed Issue #48492).
1915 Applicability
::MaybeIncorrect
,
1920 /// Parses a `while` or `while let` expression (`while` token already eaten).
1921 fn parse_while_expr(
1923 opt_label
: Option
<Label
>,
1926 ) -> PResult
<'a
, P
<Expr
>> {
1927 let cond
= self.parse_cond_expr()?
;
1928 let (iattrs
, body
) = self.parse_inner_attrs_and_block()?
;
1929 attrs
.extend(iattrs
);
1930 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::While(cond
, body
, opt_label
), attrs
))
1933 /// Parses `loop { ... }` (`loop` token already eaten).
1936 opt_label
: Option
<Label
>,
1939 ) -> PResult
<'a
, P
<Expr
>> {
1940 let (iattrs
, body
) = self.parse_inner_attrs_and_block()?
;
1941 attrs
.extend(iattrs
);
1942 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::Loop(body
, opt_label
), attrs
))
1945 fn eat_label(&mut self) -> Option
<Label
> {
1946 self.token
.lifetime().map(|ident
| {
1952 /// Parses a `match ... { ... }` expression (`match` token already eaten).
1953 fn parse_match_expr(&mut self, mut attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1954 let match_span
= self.prev_token
.span
;
1955 let lo
= self.prev_token
.span
;
1956 let scrutinee
= self.parse_expr_res(Restrictions
::NO_STRUCT_LITERAL
, None
)?
;
1957 if let Err(mut e
) = self.expect(&token
::OpenDelim(token
::Brace
)) {
1958 if self.token
== token
::Semi
{
1959 e
.span_suggestion_short(
1961 "try removing this `match`",
1963 Applicability
::MaybeIncorrect
, // speculative
1968 attrs
.extend(self.parse_inner_attributes()?
);
1970 let mut arms
: Vec
<Arm
> = Vec
::new();
1971 while self.token
!= token
::CloseDelim(token
::Brace
) {
1972 match self.parse_arm() {
1973 Ok(arm
) => arms
.push(arm
),
1975 // Recover by skipping to the end of the block.
1977 self.recover_stmt();
1978 let span
= lo
.to(self.token
.span
);
1979 if self.token
== token
::CloseDelim(token
::Brace
) {
1982 return Ok(self.mk_expr(span
, ExprKind
::Match(scrutinee
, arms
), attrs
));
1986 let hi
= self.token
.span
;
1988 Ok(self.mk_expr(lo
.to(hi
), ExprKind
::Match(scrutinee
, arms
), attrs
))
1991 /// Attempt to recover from match arm body with statements and no surrounding braces.
1992 fn parse_arm_body_missing_braces(
1994 first_expr
: &P
<Expr
>,
1996 ) -> Option
<P
<Expr
>> {
1997 if self.token
.kind
!= token
::Semi
{
2000 let start_snapshot
= self.clone();
2001 let semi_sp
= self.token
.span
;
2004 vec
![self.mk_stmt(first_expr
.span
, ast
::StmtKind
::Expr(first_expr
.clone()))];
2005 let err
= |this
: &mut Parser
<'_
>, stmts
: Vec
<ast
::Stmt
>| {
2006 let span
= stmts
[0].span
.to(stmts
[stmts
.len() - 1].span
);
2007 let mut err
= this
.struct_span_err(span
, "`match` arm body without braces");
2008 let (these
, s
, are
) =
2009 if stmts
.len() > 1 { ("these", "s", "are") }
else { ("this", "", "is") }
;
2013 "{these} statement{s} {are} not surrounded by a body",
2019 err
.span_label(arrow_span
, "while parsing the `match` arm starting here");
2020 if stmts
.len() > 1 {
2021 err
.multipart_suggestion(
2022 &format
!("surround the statement{} with a body", s
),
2024 (span
.shrink_to_lo(), "{ ".to_string()),
2025 (span
.shrink_to_hi(), " }".to_string()),
2027 Applicability
::MachineApplicable
,
2030 err
.span_suggestion(
2032 "use a comma to end a `match` arm expression",
2034 Applicability
::MachineApplicable
,
2038 this
.mk_expr_err(span
)
2040 // We might have either a `,` -> `;` typo, or a block without braces. We need
2041 // a more subtle parsing strategy.
2043 if self.token
.kind
== token
::CloseDelim(token
::Brace
) {
2044 // We have reached the closing brace of the `match` expression.
2045 return Some(err(self, stmts
));
2047 if self.token
.kind
== token
::Comma
{
2048 *self = start_snapshot
;
2051 let pre_pat_snapshot
= self.clone();
2052 match self.parse_pat_no_top_alt(None
) {
2054 if self.token
.kind
== token
::FatArrow
{
2056 *self = pre_pat_snapshot
;
2057 return Some(err(self, stmts
));
2065 *self = pre_pat_snapshot
;
2066 match self.parse_stmt_without_recovery(true, ForceCollect
::No
) {
2067 // Consume statements for as long as possible.
2072 *self = start_snapshot
;
2075 // We couldn't parse either yet another statement missing it's
2076 // enclosing block nor the next arm's pattern or closing brace.
2077 Err(mut stmt_err
) => {
2079 *self = start_snapshot
;
2087 pub(super) fn parse_arm(&mut self) -> PResult
<'a
, Arm
> {
2088 let attrs
= self.parse_outer_attributes()?
;
2089 self.collect_tokens_trailing_token(attrs
, ForceCollect
::No
, |this
, attrs
| {
2090 let lo
= this
.token
.span
;
2091 let pat
= this
.parse_pat_allow_top_alt(None
, RecoverComma
::Yes
)?
;
2092 let guard
= if this
.eat_keyword(kw
::If
) {
2093 let if_span
= this
.prev_token
.span
;
2094 let cond
= this
.parse_expr()?
;
2095 if let ExprKind
::Let(..) = cond
.kind
{
2096 // Remove the last feature gating of a `let` expression since it's stable.
2097 this
.sess
.gated_spans
.ungate_last(sym
::let_chains
, cond
.span
);
2098 let span
= if_span
.to(cond
.span
);
2099 this
.sess
.gated_spans
.gate(sym
::if_let_guard
, span
);
2105 let arrow_span
= this
.token
.span
;
2106 this
.expect(&token
::FatArrow
)?
;
2107 let arm_start_span
= this
.token
.span
;
2109 let expr
= this
.parse_expr_res(Restrictions
::STMT_EXPR
, None
).map_err(|mut err
| {
2110 err
.span_label(arrow_span
, "while parsing the `match` arm starting here");
2114 let require_comma
= classify
::expr_requires_semi_to_be_stmt(&expr
)
2115 && this
.token
!= token
::CloseDelim(token
::Brace
);
2117 let hi
= this
.prev_token
.span
;
2120 let sm
= this
.sess
.source_map();
2121 if let Some(body
) = this
.parse_arm_body_missing_braces(&expr
, arrow_span
) {
2122 let span
= body
.span
;
2131 is_placeholder
: false,
2133 TrailingToken
::None
,
2136 this
.expect_one_of(&[token
::Comma
], &[token
::CloseDelim(token
::Brace
)]).map_err(
2138 match (sm
.span_to_lines(expr
.span
), sm
.span_to_lines(arm_start_span
)) {
2139 (Ok(ref expr_lines
), Ok(ref arm_start_lines
))
2140 if arm_start_lines
.lines
[0].end_col
2141 == expr_lines
.lines
[0].end_col
2142 && expr_lines
.lines
.len() == 2
2143 && this
.token
== token
::FatArrow
=>
2145 // We check whether there's any trailing code in the parse span,
2146 // if there isn't, we very likely have the following:
2149 // | -- - missing comma
2153 // | - ^^ self.token.span
2155 // | parsed until here as `"y" & X`
2156 err
.span_suggestion_short(
2157 arm_start_span
.shrink_to_hi(),
2158 "missing a comma here to end this `match` arm",
2160 Applicability
::MachineApplicable
,
2166 "while parsing the `match` arm starting here",
2174 this
.eat(&token
::Comma
);
2185 is_placeholder
: false,
2187 TrailingToken
::None
,
2192 /// Parses a `try {...}` expression (`try` token already eaten).
2193 fn parse_try_block(&mut self, span_lo
: Span
, mut attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
2194 let (iattrs
, body
) = self.parse_inner_attrs_and_block()?
;
2195 attrs
.extend(iattrs
);
2196 if self.eat_keyword(kw
::Catch
) {
2197 let mut error
= self.struct_span_err(
2198 self.prev_token
.span
,
2199 "keyword `catch` cannot follow a `try` block",
2201 error
.help("try using `match` on the result of the `try` block instead");
2205 let span
= span_lo
.to(body
.span
);
2206 self.sess
.gated_spans
.gate(sym
::try_blocks
, span
);
2207 Ok(self.mk_expr(span
, ExprKind
::TryBlock(body
), attrs
))
2211 fn is_do_catch_block(&self) -> bool
{
2212 self.token
.is_keyword(kw
::Do
)
2213 && self.is_keyword_ahead(1, &[kw
::Catch
])
2214 && self.look_ahead(2, |t
| *t
== token
::OpenDelim(token
::Brace
))
2215 && !self.restrictions
.contains(Restrictions
::NO_STRUCT_LITERAL
)
2218 fn is_try_block(&self) -> bool
{
2219 self.token
.is_keyword(kw
::Try
)
2220 && self.look_ahead(1, |t
| *t
== token
::OpenDelim(token
::Brace
))
2221 && self.token
.uninterpolated_span().rust_2018()
2224 /// Parses an `async move? {...}` expression.
2225 fn parse_async_block(&mut self, mut attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
2226 let lo
= self.token
.span
;
2227 self.expect_keyword(kw
::Async
)?
;
2228 let capture_clause
= self.parse_capture_clause()?
;
2229 let (iattrs
, body
) = self.parse_inner_attrs_and_block()?
;
2230 attrs
.extend(iattrs
);
2231 let kind
= ExprKind
::Async(capture_clause
, DUMMY_NODE_ID
, body
);
2232 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
))
2235 fn is_async_block(&self) -> bool
{
2236 self.token
.is_keyword(kw
::Async
)
2239 self.is_keyword_ahead(1, &[kw
::Move
])
2240 && self.look_ahead(2, |t
| *t
== token
::OpenDelim(token
::Brace
))
2243 self.look_ahead(1, |t
| *t
== token
::OpenDelim(token
::Brace
))
2247 fn is_certainly_not_a_block(&self) -> bool
{
2248 self.look_ahead(1, |t
| t
.is_ident())
2250 // `{ ident, ` cannot start a block.
2251 self.look_ahead(2, |t
| t
== &token
::Comma
)
2252 || self.look_ahead(2, |t
| t
== &token
::Colon
)
2254 // `{ ident: token, ` cannot start a block.
2255 self.look_ahead(4, |t
| t
== &token
::Comma
) ||
2256 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
2257 self.look_ahead(3, |t
| !t
.can_begin_type())
2262 fn maybe_parse_struct_expr(
2266 ) -> Option
<PResult
<'a
, P
<Expr
>>> {
2267 let struct_allowed
= !self.restrictions
.contains(Restrictions
::NO_STRUCT_LITERAL
);
2268 if struct_allowed
|| self.is_certainly_not_a_block() {
2269 if let Err(err
) = self.expect(&token
::OpenDelim(token
::Brace
)) {
2270 return Some(Err(err
));
2272 let expr
= self.parse_struct_expr(path
.clone(), attrs
.clone(), true);
2273 if let (Ok(expr
), false) = (&expr
, struct_allowed
) {
2274 // This is a struct literal, but we don't can't accept them here.
2275 self.error_struct_lit_not_allowed_here(path
.span
, expr
.span
);
2282 fn error_struct_lit_not_allowed_here(&self, lo
: Span
, sp
: Span
) {
2283 self.struct_span_err(sp
, "struct literals are not allowed here")
2284 .multipart_suggestion(
2285 "surround the struct literal with parentheses",
2286 vec
![(lo
.shrink_to_lo(), "(".to_string()), (sp
.shrink_to_hi(), ")".to_string())],
2287 Applicability
::MachineApplicable
,
2292 /// Precondition: already parsed the '{'.
2293 pub(super) fn parse_struct_expr(
2298 ) -> PResult
<'a
, P
<Expr
>> {
2299 let mut fields
= Vec
::new();
2300 let mut base
= ast
::StructRest
::None
;
2301 let mut recover_async
= false;
2303 attrs
.extend(self.parse_inner_attributes()?
);
2305 let mut async_block_err
= |e
: &mut DiagnosticBuilder
<'_
>, span
: Span
| {
2306 recover_async
= true;
2307 e
.span_label(span
, "`async` blocks are only allowed in Rust 2018 or later");
2308 e
.help(&format
!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION
));
2309 e
.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
2312 while self.token
!= token
::CloseDelim(token
::Brace
) {
2313 if self.eat(&token
::DotDot
) {
2314 let exp_span
= self.prev_token
.span
;
2315 // We permit `.. }` on the left-hand side of a destructuring assignment.
2316 if self.check(&token
::CloseDelim(token
::Brace
)) {
2317 self.sess
.gated_spans
.gate(sym
::destructuring_assignment
, self.prev_token
.span
);
2318 base
= ast
::StructRest
::Rest(self.prev_token
.span
.shrink_to_hi());
2321 match self.parse_expr() {
2322 Ok(e
) => base
= ast
::StructRest
::Base(e
),
2323 Err(mut e
) if recover
=> {
2325 self.recover_stmt();
2327 Err(e
) => return Err(e
),
2329 self.recover_struct_comma_after_dotdot(exp_span
);
2333 let recovery_field
= self.find_struct_error_after_field_looking_code();
2334 let parsed_field
= match self.parse_expr_field() {
2337 if pth
== kw
::Async
{
2338 async_block_err(&mut e
, pth
.span
);
2340 e
.span_label(pth
.span
, "while parsing this struct");
2344 // If the next token is a comma, then try to parse
2345 // what comes next as additional fields, rather than
2346 // bailing out until next `}`.
2347 if self.token
!= token
::Comma
{
2348 self.recover_stmt_(SemiColonMode
::Comma
, BlockMode
::Ignore
);
2349 if self.token
!= token
::Comma
{
2357 match self.expect_one_of(&[token
::Comma
], &[token
::CloseDelim(token
::Brace
)]) {
2359 if let Some(f
) = parsed_field
.or(recovery_field
) {
2360 // Only include the field if there's no parse error for the field name.
2365 if pth
== kw
::Async
{
2366 async_block_err(&mut e
, pth
.span
);
2368 e
.span_label(pth
.span
, "while parsing this struct");
2369 if let Some(f
) = recovery_field
{
2372 self.prev_token
.span
.shrink_to_hi(),
2373 "try adding a comma",
2375 Applicability
::MachineApplicable
,
2383 self.recover_stmt_(SemiColonMode
::Comma
, BlockMode
::Ignore
);
2384 self.eat(&token
::Comma
);
2389 let span
= pth
.span
.to(self.token
.span
);
2390 self.expect(&token
::CloseDelim(token
::Brace
))?
;
2391 let expr
= if recover_async
{
2394 ExprKind
::Struct(P(ast
::StructExpr { path: pth, fields, rest: base }
))
2396 Ok(self.mk_expr(span
, expr
, attrs
))
2399 /// Use in case of error after field-looking code: `S { foo: () with a }`.
2400 fn find_struct_error_after_field_looking_code(&self) -> Option
<ExprField
> {
2401 match self.token
.ident() {
2402 Some((ident
, is_raw
))
2403 if (is_raw
|| !ident
.is_reserved())
2404 && self.look_ahead(1, |t
| *t
== token
::Colon
) =>
2406 Some(ast
::ExprField
{
2408 span
: self.token
.span
,
2409 expr
: self.mk_expr_err(self.token
.span
),
2410 is_shorthand
: false,
2411 attrs
: AttrVec
::new(),
2413 is_placeholder
: false,
2420 fn recover_struct_comma_after_dotdot(&mut self, span
: Span
) {
2421 if self.token
!= token
::Comma
{
2424 self.struct_span_err(
2425 span
.to(self.prev_token
.span
),
2426 "cannot use a comma after the base struct",
2428 .span_suggestion_short(
2430 "remove this comma",
2432 Applicability
::MachineApplicable
,
2434 .note("the base struct must always be the last field")
2436 self.recover_stmt();
2439 /// Parses `ident (COLON expr)?`.
2440 fn parse_expr_field(&mut self) -> PResult
<'a
, ExprField
> {
2441 let attrs
= self.parse_outer_attributes()?
;
2442 self.collect_tokens_trailing_token(attrs
, ForceCollect
::No
, |this
, attrs
| {
2443 let lo
= this
.token
.span
;
2445 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2446 let is_shorthand
= !this
.look_ahead(1, |t
| t
== &token
::Colon
|| t
== &token
::Eq
);
2447 let (ident
, expr
) = if is_shorthand
{
2448 // Mimic `x: x` for the `x` field shorthand.
2449 let ident
= this
.parse_ident_common(false)?
;
2450 let path
= ast
::Path
::from_ident(ident
);
2451 (ident
, this
.mk_expr(ident
.span
, ExprKind
::Path(None
, path
), AttrVec
::new()))
2453 let ident
= this
.parse_field_name()?
;
2454 this
.error_on_eq_field_init(ident
);
2456 (ident
, this
.parse_expr()?
)
2462 span
: lo
.to(expr
.span
),
2465 attrs
: attrs
.into(),
2467 is_placeholder
: false,
2469 TrailingToken
::MaybeComma
,
2474 /// Check for `=`. This means the source incorrectly attempts to
2475 /// initialize a field with an eq rather than a colon.
2476 fn error_on_eq_field_init(&self, field_name
: Ident
) {
2477 if self.token
!= token
::Eq
{
2481 self.struct_span_err(self.token
.span
, "expected `:`, found `=`")
2483 field_name
.span
.shrink_to_hi().to(self.token
.span
),
2484 "replace equals symbol with a colon",
2486 Applicability
::MachineApplicable
,
2491 fn err_dotdotdot_syntax(&self, span
: Span
) {
2492 self.struct_span_err(span
, "unexpected token: `...`")
2495 "use `..` for an exclusive range",
2497 Applicability
::MaybeIncorrect
,
2501 "or `..=` for an inclusive range",
2503 Applicability
::MaybeIncorrect
,
2508 fn err_larrow_operator(&self, span
: Span
) {
2509 self.struct_span_err(span
, "unexpected token: `<-`")
2512 "if you meant to write a comparison against a negative value, add a \
2513 space in between `<` and `-`",
2515 Applicability
::MaybeIncorrect
,
2520 fn mk_assign_op(&self, binop
: BinOp
, lhs
: P
<Expr
>, rhs
: P
<Expr
>) -> ExprKind
{
2521 ExprKind
::AssignOp(binop
, lhs
, rhs
)
2526 start
: Option
<P
<Expr
>>,
2527 end
: Option
<P
<Expr
>>,
2528 limits
: RangeLimits
,
2530 if end
.is_none() && limits
== RangeLimits
::Closed
{
2531 self.error_inclusive_range_with_no_end(self.prev_token
.span
);
2534 ExprKind
::Range(start
, end
, limits
)
2538 fn mk_unary(&self, unop
: UnOp
, expr
: P
<Expr
>) -> ExprKind
{
2539 ExprKind
::Unary(unop
, expr
)
2542 fn mk_binary(&self, binop
: BinOp
, lhs
: P
<Expr
>, rhs
: P
<Expr
>) -> ExprKind
{
2543 ExprKind
::Binary(binop
, lhs
, rhs
)
2546 fn mk_index(&self, expr
: P
<Expr
>, idx
: P
<Expr
>) -> ExprKind
{
2547 ExprKind
::Index(expr
, idx
)
2550 fn mk_call(&self, f
: P
<Expr
>, args
: Vec
<P
<Expr
>>) -> ExprKind
{
2551 ExprKind
::Call(f
, args
)
2554 fn mk_await_expr(&mut self, self_arg
: P
<Expr
>, lo
: Span
) -> P
<Expr
> {
2555 let span
= lo
.to(self.prev_token
.span
);
2556 let await_expr
= self.mk_expr(span
, ExprKind
::Await(self_arg
), AttrVec
::new());
2557 self.recover_from_await_method_call();
2561 crate fn mk_expr(&self, span
: Span
, kind
: ExprKind
, attrs
: AttrVec
) -> P
<Expr
> {
2562 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None }
)
2565 pub(super) fn mk_expr_err(&self, span
: Span
) -> P
<Expr
> {
2566 self.mk_expr(span
, ExprKind
::Err
, AttrVec
::new())
2569 /// Create expression span ensuring the span of the parent node
2570 /// is larger than the span of lhs and rhs, including the attributes.
2571 fn mk_expr_sp(&self, lhs
: &P
<Expr
>, lhs_span
: Span
, rhs_span
: Span
) -> Span
{
2574 .find(|a
| a
.style
== AttrStyle
::Outer
)
2575 .map_or(lhs_span
, |a
| a
.span
)
2579 fn collect_tokens_for_expr(
2582 f
: impl FnOnce(&mut Self, Vec
<ast
::Attribute
>) -> PResult
<'a
, P
<Expr
>>,
2583 ) -> PResult
<'a
, P
<Expr
>> {
2584 self.collect_tokens_trailing_token(attrs
, ForceCollect
::No
, |this
, attrs
| {
2585 let res
= f(this
, attrs
)?
;
2586 let trailing
= if this
.restrictions
.contains(Restrictions
::STMT_EXPR
)
2587 && this
.token
.kind
== token
::Semi
2591 // FIXME - pass this through from the place where we know
2592 // we need a comma, rather than assuming that `#[attr] expr,`
2593 // always captures a trailing comma
2594 TrailingToken
::MaybeComma