1 use super::pat
::{GateOr, PARAM_EXPECTED}
;
2 use super::ty
::{AllowPlus, RecoverQPath}
;
3 use super::{BlockMode, Parser, PathStyle, Restrictions, TokenType}
;
4 use super::{SemiColonMode, SeqSep, TokenExpectType}
;
5 use crate::maybe_recover_from_interpolated_ty_qpath
;
8 use rustc_ast
::token
::{self, Token, TokenKind}
;
9 use rustc_ast
::util
::classify
;
10 use rustc_ast
::util
::literal
::LitError
;
11 use rustc_ast
::util
::parser
::{prec_let_scrutinee_needs_par, AssocOp, Fixity}
;
12 use rustc_ast
::{self as ast, AttrStyle, AttrVec, CaptureBy, Field, Lit, UnOp, DUMMY_NODE_ID}
;
13 use rustc_ast
::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty, TyKind}
;
14 use rustc_ast
::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits}
;
15 use rustc_ast_pretty
::pprust
;
16 use rustc_errors
::{Applicability, DiagnosticBuilder, PResult}
;
17 use rustc_span
::source_map
::{self, Span, Spanned}
;
18 use rustc_span
::symbol
::{kw, sym, Ident, Symbol}
;
19 use rustc_span
::{BytePos, Pos}
;
23 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
24 /// dropped into the token stream, which happens while parsing the result of
25 /// macro expansion). Placement of these is not as complex as I feared it would
26 /// be. The important thing is to make sure that lookahead doesn't balk at
27 /// `token::Interpolated` tokens.
28 macro_rules
! maybe_whole_expr
{
30 if let token
::Interpolated(nt
) = &$p
.token
.kind
{
32 token
::NtExpr(e
) | token
::NtLiteral(e
) => {
37 token
::NtPath(path
) => {
38 let path
= path
.clone();
42 ExprKind
::Path(None
, path
),
46 token
::NtBlock(block
) => {
47 let block
= block
.clone();
51 ExprKind
::Block(block
, None
),
62 pub(super) enum LhsExpr
{
64 AttributesParsed(AttrVec
),
65 AlreadyParsed(P
<Expr
>),
68 impl From
<Option
<AttrVec
>> for LhsExpr
{
69 /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
70 /// and `None` into `LhsExpr::NotYetParsed`.
72 /// This conversion does not allocate.
73 fn from(o
: Option
<AttrVec
>) -> Self {
74 if let Some(attrs
) = o { LhsExpr::AttributesParsed(attrs) }
else { LhsExpr::NotYetParsed }
78 impl From
<P
<Expr
>> for LhsExpr
{
79 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
81 /// This conversion does not allocate.
82 fn from(expr
: P
<Expr
>) -> Self {
83 LhsExpr
::AlreadyParsed(expr
)
88 /// Parses an expression.
90 pub fn parse_expr(&mut self) -> PResult
<'a
, P
<Expr
>> {
91 self.parse_expr_res(Restrictions
::empty(), None
)
94 pub(super) fn parse_anon_const_expr(&mut self) -> PResult
<'a
, AnonConst
> {
95 self.parse_expr().map(|value
| AnonConst { id: DUMMY_NODE_ID, value }
)
98 fn parse_expr_catch_underscore(&mut self) -> PResult
<'a
, P
<Expr
>> {
99 match self.parse_expr() {
100 Ok(expr
) => Ok(expr
),
101 Err(mut err
) => match self.token
.ident() {
102 Some((Ident { name: kw::Underscore, .. }
, false))
103 if self.look_ahead(1, |t
| t
== &token
::Comma
) =>
105 // Special-case handling of `foo(_, _, _)`
108 Ok(self.mk_expr(self.prev_token
.span
, ExprKind
::Err
, AttrVec
::new()))
115 /// Parses a sequence of expressions delimited by parentheses.
116 fn parse_paren_expr_seq(&mut self) -> PResult
<'a
, Vec
<P
<Expr
>>> {
117 self.parse_paren_comma_seq(|p
| p
.parse_expr_catch_underscore()).map(|(r
, _
)| r
)
120 /// Parses an expression, subject to the given restrictions.
122 pub(super) fn parse_expr_res(
125 already_parsed_attrs
: Option
<AttrVec
>,
126 ) -> PResult
<'a
, P
<Expr
>> {
127 self.with_res(r
, |this
| this
.parse_assoc_expr(already_parsed_attrs
))
130 /// Parses an associative expression.
132 /// This parses an expression accounting for associativity and precedence of the operators in
135 fn parse_assoc_expr(&mut self, already_parsed_attrs
: Option
<AttrVec
>) -> PResult
<'a
, P
<Expr
>> {
136 self.parse_assoc_expr_with(0, already_parsed_attrs
.into())
139 /// Parses an associative expression with operators of at least `min_prec` precedence.
140 pub(super) fn parse_assoc_expr_with(
144 ) -> PResult
<'a
, P
<Expr
>> {
145 let mut lhs
= if let LhsExpr
::AlreadyParsed(expr
) = lhs
{
148 let attrs
= match lhs
{
149 LhsExpr
::AttributesParsed(attrs
) => Some(attrs
),
152 if [token
::DotDot
, token
::DotDotDot
, token
::DotDotEq
].contains(&self.token
.kind
) {
153 return self.parse_prefix_range_expr(attrs
);
155 self.parse_prefix_expr(attrs
)?
158 let last_type_ascription_set
= self.last_type_ascription
.is_some();
160 if !self.should_continue_as_assoc_expr(&lhs
) {
161 self.last_type_ascription
= None
;
165 self.expected_tokens
.push(TokenType
::Operator
);
166 while let Some(op
) = self.check_assoc_op() {
167 // Adjust the span for interpolated LHS to point to the `$lhs` token
168 // and not to what it refers to.
169 let lhs_span
= match self.prev_token
.kind
{
170 TokenKind
::Interpolated(..) => self.prev_token
.span
,
174 let cur_op_span
= self.token
.span
;
175 let restrictions
= if op
.node
.is_assign_like() {
176 self.restrictions
& Restrictions
::NO_STRUCT_LITERAL
180 let prec
= op
.node
.precedence();
184 // Check for deprecated `...` syntax
185 if self.token
== token
::DotDotDot
&& op
.node
== AssocOp
::DotDotEq
{
186 self.err_dotdotdot_syntax(self.token
.span
);
189 if self.token
== token
::LArrow
{
190 self.err_larrow_operator(self.token
.span
);
194 if op
.node
.is_comparison() {
195 if let Some(expr
) = self.check_no_chained_comparison(&lhs
, &op
)?
{
200 if (op
.node
== AssocOp
::Equal
|| op
.node
== AssocOp
::NotEqual
)
201 && self.token
.kind
== token
::Eq
202 && self.prev_token
.span
.hi() == self.token
.span
.lo()
204 // Look for JS' `===` and `!==` and recover 😇
205 let sp
= op
.span
.to(self.token
.span
);
206 let sugg
= match op
.node
{
207 AssocOp
::Equal
=> "==",
208 AssocOp
::NotEqual
=> "!=",
211 self.struct_span_err(sp
, &format
!("invalid comparison operator `{}=`", sugg
))
212 .span_suggestion_short(
214 &format
!("`{s}=` is not a valid comparison operator, use `{s}`", s
= sugg
),
216 Applicability
::MachineApplicable
,
224 if op
== AssocOp
::As
{
225 lhs
= self.parse_assoc_op_cast(lhs
, lhs_span
, ExprKind
::Cast
)?
;
227 } else if op
== AssocOp
::Colon
{
228 lhs
= self.parse_assoc_op_ascribe(lhs
, lhs_span
)?
;
230 } else if op
== AssocOp
::DotDot
|| op
== AssocOp
::DotDotEq
{
231 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
232 // generalise it to the Fixity::None code.
233 lhs
= self.parse_range_expr(prec
, lhs
, op
, cur_op_span
)?
;
237 let fixity
= op
.fixity();
238 let prec_adjustment
= match fixity
{
241 // We currently have no non-associative operators that are not handled above by
242 // the special cases. The code is here only for future convenience.
245 let rhs
= self.with_res(restrictions
- Restrictions
::STMT_EXPR
, |this
| {
246 this
.parse_assoc_expr_with(prec
+ prec_adjustment
, LhsExpr
::NotYetParsed
)
249 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
250 // including the attributes.
252 lhs
.attrs
.iter().find(|a
| a
.style
== AttrStyle
::Outer
).map_or(lhs_span
, |a
| a
.span
);
253 let span
= lhs_span
.to(rhs
.span
);
266 | AssocOp
::ShiftRight
272 | AssocOp
::GreaterEqual
=> {
273 let ast_op
= op
.to_ast_binop().unwrap();
274 let binary
= self.mk_binary(source_map
::respan(cur_op_span
, ast_op
), lhs
, rhs
);
275 self.mk_expr(span
, binary
, AttrVec
::new())
278 self.mk_expr(span
, ExprKind
::Assign(lhs
, rhs
, cur_op_span
), AttrVec
::new())
280 AssocOp
::AssignOp(k
) => {
282 token
::Plus
=> BinOpKind
::Add
,
283 token
::Minus
=> BinOpKind
::Sub
,
284 token
::Star
=> BinOpKind
::Mul
,
285 token
::Slash
=> BinOpKind
::Div
,
286 token
::Percent
=> BinOpKind
::Rem
,
287 token
::Caret
=> BinOpKind
::BitXor
,
288 token
::And
=> BinOpKind
::BitAnd
,
289 token
::Or
=> BinOpKind
::BitOr
,
290 token
::Shl
=> BinOpKind
::Shl
,
291 token
::Shr
=> BinOpKind
::Shr
,
293 let aopexpr
= self.mk_assign_op(source_map
::respan(cur_op_span
, aop
), lhs
, rhs
);
294 self.mk_expr(span
, aopexpr
, AttrVec
::new())
296 AssocOp
::As
| AssocOp
::Colon
| AssocOp
::DotDot
| AssocOp
::DotDotEq
=> {
297 self.span_bug(span
, "AssocOp should have been handled by special case")
301 if let Fixity
::None
= fixity
{
305 if last_type_ascription_set
{
306 self.last_type_ascription
= None
;
311 fn should_continue_as_assoc_expr(&mut self, lhs
: &Expr
) -> bool
{
312 match (self.expr_is_complete(lhs
), AssocOp
::from_token(&self.token
)) {
313 // Semi-statement forms are odd:
314 // See https://github.com/rust-lang/rust/issues/29071
315 (true, None
) => false,
316 (false, _
) => true, // Continue parsing the expression.
317 // An exhaustive check is done in the following block, but these are checked first
318 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
319 // want to keep their span info to improve diagnostics in these cases in a later stage.
320 (true, Some(AssocOp
::Multiply
)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
321 (true, Some(AssocOp
::Subtract
)) | // `{ 42 } -5`
322 (true, Some(AssocOp
::Add
)) // `{ 42 } + 42
323 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
324 // `if x { a } else { b } && if y { c } else { d }`
325 if !self.look_ahead(1, |t
| t
.is_used_keyword()) => {
326 // These cases are ambiguous and can't be identified in the parser alone.
327 let sp
= self.sess
.source_map().start_point(self.token
.span
);
328 self.sess
.ambiguous_block_expr_parse
.borrow_mut().insert(sp
, lhs
.span
);
331 (true, Some(AssocOp
::LAnd
)) => {
332 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`. Separated from the
333 // above due to #74233.
334 // These cases are ambiguous and can't be identified in the parser alone.
335 let sp
= self.sess
.source_map().start_point(self.token
.span
);
336 self.sess
.ambiguous_block_expr_parse
.borrow_mut().insert(sp
, lhs
.span
);
339 (true, Some(ref op
)) if !op
.can_continue_expr_unambiguously() => false,
341 self.error_found_expr_would_be_stmt(lhs
);
347 /// We've found an expression that would be parsed as a statement,
348 /// but the next token implies this should be parsed as an expression.
349 /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
350 fn error_found_expr_would_be_stmt(&self, lhs
: &Expr
) {
351 let mut err
= self.struct_span_err(
353 &format
!("expected expression, found `{}`", pprust
::token_to_string(&self.token
),),
355 err
.span_label(self.token
.span
, "expected expression");
356 self.sess
.expr_parentheses_needed(&mut err
, lhs
.span
, Some(pprust
::expr_to_string(&lhs
)));
360 /// Possibly translate the current token to an associative operator.
361 /// The method does not advance the current token.
363 /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
364 fn check_assoc_op(&self) -> Option
<Spanned
<AssocOp
>> {
365 let (op
, span
) = match (AssocOp
::from_token(&self.token
), self.token
.ident()) {
366 (Some(op
), _
) => (op
, self.token
.span
),
367 (None
, Some((Ident { name: sym::and, span }
, false))) => {
368 self.error_bad_logical_op("and", "&&", "conjunction");
369 (AssocOp
::LAnd
, span
)
371 (None
, Some((Ident { name: sym::or, span }
, false))) => {
372 self.error_bad_logical_op("or", "||", "disjunction");
377 Some(source_map
::respan(span
, op
))
380 /// Error on `and` and `or` suggesting `&&` and `||` respectively.
381 fn error_bad_logical_op(&self, bad
: &str, good
: &str, english
: &str) {
382 self.struct_span_err(self.token
.span
, &format
!("`{}` is not a logical operator", bad
))
383 .span_suggestion_short(
385 &format
!("use `{}` to perform logical {}", good
, english
),
387 Applicability
::MachineApplicable
,
389 .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators")
393 /// Checks if this expression is a successfully parsed statement.
394 fn expr_is_complete(&self, e
: &Expr
) -> bool
{
395 self.restrictions
.contains(Restrictions
::STMT_EXPR
)
396 && !classify
::expr_requires_semi_to_be_stmt(e
)
399 /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
400 /// The other two variants are handled in `parse_prefix_range_expr` below.
407 ) -> PResult
<'a
, P
<Expr
>> {
408 let rhs
= if self.is_at_start_of_range_notation_rhs() {
409 Some(self.parse_assoc_expr_with(prec
+ 1, LhsExpr
::NotYetParsed
)?
)
413 let rhs_span
= rhs
.as_ref().map_or(cur_op_span
, |x
| x
.span
);
414 let span
= lhs
.span
.to(rhs_span
);
416 if op
== AssocOp
::DotDot { RangeLimits::HalfOpen }
else { RangeLimits::Closed }
;
417 Ok(self.mk_expr(span
, self.mk_range(Some(lhs
), rhs
, limits
)?
, AttrVec
::new()))
420 fn is_at_start_of_range_notation_rhs(&self) -> bool
{
421 if self.token
.can_begin_expr() {
422 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
423 if self.token
== token
::OpenDelim(token
::Brace
) {
424 return !self.restrictions
.contains(Restrictions
::NO_STRUCT_LITERAL
);
432 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
433 fn parse_prefix_range_expr(&mut self, attrs
: Option
<AttrVec
>) -> PResult
<'a
, P
<Expr
>> {
434 // Check for deprecated `...` syntax.
435 if self.token
== token
::DotDotDot
{
436 self.err_dotdotdot_syntax(self.token
.span
);
440 [token
::DotDot
, token
::DotDotDot
, token
::DotDotEq
].contains(&self.token
.kind
),
441 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
445 let limits
= match self.token
.kind
{
446 token
::DotDot
=> RangeLimits
::HalfOpen
,
447 _
=> RangeLimits
::Closed
,
449 let op
= AssocOp
::from_token(&self.token
);
450 let attrs
= self.parse_or_use_outer_attributes(attrs
)?
;
451 let lo
= self.token
.span
;
453 let (span
, opt_end
) = if self.is_at_start_of_range_notation_rhs() {
454 // RHS must be parsed with more associativity than the dots.
455 self.parse_assoc_expr_with(op
.unwrap().precedence() + 1, LhsExpr
::NotYetParsed
)
456 .map(|x
| (lo
.to(x
.span
), Some(x
)))?
460 Ok(self.mk_expr(span
, self.mk_range(None
, opt_end
, limits
)?
, attrs
))
463 /// Parses a prefix-unary-operator expr.
464 fn parse_prefix_expr(&mut self, attrs
: Option
<AttrVec
>) -> PResult
<'a
, P
<Expr
>> {
465 let attrs
= self.parse_or_use_outer_attributes(attrs
)?
;
466 self.maybe_collect_tokens(!attrs
.is_empty(), |this
| {
467 let lo
= this
.token
.span
;
468 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
469 let (hi
, ex
) = match this
.token
.uninterpolate().kind
{
470 token
::Not
=> this
.parse_unary_expr(lo
, UnOp
::Not
), // `!expr`
471 token
::Tilde
=> this
.recover_tilde_expr(lo
), // `~expr`
472 token
::BinOp(token
::Minus
) => this
.parse_unary_expr(lo
, UnOp
::Neg
), // `-expr`
473 token
::BinOp(token
::Star
) => this
.parse_unary_expr(lo
, UnOp
::Deref
), // `*expr`
474 token
::BinOp(token
::And
) | token
::AndAnd
=> this
.parse_borrow_expr(lo
),
475 token
::Ident(..) if this
.token
.is_keyword(kw
::Box
) => this
.parse_box_expr(lo
),
476 token
::Ident(..) if this
.is_mistaken_not_ident_negation() => {
477 this
.recover_not_expr(lo
)
479 _
=> return this
.parse_dot_or_call_expr(Some(attrs
)),
481 Ok(this
.mk_expr(lo
.to(hi
), ex
, attrs
))
485 fn parse_prefix_expr_common(&mut self, lo
: Span
) -> PResult
<'a
, (Span
, P
<Expr
>)> {
487 let expr
= self.parse_prefix_expr(None
);
488 let (span
, expr
) = self.interpolated_or_expr_span(expr
)?
;
489 Ok((lo
.to(span
), expr
))
492 fn parse_unary_expr(&mut self, lo
: Span
, op
: UnOp
) -> PResult
<'a
, (Span
, ExprKind
)> {
493 let (span
, expr
) = self.parse_prefix_expr_common(lo
)?
;
494 Ok((span
, self.mk_unary(op
, expr
)))
497 // Recover on `!` suggesting for bitwise negation instead.
498 fn recover_tilde_expr(&mut self, lo
: Span
) -> PResult
<'a
, (Span
, ExprKind
)> {
499 self.struct_span_err(lo
, "`~` cannot be used as a unary operator")
500 .span_suggestion_short(
502 "use `!` to perform bitwise not",
504 Applicability
::MachineApplicable
,
508 self.parse_unary_expr(lo
, UnOp
::Not
)
511 /// Parse `box expr`.
512 fn parse_box_expr(&mut self, lo
: Span
) -> PResult
<'a
, (Span
, ExprKind
)> {
513 let (span
, expr
) = self.parse_prefix_expr_common(lo
)?
;
514 self.sess
.gated_spans
.gate(sym
::box_syntax
, span
);
515 Ok((span
, ExprKind
::Box(expr
)))
518 fn is_mistaken_not_ident_negation(&self) -> bool
{
519 let token_cannot_continue_expr
= |t
: &Token
| match t
.uninterpolate().kind
{
520 // These tokens can start an expression after `!`, but
521 // can't continue an expression after an ident
522 token
::Ident(name
, is_raw
) => token
::ident_can_begin_expr(name
, t
.span
, is_raw
),
523 token
::Literal(..) | token
::Pound
=> true,
524 _
=> t
.is_whole_expr(),
526 self.token
.is_ident_named(sym
::not
) && self.look_ahead(1, token_cannot_continue_expr
)
529 /// Recover on `not expr` in favor of `!expr`.
530 fn recover_not_expr(&mut self, lo
: Span
) -> PResult
<'a
, (Span
, ExprKind
)> {
532 let not_token
= self.look_ahead(1, |t
| t
.clone());
533 self.struct_span_err(
535 &format
!("unexpected {} after identifier", super::token_descr(¬_token
)),
537 .span_suggestion_short(
538 // Span the `not` plus trailing whitespace to avoid
539 // trailing whitespace after the `!` in our suggestion
540 self.sess
.source_map().span_until_non_whitespace(lo
.to(not_token
.span
)),
541 "use `!` to perform logical negation",
543 Applicability
::MachineApplicable
,
548 self.parse_unary_expr(lo
, UnOp
::Not
)
551 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
552 fn interpolated_or_expr_span(
554 expr
: PResult
<'a
, P
<Expr
>>,
555 ) -> PResult
<'a
, (Span
, P
<Expr
>)> {
558 match self.prev_token
.kind
{
559 TokenKind
::Interpolated(..) => self.prev_token
.span
,
567 fn parse_assoc_op_cast(
571 expr_kind
: fn(P
<Expr
>, P
<Ty
>) -> ExprKind
,
572 ) -> PResult
<'a
, P
<Expr
>> {
573 let mk_expr
= |this
: &mut Self, rhs
: P
<Ty
>| {
574 this
.mk_expr(lhs_span
.to(rhs
.span
), expr_kind(lhs
, rhs
), AttrVec
::new())
577 // Save the state of the parser before parsing type normally, in case there is a
578 // LessThan comparison after this cast.
579 let parser_snapshot_before_type
= self.clone();
580 let cast_expr
= match self.parse_ty_no_plus() {
581 Ok(rhs
) => mk_expr(self, rhs
),
582 Err(mut type_err
) => {
583 // Rewind to before attempting to parse the type with generics, to recover
584 // from situations like `x as usize < y` in which we first tried to parse
585 // `usize < y` as a type with generic arguments.
586 let parser_snapshot_after_type
= mem
::replace(self, parser_snapshot_before_type
);
588 match self.parse_path(PathStyle
::Expr
) {
590 let (op_noun
, op_verb
) = match self.token
.kind
{
591 token
::Lt
=> ("comparison", "comparing"),
592 token
::BinOp(token
::Shl
) => ("shift", "shifting"),
594 // We can end up here even without `<` being the next token, for
595 // example because `parse_ty_no_plus` returns `Err` on keywords,
596 // but `parse_path` returns `Ok` on them due to error recovery.
597 // Return original error and parser state.
598 *self = parser_snapshot_after_type
;
599 return Err(type_err
);
603 // Successfully parsed the type path leaving a `<` yet to parse.
606 // Report non-fatal diagnostics, keep `x as usize` as an expression
607 // in AST and continue parsing.
609 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
610 pprust
::path_to_string(&path
),
613 let span_after_type
= parser_snapshot_after_type
.token
.span
;
614 let expr
= mk_expr(self, self.mk_ty(path
.span
, TyKind
::Path(None
, path
)));
617 .span_to_snippet(expr
.span
)
618 .unwrap_or_else(|_
| pprust
::expr_to_string(&expr
));
620 self.struct_span_err(self.token
.span
, &msg
)
622 self.look_ahead(1, |t
| t
.span
).to(span_after_type
),
623 "interpreted as generic arguments",
625 .span_label(self.token
.span
, format
!("not interpreted as {}", op_noun
))
628 &format
!("try {} the cast value", op_verb
),
629 format
!("({})", expr_str
),
630 Applicability
::MachineApplicable
,
636 Err(mut path_err
) => {
637 // Couldn't parse as a path, return original error and parser state.
639 *self = parser_snapshot_after_type
;
640 return Err(type_err
);
646 self.parse_and_disallow_postfix_after_cast(cast_expr
)
649 /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
650 /// then emits an error and returns the newly parsed tree.
651 /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
652 fn parse_and_disallow_postfix_after_cast(
655 ) -> PResult
<'a
, P
<Expr
>> {
656 // Save the memory location of expr before parsing any following postfix operators.
657 // This will be compared with the memory location of the output expression.
658 // If they different we can assume we parsed another expression because the existing expression is not reallocated.
659 let addr_before
= &*cast_expr
as *const _
as usize;
660 let span
= cast_expr
.span
;
661 let with_postfix
= self.parse_dot_or_call_expr_with_(cast_expr
, span
)?
;
662 let changed
= addr_before
!= &*with_postfix
as *const _
as usize;
664 // Check if an illegal postfix operator has been added after the cast.
665 // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator.
666 if !matches
!(with_postfix
.kind
, ExprKind
::Cast(_
, _
) | ExprKind
::Type(_
, _
)) || changed
{
668 "casts cannot be followed by {}",
669 match with_postfix
.kind
{
670 ExprKind
::Index(_
, _
) => "indexing",
671 ExprKind
::Try(_
) => "?",
672 ExprKind
::Field(_
, _
) => "a field access",
673 ExprKind
::MethodCall(_
, _
, _
) => "a method call",
674 ExprKind
::Call(_
, _
) => "a function call",
675 ExprKind
::Await(_
) => "`.await`",
676 ExprKind
::Err
=> return Ok(with_postfix
),
677 _
=> unreachable
!("parse_dot_or_call_expr_with_ shouldn't produce this"),
680 let mut err
= self.struct_span_err(span
, &msg
);
681 // If type ascription is "likely an error", the user will already be getting a useful
682 // help message, and doesn't need a second.
683 if self.last_type_ascription
.map_or(false, |last_ascription
| last_ascription
.1) {
684 self.maybe_annotate_with_ascription(&mut err
, false);
686 let suggestions
= vec
![
687 (span
.shrink_to_lo(), "(".to_string()),
688 (span
.shrink_to_hi(), ")".to_string()),
690 err
.multipart_suggestion(
691 "try surrounding the expression in parentheses",
693 Applicability
::MachineApplicable
,
701 fn parse_assoc_op_ascribe(&mut self, lhs
: P
<Expr
>, lhs_span
: Span
) -> PResult
<'a
, P
<Expr
>> {
702 let maybe_path
= self.could_ascription_be_path(&lhs
.kind
);
703 self.last_type_ascription
= Some((self.prev_token
.span
, maybe_path
));
704 let lhs
= self.parse_assoc_op_cast(lhs
, lhs_span
, ExprKind
::Type
)?
;
705 self.sess
.gated_spans
.gate(sym
::type_ascription
, lhs
.span
);
709 /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
710 fn parse_borrow_expr(&mut self, lo
: Span
) -> PResult
<'a
, (Span
, ExprKind
)> {
712 let has_lifetime
= self.token
.is_lifetime() && self.look_ahead(1, |t
| t
!= &token
::Colon
);
713 let lifetime
= has_lifetime
.then(|| self.expect_lifetime()); // For recovery, see below.
714 let (borrow_kind
, mutbl
) = self.parse_borrow_modifiers(lo
);
715 let expr
= self.parse_prefix_expr(None
);
716 let (hi
, expr
) = self.interpolated_or_expr_span(expr
)?
;
717 let span
= lo
.to(hi
);
718 if let Some(lt
) = lifetime
{
719 self.error_remove_borrow_lifetime(span
, lt
.ident
.span
);
721 Ok((span
, ExprKind
::AddrOf(borrow_kind
, mutbl
, expr
)))
724 fn error_remove_borrow_lifetime(&self, span
: Span
, lt_span
: Span
) {
725 self.struct_span_err(span
, "borrow expressions cannot be annotated with lifetimes")
726 .span_label(lt_span
, "annotated with lifetime here")
729 "remove the lifetime annotation",
731 Applicability
::MachineApplicable
,
736 /// Parse `mut?` or `raw [ const | mut ]`.
737 fn parse_borrow_modifiers(&mut self, lo
: Span
) -> (ast
::BorrowKind
, ast
::Mutability
) {
738 if self.check_keyword(kw
::Raw
) && self.look_ahead(1, Token
::is_mutability
) {
739 // `raw [ const | mut ]`.
740 let found_raw
= self.eat_keyword(kw
::Raw
);
742 let mutability
= self.parse_const_or_mut().unwrap();
743 self.sess
.gated_spans
.gate(sym
::raw_ref_op
, lo
.to(self.prev_token
.span
));
744 (ast
::BorrowKind
::Raw
, mutability
)
747 (ast
::BorrowKind
::Ref
, self.parse_mutability())
751 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
752 fn parse_dot_or_call_expr(&mut self, attrs
: Option
<AttrVec
>) -> PResult
<'a
, P
<Expr
>> {
753 let attrs
= self.parse_or_use_outer_attributes(attrs
)?
;
754 let base
= self.parse_bottom_expr();
755 let (span
, base
) = self.interpolated_or_expr_span(base
)?
;
756 self.parse_dot_or_call_expr_with(base
, span
, attrs
)
759 pub(super) fn parse_dot_or_call_expr_with(
764 ) -> PResult
<'a
, P
<Expr
>> {
765 // Stitch the list of outer attributes onto the return value.
766 // A little bit ugly, but the best way given the current code
768 self.parse_dot_or_call_expr_with_(e0
, lo
).map(|expr
| {
769 expr
.map(|mut expr
| {
770 attrs
.extend
::<Vec
<_
>>(expr
.attrs
.into());
777 fn parse_dot_or_call_expr_with_(&mut self, mut e
: P
<Expr
>, lo
: Span
) -> PResult
<'a
, P
<Expr
>> {
779 if self.eat(&token
::Question
) {
781 e
= self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::Try(e
), AttrVec
::new());
784 if self.eat(&token
::Dot
) {
786 e
= self.parse_dot_suffix_expr(lo
, e
)?
;
789 if self.expr_is_complete(&e
) {
792 e
= match self.token
.kind
{
793 token
::OpenDelim(token
::Paren
) => self.parse_fn_call_expr(lo
, e
),
794 token
::OpenDelim(token
::Bracket
) => self.parse_index_expr(lo
, e
)?
,
800 fn parse_dot_suffix_expr(&mut self, lo
: Span
, base
: P
<Expr
>) -> PResult
<'a
, P
<Expr
>> {
801 match self.token
.uninterpolate().kind
{
802 token
::Ident(..) => self.parse_dot_suffix(base
, lo
),
803 token
::Literal(token
::Lit { kind: token::Integer, symbol, suffix }
) => {
804 Ok(self.parse_tuple_field_access_expr(lo
, base
, symbol
, suffix
, None
))
806 token
::Literal(token
::Lit { kind: token::Float, symbol, suffix }
) => {
807 Ok(self.parse_tuple_field_access_expr_float(lo
, base
, symbol
, suffix
))
810 self.error_unexpected_after_dot();
816 fn error_unexpected_after_dot(&self) {
817 // FIXME Could factor this out into non_fatal_unexpected or something.
818 let actual
= pprust
::token_to_string(&self.token
);
819 self.struct_span_err(self.token
.span
, &format
!("unexpected token: `{}`", actual
)).emit();
822 // We need and identifier or integer, but the next token is a float.
823 // Break the float into components to extract the identifier or integer.
824 // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
825 // parts unless those parts are processed immediately. `TokenCursor` should either
826 // support pushing "future tokens" (would be also helpful to `break_and_eat`), or
827 // we should break everything including floats into more basic proc-macro style
828 // tokens in the lexer (probably preferable).
829 fn parse_tuple_field_access_expr_float(
834 suffix
: Option
<Symbol
>,
837 enum FloatComponent
{
841 use FloatComponent
::*;
843 let float_str
= float
.as_str();
844 let mut components
= Vec
::new();
845 let mut ident_like
= String
::new();
846 for c
in float_str
.chars() {
847 if c
== '_'
|| c
.is_ascii_alphanumeric() {
849 } else if matches
!(c
, '
.'
| '
+'
| '
-'
) {
850 if !ident_like
.is_empty() {
851 components
.push(IdentLike(mem
::take(&mut ident_like
)));
853 components
.push(Punct(c
));
855 panic
!("unexpected character in a float token: {:?}", c
)
858 if !ident_like
.is_empty() {
859 components
.push(IdentLike(ident_like
));
862 // With proc macros the span can refer to anything, the source may be too short,
863 // or too long, or non-ASCII. It only makes sense to break our span into components
864 // if its underlying text is identical to our float literal.
865 let span
= self.token
.span
;
866 let can_take_span_apart
=
867 || self.span_to_snippet(span
).as_deref() == Ok(float_str
).as_deref();
872 self.parse_tuple_field_access_expr(lo
, base
, Symbol
::intern(&i
), suffix
, None
)
875 [IdentLike(i
), Punct('
.'
)] => {
876 let (ident_span
, dot_span
) = if can_take_span_apart() {
877 let (span
, ident_len
) = (span
.data(), BytePos
::from_usize(i
.len()));
878 let ident_span
= span
.with_hi(span
.lo
+ ident_len
);
879 let dot_span
= span
.with_lo(span
.lo
+ ident_len
);
880 (ident_span
, dot_span
)
884 assert
!(suffix
.is_none());
885 let symbol
= Symbol
::intern(&i
);
886 self.token
= Token
::new(token
::Ident(symbol
, false), ident_span
);
887 let next_token
= Token
::new(token
::Dot
, dot_span
);
888 self.parse_tuple_field_access_expr(lo
, base
, symbol
, None
, Some(next_token
))
891 [IdentLike(i1
), Punct('
.'
), IdentLike(i2
)] => {
892 let (ident1_span
, dot_span
, ident2_span
) = if can_take_span_apart() {
893 let (span
, ident1_len
) = (span
.data(), BytePos
::from_usize(i1
.len()));
894 let ident1_span
= span
.with_hi(span
.lo
+ ident1_len
);
896 .with_lo(span
.lo
+ ident1_len
)
897 .with_hi(span
.lo
+ ident1_len
+ BytePos(1));
898 let ident2_span
= self.token
.span
.with_lo(span
.lo
+ ident1_len
+ BytePos(1));
899 (ident1_span
, dot_span
, ident2_span
)
903 let symbol1
= Symbol
::intern(&i1
);
904 self.token
= Token
::new(token
::Ident(symbol1
, false), ident1_span
);
905 let next_token1
= Token
::new(token
::Dot
, dot_span
);
907 self.parse_tuple_field_access_expr(lo
, base
, symbol1
, None
, Some(next_token1
));
908 let symbol2
= Symbol
::intern(&i2
);
909 let next_token2
= Token
::new(token
::Ident(symbol2
, false), ident2_span
);
910 self.bump_with(next_token2
); // `.`
911 self.parse_tuple_field_access_expr(lo
, base1
, symbol2
, suffix
, None
)
913 // 1e+ | 1e- (recovered)
914 [IdentLike(_
), Punct('
+'
| '
-'
)] |
916 [IdentLike(_
), Punct('
+'
| '
-'
), IdentLike(_
)] |
918 [IdentLike(_
), Punct('
.'
), IdentLike(_
), Punct('
+'
| '
-'
), IdentLike(_
)] => {
919 // See the FIXME about `TokenCursor` above.
920 self.error_unexpected_after_dot();
923 _
=> panic
!("unexpected components in a float token: {:?}", components
),
927 fn parse_tuple_field_access_expr(
932 suffix
: Option
<Symbol
>,
933 next_token
: Option
<Token
>,
936 Some(next_token
) => self.bump_with(next_token
),
939 let span
= self.prev_token
.span
;
940 let field
= ExprKind
::Field(base
, Ident
::new(field
, span
));
941 self.expect_no_suffix(span
, "a tuple index", suffix
);
942 self.mk_expr(lo
.to(span
), field
, AttrVec
::new())
945 /// Parse a function call expression, `expr(...)`.
946 fn parse_fn_call_expr(&mut self, lo
: Span
, fun
: P
<Expr
>) -> P
<Expr
> {
947 let seq
= self.parse_paren_expr_seq().map(|args
| {
948 self.mk_expr(lo
.to(self.prev_token
.span
), self.mk_call(fun
, args
), AttrVec
::new())
950 self.recover_seq_parse_error(token
::Paren
, lo
, seq
)
953 /// Parse an indexing expression `expr[...]`.
954 fn parse_index_expr(&mut self, lo
: Span
, base
: P
<Expr
>) -> PResult
<'a
, P
<Expr
>> {
956 let index
= self.parse_expr()?
;
957 self.expect(&token
::CloseDelim(token
::Bracket
))?
;
958 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), self.mk_index(base
, index
), AttrVec
::new()))
961 /// Assuming we have just parsed `.`, continue parsing into an expression.
962 fn parse_dot_suffix(&mut self, self_arg
: P
<Expr
>, lo
: Span
) -> PResult
<'a
, P
<Expr
>> {
963 if self.token
.uninterpolated_span().rust_2018() && self.eat_keyword(kw
::Await
) {
964 return self.mk_await_expr(self_arg
, lo
);
967 let fn_span_lo
= self.token
.span
;
968 let mut segment
= self.parse_path_segment(PathStyle
::Expr
)?
;
969 self.check_trailing_angle_brackets(&segment
, &[&token
::OpenDelim(token
::Paren
)]);
970 self.check_turbofish_missing_angle_brackets(&mut segment
);
972 if self.check(&token
::OpenDelim(token
::Paren
)) {
973 // Method call `expr.f()`
974 let mut args
= self.parse_paren_expr_seq()?
;
975 args
.insert(0, self_arg
);
977 let fn_span
= fn_span_lo
.to(self.prev_token
.span
);
978 let span
= lo
.to(self.prev_token
.span
);
979 Ok(self.mk_expr(span
, ExprKind
::MethodCall(segment
, args
, fn_span
), AttrVec
::new()))
981 // Field access `expr.f`
982 if let Some(args
) = segment
.args
{
983 self.struct_span_err(
985 "field expressions cannot have generic arguments",
990 let span
= lo
.to(self.prev_token
.span
);
991 Ok(self.mk_expr(span
, ExprKind
::Field(self_arg
, segment
.ident
), AttrVec
::new()))
995 /// At the bottom (top?) of the precedence hierarchy,
996 /// Parses things like parenthesized exprs, macros, `return`, etc.
998 /// N.B., this does not parse outer attributes, and is private because it only works
999 /// correctly if called from `parse_dot_or_call_expr()`.
1000 fn parse_bottom_expr(&mut self) -> PResult
<'a
, P
<Expr
>> {
1001 maybe_recover_from_interpolated_ty_qpath
!(self, true);
1002 maybe_whole_expr
!(self);
1004 // Outer attributes are already parsed and will be
1005 // added to the return value after the fact.
1007 // Therefore, prevent sub-parser from parsing
1008 // attributes by giving them a empty "already-parsed" list.
1009 let attrs
= AttrVec
::new();
1011 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
1012 let lo
= self.token
.span
;
1013 if let token
::Literal(_
) = self.token
.kind
{
1014 // This match arm is a special-case of the `_` match arm below and
1015 // could be removed without changing functionality, but it's faster
1016 // to have it here, especially for programs with large constants.
1017 self.parse_lit_expr(attrs
)
1018 } else if self.check(&token
::OpenDelim(token
::Paren
)) {
1019 self.parse_tuple_parens_expr(attrs
)
1020 } else if self.check(&token
::OpenDelim(token
::Brace
)) {
1021 self.parse_block_expr(None
, lo
, BlockCheckMode
::Default
, attrs
)
1022 } else if self.check(&token
::BinOp(token
::Or
)) || self.check(&token
::OrOr
) {
1023 self.parse_closure_expr(attrs
)
1024 } else if self.check(&token
::OpenDelim(token
::Bracket
)) {
1025 self.parse_array_or_repeat_expr(attrs
)
1026 } else if self.eat_lt() {
1027 let (qself
, path
) = self.parse_qpath(PathStyle
::Expr
)?
;
1028 Ok(self.mk_expr(lo
.to(path
.span
), ExprKind
::Path(Some(qself
), path
), attrs
))
1029 } else if self.check_path() {
1030 self.parse_path_start_expr(attrs
)
1031 } else if self.check_keyword(kw
::Move
) || self.check_keyword(kw
::Static
) {
1032 self.parse_closure_expr(attrs
)
1033 } else if self.eat_keyword(kw
::If
) {
1034 self.parse_if_expr(attrs
)
1035 } else if self.check_keyword(kw
::For
) {
1036 if self.choose_generics_over_qpath(1) {
1037 // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery,
1038 // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns.
1039 // When `for <Foo as Bar>::Proj in $expr $block` is wanted,
1040 // you can disambiguate in favor of a pattern with `(...)`.
1041 self.recover_quantified_closure_expr(attrs
)
1043 assert
!(self.eat_keyword(kw
::For
));
1044 self.parse_for_expr(None
, self.prev_token
.span
, attrs
)
1046 } else if self.eat_keyword(kw
::While
) {
1047 self.parse_while_expr(None
, self.prev_token
.span
, attrs
)
1048 } else if let Some(label
) = self.eat_label() {
1049 self.parse_labeled_expr(label
, attrs
)
1050 } else if self.eat_keyword(kw
::Loop
) {
1051 self.parse_loop_expr(None
, self.prev_token
.span
, attrs
)
1052 } else if self.eat_keyword(kw
::Continue
) {
1053 let kind
= ExprKind
::Continue(self.eat_label());
1054 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
))
1055 } else if self.eat_keyword(kw
::Match
) {
1056 let match_sp
= self.prev_token
.span
;
1057 self.parse_match_expr(attrs
).map_err(|mut err
| {
1058 err
.span_label(match_sp
, "while parsing this match expression");
1061 } else if self.eat_keyword(kw
::Unsafe
) {
1062 self.parse_block_expr(None
, lo
, BlockCheckMode
::Unsafe(ast
::UserProvided
), attrs
)
1063 } else if self.is_do_catch_block() {
1064 self.recover_do_catch(attrs
)
1065 } else if self.is_try_block() {
1066 self.expect_keyword(kw
::Try
)?
;
1067 self.parse_try_block(lo
, attrs
)
1068 } else if self.eat_keyword(kw
::Return
) {
1069 self.parse_return_expr(attrs
)
1070 } else if self.eat_keyword(kw
::Break
) {
1071 self.parse_break_expr(attrs
)
1072 } else if self.eat_keyword(kw
::Yield
) {
1073 self.parse_yield_expr(attrs
)
1074 } else if self.eat_keyword(kw
::Let
) {
1075 self.parse_let_expr(attrs
)
1076 } else if !self.unclosed_delims
.is_empty() && self.check(&token
::Semi
) {
1077 // Don't complain about bare semicolons after unclosed braces
1078 // recovery in order to keep the error count down. Fixing the
1079 // delimiters will possibly also fix the bare semicolon found in
1080 // expression context. For example, silence the following error:
1082 // error: expected expression, found `;`
1086 // | ^ expected expression
1088 Ok(self.mk_expr_err(self.token
.span
))
1089 } else if self.token
.uninterpolated_span().rust_2018() {
1090 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1091 if self.check_keyword(kw
::Async
) {
1092 if self.is_async_block() {
1093 // Check for `async {` and `async move {`.
1094 self.parse_async_block(attrs
)
1096 self.parse_closure_expr(attrs
)
1098 } else if self.eat_keyword(kw
::Await
) {
1099 self.recover_incorrect_await_syntax(lo
, self.prev_token
.span
, attrs
)
1101 self.parse_lit_expr(attrs
)
1104 self.parse_lit_expr(attrs
)
1108 fn maybe_collect_tokens(
1110 has_outer_attrs
: bool
,
1111 f
: impl FnOnce(&mut Self) -> PResult
<'a
, P
<Expr
>>,
1112 ) -> PResult
<'a
, P
<Expr
>> {
1113 if has_outer_attrs
{
1114 let (mut expr
, tokens
) = self.collect_tokens(f
)?
;
1115 debug
!("maybe_collect_tokens: Collected tokens for {:?} (tokens {:?}", expr
, tokens
);
1116 expr
.tokens
= Some(tokens
);
1123 fn parse_lit_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1124 let lo
= self.token
.span
;
1125 match self.parse_opt_lit() {
1127 let expr
= self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::Lit(literal
), attrs
);
1128 self.maybe_recover_from_bad_qpath(expr
, true)
1130 None
=> self.try_macro_suggestion(),
1134 fn parse_tuple_parens_expr(&mut self, mut attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1135 let lo
= self.token
.span
;
1136 self.expect(&token
::OpenDelim(token
::Paren
))?
;
1137 attrs
.extend(self.parse_inner_attributes()?
); // `(#![foo] a, b, ...)` is OK.
1138 let (es
, trailing_comma
) = match self.parse_seq_to_end(
1139 &token
::CloseDelim(token
::Paren
),
1140 SeqSep
::trailing_allowed(token
::Comma
),
1141 |p
| p
.parse_expr_catch_underscore(),
1144 Err(err
) => return Ok(self.recover_seq_parse_error(token
::Paren
, lo
, Err(err
))),
1146 let kind
= if es
.len() == 1 && !trailing_comma
{
1147 // `(e)` is parenthesized `e`.
1148 ExprKind
::Paren(es
.into_iter().next().unwrap())
1150 // `(e,)` is a tuple with only one field, `e`.
1153 let expr
= self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
);
1154 self.maybe_recover_from_bad_qpath(expr
, true)
1157 fn parse_array_or_repeat_expr(&mut self, mut attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1158 let lo
= self.token
.span
;
1161 attrs
.extend(self.parse_inner_attributes()?
);
1163 let close
= &token
::CloseDelim(token
::Bracket
);
1164 let kind
= if self.eat(close
) {
1166 ExprKind
::Array(Vec
::new())
1169 let first_expr
= self.parse_expr()?
;
1170 if self.eat(&token
::Semi
) {
1171 // Repeating array syntax: `[ 0; 512 ]`
1172 let count
= self.parse_anon_const_expr()?
;
1173 self.expect(close
)?
;
1174 ExprKind
::Repeat(first_expr
, count
)
1175 } else if self.eat(&token
::Comma
) {
1176 // Vector with two or more elements.
1177 let sep
= SeqSep
::trailing_allowed(token
::Comma
);
1178 let (remaining_exprs
, _
) = self.parse_seq_to_end(close
, sep
, |p
| p
.parse_expr())?
;
1179 let mut exprs
= vec
![first_expr
];
1180 exprs
.extend(remaining_exprs
);
1181 ExprKind
::Array(exprs
)
1183 // Vector with one element
1184 self.expect(close
)?
;
1185 ExprKind
::Array(vec
![first_expr
])
1188 let expr
= self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
);
1189 self.maybe_recover_from_bad_qpath(expr
, true)
1192 fn parse_path_start_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1193 let path
= self.parse_path(PathStyle
::Expr
)?
;
1196 // `!`, as an operator, is prefix, so we know this isn't that.
1197 let (hi
, kind
) = if self.eat(&token
::Not
) {
1198 // MACRO INVOCATION expression
1201 args
: self.parse_mac_args()?
,
1202 prior_type_ascription
: self.last_type_ascription
,
1204 (self.prev_token
.span
, ExprKind
::MacCall(mac
))
1205 } else if self.check(&token
::OpenDelim(token
::Brace
)) {
1206 if let Some(expr
) = self.maybe_parse_struct_expr(&path
, &attrs
) {
1209 (path
.span
, ExprKind
::Path(None
, path
))
1212 (path
.span
, ExprKind
::Path(None
, path
))
1215 let expr
= self.mk_expr(lo
.to(hi
), kind
, attrs
);
1216 self.maybe_recover_from_bad_qpath(expr
, true)
1219 /// Parse `'label: $expr`. The label is already parsed.
1220 fn parse_labeled_expr(&mut self, label
: Label
, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1221 let lo
= label
.ident
.span
;
1222 let label
= Some(label
);
1223 let ate_colon
= self.eat(&token
::Colon
);
1224 let expr
= if self.eat_keyword(kw
::While
) {
1225 self.parse_while_expr(label
, lo
, attrs
)
1226 } else if self.eat_keyword(kw
::For
) {
1227 self.parse_for_expr(label
, lo
, attrs
)
1228 } else if self.eat_keyword(kw
::Loop
) {
1229 self.parse_loop_expr(label
, lo
, attrs
)
1230 } else if self.check(&token
::OpenDelim(token
::Brace
)) || self.token
.is_whole_block() {
1231 self.parse_block_expr(label
, lo
, BlockCheckMode
::Default
, attrs
)
1233 let msg
= "expected `while`, `for`, `loop` or `{` after a label";
1234 self.struct_span_err(self.token
.span
, msg
).span_label(self.token
.span
, msg
).emit();
1235 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1240 self.error_labeled_expr_must_be_followed_by_colon(lo
, expr
.span
);
1246 fn error_labeled_expr_must_be_followed_by_colon(&self, lo
: Span
, span
: Span
) {
1247 self.struct_span_err(span
, "labeled expression must be followed by `:`")
1248 .span_label(lo
, "the label")
1249 .span_suggestion_short(
1251 "add `:` after the label",
1253 Applicability
::MachineApplicable
,
1255 .note("labels are used before loops and blocks, allowing e.g., `break 'label` to them")
1259 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1260 fn recover_do_catch(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1261 let lo
= self.token
.span
;
1263 self.bump(); // `do`
1264 self.bump(); // `catch`
1266 let span_dc
= lo
.to(self.prev_token
.span
);
1267 self.struct_span_err(span_dc
, "found removed `do catch` syntax")
1270 "replace with the new syntax",
1272 Applicability
::MachineApplicable
,
1274 .note("following RFC #2388, the new non-placeholder syntax is `try`")
1277 self.parse_try_block(lo
, attrs
)
1280 /// Parse an expression if the token can begin one.
1281 fn parse_expr_opt(&mut self) -> PResult
<'a
, Option
<P
<Expr
>>> {
1282 Ok(if self.token
.can_begin_expr() { Some(self.parse_expr()?) }
else { None }
)
1285 /// Parse `"return" expr?`.
1286 fn parse_return_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1287 let lo
= self.prev_token
.span
;
1288 let kind
= ExprKind
::Ret(self.parse_expr_opt()?
);
1289 let expr
= self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
);
1290 self.maybe_recover_from_bad_qpath(expr
, true)
1293 /// Parse `"('label ":")? break expr?`.
1294 fn parse_break_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1295 let lo
= self.prev_token
.span
;
1296 let label
= self.eat_label();
1297 let kind
= if self.token
!= token
::OpenDelim(token
::Brace
)
1298 || !self.restrictions
.contains(Restrictions
::NO_STRUCT_LITERAL
)
1300 self.parse_expr_opt()?
1304 let expr
= self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::Break(label
, kind
), attrs
);
1305 self.maybe_recover_from_bad_qpath(expr
, true)
1308 /// Parse `"yield" expr?`.
1309 fn parse_yield_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1310 let lo
= self.prev_token
.span
;
1311 let kind
= ExprKind
::Yield(self.parse_expr_opt()?
);
1312 let span
= lo
.to(self.prev_token
.span
);
1313 self.sess
.gated_spans
.gate(sym
::generators
, span
);
1314 let expr
= self.mk_expr(span
, kind
, attrs
);
1315 self.maybe_recover_from_bad_qpath(expr
, true)
1318 /// Returns a string literal if the next token is a string literal.
1319 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1320 /// and returns `None` if the next token is not literal at all.
1321 pub fn parse_str_lit(&mut self) -> Result
<ast
::StrLit
, Option
<Lit
>> {
1322 match self.parse_opt_lit() {
1323 Some(lit
) => match lit
.kind
{
1324 ast
::LitKind
::Str(symbol_unescaped
, style
) => Ok(ast
::StrLit
{
1326 symbol
: lit
.token
.symbol
,
1327 suffix
: lit
.token
.suffix
,
1331 _
=> Err(Some(lit
)),
1337 pub(super) fn parse_lit(&mut self) -> PResult
<'a
, Lit
> {
1338 self.parse_opt_lit().ok_or_else(|| {
1339 let msg
= format
!("unexpected token: {}", super::token_descr(&self.token
));
1340 self.struct_span_err(self.token
.span
, &msg
)
1344 /// Matches `lit = true | false | token_lit`.
1345 /// Returns `None` if the next token is not a literal.
1346 pub(super) fn parse_opt_lit(&mut self) -> Option
<Lit
> {
1347 let mut recovered
= None
;
1348 if self.token
== token
::Dot
{
1349 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1350 // dot would follow an optional literal, so we do this unconditionally.
1351 recovered
= self.look_ahead(1, |next_token
| {
1352 if let token
::Literal(token
::Lit { kind: token::Integer, symbol, suffix }
) =
1355 if self.token
.span
.hi() == next_token
.span
.lo() {
1356 let s
= String
::from("0.") + &symbol
.as_str();
1357 let kind
= TokenKind
::lit(token
::Float
, Symbol
::intern(&s
), suffix
);
1358 return Some(Token
::new(kind
, self.token
.span
.to(next_token
.span
)));
1363 if let Some(token
) = &recovered
{
1365 self.error_float_lits_must_have_int_part(&token
);
1369 let token
= recovered
.as_ref().unwrap_or(&self.token
);
1370 match Lit
::from_token(token
) {
1375 Err(LitError
::NotLiteral
) => None
,
1377 let span
= token
.span
;
1378 let lit
= match token
.kind
{
1379 token
::Literal(lit
) => lit
,
1380 _
=> unreachable
!(),
1383 self.report_lit_error(err
, lit
, span
);
1384 // Pack possible quotes and prefixes from the original literal into
1385 // the error literal's symbol so they can be pretty-printed faithfully.
1386 let suffixless_lit
= token
::Lit
::new(lit
.kind
, lit
.symbol
, None
);
1387 let symbol
= Symbol
::intern(&suffixless_lit
.to_string());
1388 let lit
= token
::Lit
::new(token
::Err
, symbol
, lit
.suffix
);
1389 Some(Lit
::from_lit_token(lit
, span
).unwrap_or_else(|_
| unreachable
!()))
1394 fn error_float_lits_must_have_int_part(&self, token
: &Token
) {
1395 self.struct_span_err(token
.span
, "float literals must have an integer part")
1398 "must have an integer part",
1399 pprust
::token_to_string(token
),
1400 Applicability
::MachineApplicable
,
1405 fn report_lit_error(&self, err
: LitError
, lit
: token
::Lit
, span
: Span
) {
1406 // Checks if `s` looks like i32 or u1234 etc.
1407 fn looks_like_width_suffix(first_chars
: &[char], s
: &str) -> bool
{
1408 s
.len() > 1 && s
.starts_with(first_chars
) && s
[1..].chars().all(|c
| c
.is_ascii_digit())
1411 let token
::Lit { kind, suffix, .. }
= lit
;
1413 // `NotLiteral` is not an error by itself, so we don't report
1414 // it and give the parser opportunity to try something else.
1415 LitError
::NotLiteral
=> {}
1416 // `LexerError` *is* an error, but it was already reported
1417 // by lexer, so here we don't report it the second time.
1418 LitError
::LexerError
=> {}
1419 LitError
::InvalidSuffix
=> {
1420 self.expect_no_suffix(
1422 &format
!("{} {} literal", kind
.article(), kind
.descr()),
1426 LitError
::InvalidIntSuffix
=> {
1427 let suf
= suffix
.expect("suffix error with no suffix").as_str();
1428 if looks_like_width_suffix(&['i'
, 'u'
], &suf
) {
1429 // If it looks like a width, try to be helpful.
1430 let msg
= format
!("invalid width `{}` for integer literal", &suf
[1..]);
1431 self.struct_span_err(span
, &msg
)
1432 .help("valid widths are 8, 16, 32, 64 and 128")
1435 let msg
= format
!("invalid suffix `{}` for integer literal", suf
);
1436 self.struct_span_err(span
, &msg
)
1437 .span_label(span
, format
!("invalid suffix `{}`", suf
))
1438 .help("the suffix must be one of the integral types (`u32`, `isize`, etc)")
1442 LitError
::InvalidFloatSuffix
=> {
1443 let suf
= suffix
.expect("suffix error with no suffix").as_str();
1444 if looks_like_width_suffix(&['f'
], &suf
) {
1445 // If it looks like a width, try to be helpful.
1446 let msg
= format
!("invalid width `{}` for float literal", &suf
[1..]);
1447 self.struct_span_err(span
, &msg
).help("valid widths are 32 and 64").emit();
1449 let msg
= format
!("invalid suffix `{}` for float literal", suf
);
1450 self.struct_span_err(span
, &msg
)
1451 .span_label(span
, format
!("invalid suffix `{}`", suf
))
1452 .help("valid suffixes are `f32` and `f64`")
1456 LitError
::NonDecimalFloat(base
) => {
1457 let descr
= match base
{
1458 16 => "hexadecimal",
1461 _
=> unreachable
!(),
1463 self.struct_span_err(span
, &format
!("{} float literal is not supported", descr
))
1464 .span_label(span
, "not supported")
1467 LitError
::IntTooLarge
=> {
1468 self.struct_span_err(span
, "integer literal is too large").emit();
1473 pub(super) fn expect_no_suffix(&self, sp
: Span
, kind
: &str, suffix
: Option
<Symbol
>) {
1474 if let Some(suf
) = suffix
{
1475 let mut err
= if kind
== "a tuple index"
1476 && [sym
::i32, sym
::u32, sym
::isize, sym
::usize].contains(&suf
)
1478 // #59553: warn instead of reject out of hand to allow the fix to percolate
1479 // through the ecosystem when people fix their macros
1483 .struct_span_warn(sp
, &format
!("suffixes on {} are invalid", kind
));
1485 "`{}` is *temporarily* accepted on tuple index fields as it was \
1486 incorrectly accepted on stable for a few releases",
1490 "on proc macros, you'll want to use `syn::Index::from` or \
1491 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1492 to tuple field access",
1495 "see issue #60210 <https://github.com/rust-lang/rust/issues/60210> \
1496 for more information",
1500 self.struct_span_err(sp
, &format
!("suffixes on {} are invalid", kind
))
1502 err
.span_label(sp
, format
!("invalid suffix `{}`", suf
));
1507 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1508 /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
1509 pub fn parse_literal_maybe_minus(&mut self) -> PResult
<'a
, P
<Expr
>> {
1510 maybe_whole_expr
!(self);
1512 let lo
= self.token
.span
;
1513 let minus_present
= self.eat(&token
::BinOp(token
::Minus
));
1514 let lit
= self.parse_lit()?
;
1515 let expr
= self.mk_expr(lit
.span
, ExprKind
::Lit(lit
), AttrVec
::new());
1519 lo
.to(self.prev_token
.span
),
1520 self.mk_unary(UnOp
::Neg
, expr
),
1528 /// Parses a block or unsafe block.
1529 pub(super) fn parse_block_expr(
1531 opt_label
: Option
<Label
>,
1533 blk_mode
: BlockCheckMode
,
1535 ) -> PResult
<'a
, P
<Expr
>> {
1536 if let Some(label
) = opt_label
{
1537 self.sess
.gated_spans
.gate(sym
::label_break_value
, label
.ident
.span
);
1540 if self.token
.is_whole_block() {
1541 self.struct_span_err(self.token
.span
, "cannot use a `block` macro fragment here")
1542 .span_label(lo
.to(self.token
.span
), "the `block` fragment is within this context")
1546 let (inner_attrs
, blk
) = self.parse_block_common(lo
, blk_mode
)?
;
1547 attrs
.extend(inner_attrs
);
1548 Ok(self.mk_expr(blk
.span
, ExprKind
::Block(blk
, opt_label
), attrs
))
1551 /// Recover on an explicitly quantified closure expression, e.g., `for<'a> |x: &'a u8| *x + 1`.
1552 fn recover_quantified_closure_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1553 let lo
= self.token
.span
;
1554 let _
= self.parse_late_bound_lifetime_defs()?
;
1555 let span_for
= lo
.to(self.prev_token
.span
);
1556 let closure
= self.parse_closure_expr(attrs
)?
;
1558 self.struct_span_err(span_for
, "cannot introduce explicit parameters for a closure")
1559 .span_label(closure
.span
, "the parameters are attached to this closure")
1562 "remove the parameters",
1564 Applicability
::MachineApplicable
,
1568 Ok(self.mk_expr_err(lo
.to(closure
.span
)))
1571 /// Parses a closure expression (e.g., `move |args| expr`).
1572 fn parse_closure_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1573 let lo
= self.token
.span
;
1576 if self.eat_keyword(kw
::Static
) { Movability::Static }
else { Movability::Movable }
;
1578 let asyncness
= if self.token
.uninterpolated_span().rust_2018() {
1579 self.parse_asyncness()
1583 if let Async
::Yes { span, .. }
= asyncness
{
1584 // Feature-gate `async ||` closures.
1585 self.sess
.gated_spans
.gate(sym
::async_closure
, span
);
1588 let capture_clause
= self.parse_capture_clause();
1589 let decl
= self.parse_fn_block_decl()?
;
1590 let decl_hi
= self.prev_token
.span
;
1591 let body
= match decl
.output
{
1592 FnRetTy
::Default(_
) => {
1593 let restrictions
= self.restrictions
- Restrictions
::STMT_EXPR
;
1594 self.parse_expr_res(restrictions
, None
)?
1597 // If an explicit return type is given, require a block to appear (RFC 968).
1598 let body_lo
= self.token
.span
;
1599 self.parse_block_expr(None
, body_lo
, BlockCheckMode
::Default
, AttrVec
::new())?
1605 ExprKind
::Closure(capture_clause
, asyncness
, movability
, decl
, body
, lo
.to(decl_hi
)),
1610 /// Parses an optional `move` prefix to a closure-like construct.
1611 fn parse_capture_clause(&mut self) -> CaptureBy
{
1612 if self.eat_keyword(kw
::Move
) { CaptureBy::Value }
else { CaptureBy::Ref }
1615 /// Parses the `|arg, arg|` header of a closure.
1616 fn parse_fn_block_decl(&mut self) -> PResult
<'a
, P
<FnDecl
>> {
1617 let inputs
= if self.eat(&token
::OrOr
) {
1620 self.expect(&token
::BinOp(token
::Or
))?
;
1622 .parse_seq_to_before_tokens(
1623 &[&token
::BinOp(token
::Or
), &token
::OrOr
],
1624 SeqSep
::trailing_allowed(token
::Comma
),
1625 TokenExpectType
::NoExpect
,
1626 |p
| p
.parse_fn_block_param(),
1632 let output
= self.parse_ret_ty(AllowPlus
::Yes
, RecoverQPath
::Yes
)?
;
1634 Ok(P(FnDecl { inputs, output }
))
1637 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1638 fn parse_fn_block_param(&mut self) -> PResult
<'a
, Param
> {
1639 let lo
= self.token
.span
;
1640 let attrs
= self.parse_outer_attributes()?
;
1641 let pat
= self.parse_pat(PARAM_EXPECTED
)?
;
1642 let ty
= if self.eat(&token
::Colon
) {
1645 self.mk_ty(self.prev_token
.span
, TyKind
::Infer
)
1648 attrs
: attrs
.into(),
1651 span
: lo
.to(self.token
.span
),
1653 is_placeholder
: false,
1657 /// Parses an `if` expression (`if` token already eaten).
1658 fn parse_if_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1659 let lo
= self.prev_token
.span
;
1660 let cond
= self.parse_cond_expr()?
;
1662 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1663 // verify that the last statement is either an implicit return (no `;`) or an explicit
1664 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1665 // the dead code lint.
1666 let thn
= if self.eat_keyword(kw
::Else
) || !cond
.returns() {
1667 self.error_missing_if_cond(lo
, cond
.span
)
1669 let attrs
= self.parse_outer_attributes()?
; // For recovery.
1670 let not_block
= self.token
!= token
::OpenDelim(token
::Brace
);
1671 let block
= self.parse_block().map_err(|mut err
| {
1673 err
.span_label(lo
, "this `if` expression has a condition, but no block");
1674 if let ExprKind
::Binary(_
, _
, ref right
) = cond
.kind
{
1675 if let ExprKind
::Block(_
, _
) = right
.kind
{
1676 err
.help("maybe you forgot the right operand of the condition?");
1682 self.error_on_if_block_attrs(lo
, false, block
.span
, &attrs
);
1685 let els
= if self.eat_keyword(kw
::Else
) { Some(self.parse_else_expr()?) }
else { None }
;
1686 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::If(cond
, thn
, els
), attrs
))
1689 fn error_missing_if_cond(&self, lo
: Span
, span
: Span
) -> P
<ast
::Block
> {
1690 let sp
= self.sess
.source_map().next_point(lo
);
1691 self.struct_span_err(sp
, "missing condition for `if` expression")
1692 .span_label(sp
, "expected if condition here")
1694 self.mk_block_err(span
)
1697 /// Parses the condition of a `if` or `while` expression.
1698 fn parse_cond_expr(&mut self) -> PResult
<'a
, P
<Expr
>> {
1699 let cond
= self.parse_expr_res(Restrictions
::NO_STRUCT_LITERAL
, None
)?
;
1701 if let ExprKind
::Let(..) = cond
.kind
{
1702 // Remove the last feature gating of a `let` expression since it's stable.
1703 self.sess
.gated_spans
.ungate_last(sym
::let_chains
, cond
.span
);
1709 /// Parses a `let $pat = $expr` pseudo-expression.
1710 /// The `let` token has already been eaten.
1711 fn parse_let_expr(&mut self, attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1712 let lo
= self.prev_token
.span
;
1713 let pat
= self.parse_top_pat(GateOr
::No
)?
;
1714 self.expect(&token
::Eq
)?
;
1715 let expr
= self.with_res(Restrictions
::NO_STRUCT_LITERAL
, |this
| {
1716 this
.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None
.into())
1718 let span
= lo
.to(expr
.span
);
1719 self.sess
.gated_spans
.gate(sym
::let_chains
, span
);
1720 Ok(self.mk_expr(span
, ExprKind
::Let(pat
, expr
), attrs
))
1723 /// Parses an `else { ... }` expression (`else` token already eaten).
1724 fn parse_else_expr(&mut self) -> PResult
<'a
, P
<Expr
>> {
1725 let ctx_span
= self.prev_token
.span
; // `else`
1726 let attrs
= self.parse_outer_attributes()?
; // For recovery.
1727 let expr
= if self.eat_keyword(kw
::If
) {
1728 self.parse_if_expr(AttrVec
::new())?
1730 let blk
= self.parse_block()?
;
1731 self.mk_expr(blk
.span
, ExprKind
::Block(blk
, None
), AttrVec
::new())
1733 self.error_on_if_block_attrs(ctx_span
, true, expr
.span
, &attrs
);
1737 fn error_on_if_block_attrs(
1742 attrs
: &[ast
::Attribute
],
1744 let (span
, last
) = match attrs
{
1746 [x0 @ xn
] | [x0
, .., xn
] => (x0
.span
.to(xn
.span
), xn
.span
),
1748 let ctx
= if is_ctx_else { "else" }
else { "if" }
;
1749 self.struct_span_err(last
, "outer attributes are not allowed on `if` and `else` branches")
1750 .span_label(branch_span
, "the attributes are attached to this branch")
1751 .span_label(ctx_span
, format
!("the branch belongs to this `{}`", ctx
))
1754 "remove the attributes",
1756 Applicability
::MachineApplicable
,
1761 /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
1764 opt_label
: Option
<Label
>,
1767 ) -> PResult
<'a
, P
<Expr
>> {
1768 // Record whether we are about to parse `for (`.
1769 // This is used below for recovery in case of `for ( $stuff ) $block`
1770 // in which case we will suggest `for $stuff $block`.
1771 let begin_paren
= match self.token
.kind
{
1772 token
::OpenDelim(token
::Paren
) => Some(self.token
.span
),
1776 let pat
= self.parse_top_pat(GateOr
::Yes
)?
;
1777 if !self.eat_keyword(kw
::In
) {
1778 self.error_missing_in_for_loop();
1780 self.check_for_for_in_in_typo(self.prev_token
.span
);
1781 let expr
= self.parse_expr_res(Restrictions
::NO_STRUCT_LITERAL
, None
)?
;
1783 let pat
= self.recover_parens_around_for_head(pat
, &expr
, begin_paren
);
1785 let (iattrs
, loop_block
) = self.parse_inner_attrs_and_block()?
;
1786 attrs
.extend(iattrs
);
1788 let kind
= ExprKind
::ForLoop(pat
, expr
, loop_block
, opt_label
);
1789 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
))
1792 fn error_missing_in_for_loop(&mut self) {
1793 let (span
, msg
, sugg
) = if self.token
.is_ident_named(sym
::of
) {
1794 // Possibly using JS syntax (#75311).
1795 let span
= self.token
.span
;
1797 (span
, "try using `in` here instead", "in")
1799 (self.prev_token
.span
.between(self.token
.span
), "try adding `in` here", " in ")
1801 self.struct_span_err(span
, "missing `in` in `for` loop")
1802 .span_suggestion_short(
1806 // Has been misleading, at least in the past (closed Issue #48492).
1807 Applicability
::MaybeIncorrect
,
1812 /// Parses a `while` or `while let` expression (`while` token already eaten).
1813 fn parse_while_expr(
1815 opt_label
: Option
<Label
>,
1818 ) -> PResult
<'a
, P
<Expr
>> {
1819 let cond
= self.parse_cond_expr()?
;
1820 let (iattrs
, body
) = self.parse_inner_attrs_and_block()?
;
1821 attrs
.extend(iattrs
);
1822 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::While(cond
, body
, opt_label
), attrs
))
1825 /// Parses `loop { ... }` (`loop` token already eaten).
1828 opt_label
: Option
<Label
>,
1831 ) -> PResult
<'a
, P
<Expr
>> {
1832 let (iattrs
, body
) = self.parse_inner_attrs_and_block()?
;
1833 attrs
.extend(iattrs
);
1834 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), ExprKind
::Loop(body
, opt_label
), attrs
))
1837 fn eat_label(&mut self) -> Option
<Label
> {
1838 self.token
.lifetime().map(|ident
| {
1844 /// Parses a `match ... { ... }` expression (`match` token already eaten).
1845 fn parse_match_expr(&mut self, mut attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1846 let match_span
= self.prev_token
.span
;
1847 let lo
= self.prev_token
.span
;
1848 let scrutinee
= self.parse_expr_res(Restrictions
::NO_STRUCT_LITERAL
, None
)?
;
1849 if let Err(mut e
) = self.expect(&token
::OpenDelim(token
::Brace
)) {
1850 if self.token
== token
::Semi
{
1851 e
.span_suggestion_short(
1853 "try removing this `match`",
1855 Applicability
::MaybeIncorrect
, // speculative
1860 attrs
.extend(self.parse_inner_attributes()?
);
1862 let mut arms
: Vec
<Arm
> = Vec
::new();
1863 while self.token
!= token
::CloseDelim(token
::Brace
) {
1864 match self.parse_arm() {
1865 Ok(arm
) => arms
.push(arm
),
1867 // Recover by skipping to the end of the block.
1869 self.recover_stmt();
1870 let span
= lo
.to(self.token
.span
);
1871 if self.token
== token
::CloseDelim(token
::Brace
) {
1874 return Ok(self.mk_expr(span
, ExprKind
::Match(scrutinee
, arms
), attrs
));
1878 let hi
= self.token
.span
;
1880 Ok(self.mk_expr(lo
.to(hi
), ExprKind
::Match(scrutinee
, arms
), attrs
))
1883 pub(super) fn parse_arm(&mut self) -> PResult
<'a
, Arm
> {
1884 let attrs
= self.parse_outer_attributes()?
;
1885 let lo
= self.token
.span
;
1886 let pat
= self.parse_top_pat(GateOr
::No
)?
;
1887 let guard
= if self.eat_keyword(kw
::If
) {
1888 let if_span
= self.prev_token
.span
;
1889 let cond
= self.parse_expr()?
;
1890 if let ExprKind
::Let(..) = cond
.kind
{
1891 // Remove the last feature gating of a `let` expression since it's stable.
1892 self.sess
.gated_spans
.ungate_last(sym
::let_chains
, cond
.span
);
1893 let span
= if_span
.to(cond
.span
);
1894 self.sess
.gated_spans
.gate(sym
::if_let_guard
, span
);
1900 let arrow_span
= self.token
.span
;
1901 self.expect(&token
::FatArrow
)?
;
1902 let arm_start_span
= self.token
.span
;
1904 let expr
= self.parse_expr_res(Restrictions
::STMT_EXPR
, None
).map_err(|mut err
| {
1905 err
.span_label(arrow_span
, "while parsing the `match` arm starting here");
1909 let require_comma
= classify
::expr_requires_semi_to_be_stmt(&expr
)
1910 && self.token
!= token
::CloseDelim(token
::Brace
);
1912 let hi
= self.prev_token
.span
;
1915 let sm
= self.sess
.source_map();
1916 self.expect_one_of(&[token
::Comma
], &[token
::CloseDelim(token
::Brace
)]).map_err(
1918 match (sm
.span_to_lines(expr
.span
), sm
.span_to_lines(arm_start_span
)) {
1919 (Ok(ref expr_lines
), Ok(ref arm_start_lines
))
1920 if arm_start_lines
.lines
[0].end_col
== expr_lines
.lines
[0].end_col
1921 && expr_lines
.lines
.len() == 2
1922 && self.token
== token
::FatArrow
=>
1924 // We check whether there's any trailing code in the parse span,
1925 // if there isn't, we very likely have the following:
1928 // | -- - missing comma
1932 // | - ^^ self.token.span
1934 // | parsed until here as `"y" & X`
1935 err
.span_suggestion_short(
1936 arm_start_span
.shrink_to_hi(),
1937 "missing a comma here to end this `match` arm",
1939 Applicability
::MachineApplicable
,
1945 "while parsing the `match` arm starting here",
1953 self.eat(&token
::Comma
);
1963 is_placeholder
: false,
1967 /// Parses a `try {...}` expression (`try` token already eaten).
1968 fn parse_try_block(&mut self, span_lo
: Span
, mut attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
1969 let (iattrs
, body
) = self.parse_inner_attrs_and_block()?
;
1970 attrs
.extend(iattrs
);
1971 if self.eat_keyword(kw
::Catch
) {
1972 let mut error
= self.struct_span_err(
1973 self.prev_token
.span
,
1974 "keyword `catch` cannot follow a `try` block",
1976 error
.help("try using `match` on the result of the `try` block instead");
1980 let span
= span_lo
.to(body
.span
);
1981 self.sess
.gated_spans
.gate(sym
::try_blocks
, span
);
1982 Ok(self.mk_expr(span
, ExprKind
::TryBlock(body
), attrs
))
1986 fn is_do_catch_block(&self) -> bool
{
1987 self.token
.is_keyword(kw
::Do
)
1988 && self.is_keyword_ahead(1, &[kw
::Catch
])
1989 && self.look_ahead(2, |t
| *t
== token
::OpenDelim(token
::Brace
))
1990 && !self.restrictions
.contains(Restrictions
::NO_STRUCT_LITERAL
)
1993 fn is_try_block(&self) -> bool
{
1994 self.token
.is_keyword(kw
::Try
)
1995 && self.look_ahead(1, |t
| *t
== token
::OpenDelim(token
::Brace
))
1996 && self.token
.uninterpolated_span().rust_2018()
1999 /// Parses an `async move? {...}` expression.
2000 fn parse_async_block(&mut self, mut attrs
: AttrVec
) -> PResult
<'a
, P
<Expr
>> {
2001 let lo
= self.token
.span
;
2002 self.expect_keyword(kw
::Async
)?
;
2003 let capture_clause
= self.parse_capture_clause();
2004 let (iattrs
, body
) = self.parse_inner_attrs_and_block()?
;
2005 attrs
.extend(iattrs
);
2006 let kind
= ExprKind
::Async(capture_clause
, DUMMY_NODE_ID
, body
);
2007 Ok(self.mk_expr(lo
.to(self.prev_token
.span
), kind
, attrs
))
2010 fn is_async_block(&self) -> bool
{
2011 self.token
.is_keyword(kw
::Async
)
2014 self.is_keyword_ahead(1, &[kw
::Move
])
2015 && self.look_ahead(2, |t
| *t
== token
::OpenDelim(token
::Brace
))
2018 self.look_ahead(1, |t
| *t
== token
::OpenDelim(token
::Brace
))
2022 fn is_certainly_not_a_block(&self) -> bool
{
2023 self.look_ahead(1, |t
| t
.is_ident())
2025 // `{ ident, ` cannot start a block.
2026 self.look_ahead(2, |t
| t
== &token
::Comma
)
2027 || self.look_ahead(2, |t
| t
== &token
::Colon
)
2029 // `{ ident: token, ` cannot start a block.
2030 self.look_ahead(4, |t
| t
== &token
::Comma
) ||
2031 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
2032 self.look_ahead(3, |t
| !t
.can_begin_type())
2037 fn maybe_parse_struct_expr(
2041 ) -> Option
<PResult
<'a
, P
<Expr
>>> {
2042 let struct_allowed
= !self.restrictions
.contains(Restrictions
::NO_STRUCT_LITERAL
);
2043 if struct_allowed
|| self.is_certainly_not_a_block() {
2044 // This is a struct literal, but we don't can't accept them here.
2045 let expr
= self.parse_struct_expr(path
.clone(), attrs
.clone());
2046 if let (Ok(expr
), false) = (&expr
, struct_allowed
) {
2047 self.error_struct_lit_not_allowed_here(path
.span
, expr
.span
);
2054 fn error_struct_lit_not_allowed_here(&self, lo
: Span
, sp
: Span
) {
2055 self.struct_span_err(sp
, "struct literals are not allowed here")
2056 .multipart_suggestion(
2057 "surround the struct literal with parentheses",
2058 vec
![(lo
.shrink_to_lo(), "(".to_string()), (sp
.shrink_to_hi(), ")".to_string())],
2059 Applicability
::MachineApplicable
,
2064 pub(super) fn parse_struct_expr(
2068 ) -> PResult
<'a
, P
<Expr
>> {
2070 let mut fields
= Vec
::new();
2071 let mut base
= None
;
2072 let mut recover_async
= false;
2074 attrs
.extend(self.parse_inner_attributes()?
);
2076 let mut async_block_err
= |e
: &mut DiagnosticBuilder
<'_
>, span
: Span
| {
2077 recover_async
= true;
2078 e
.span_label(span
, "`async` blocks are only allowed in the 2018 edition");
2079 e
.help("set `edition = \"2018\"` in `Cargo.toml`");
2080 e
.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
2083 while self.token
!= token
::CloseDelim(token
::Brace
) {
2084 if self.eat(&token
::DotDot
) {
2085 let exp_span
= self.prev_token
.span
;
2086 match self.parse_expr() {
2087 Ok(e
) => base
= Some(e
),
2090 self.recover_stmt();
2093 self.recover_struct_comma_after_dotdot(exp_span
);
2097 let recovery_field
= self.find_struct_error_after_field_looking_code();
2098 let parsed_field
= match self.parse_field() {
2101 if pth
== kw
::Async
{
2102 async_block_err(&mut e
, pth
.span
);
2104 e
.span_label(pth
.span
, "while parsing this struct");
2108 // If the next token is a comma, then try to parse
2109 // what comes next as additional fields, rather than
2110 // bailing out until next `}`.
2111 if self.token
!= token
::Comma
{
2112 self.recover_stmt_(SemiColonMode
::Comma
, BlockMode
::Ignore
);
2113 if self.token
!= token
::Comma
{
2121 match self.expect_one_of(&[token
::Comma
], &[token
::CloseDelim(token
::Brace
)]) {
2123 if let Some(f
) = parsed_field
.or(recovery_field
) {
2124 // Only include the field if there's no parse error for the field name.
2129 if pth
== kw
::Async
{
2130 async_block_err(&mut e
, pth
.span
);
2132 e
.span_label(pth
.span
, "while parsing this struct");
2133 if let Some(f
) = recovery_field
{
2136 self.prev_token
.span
.shrink_to_hi(),
2137 "try adding a comma",
2139 Applicability
::MachineApplicable
,
2144 self.recover_stmt_(SemiColonMode
::Comma
, BlockMode
::Ignore
);
2145 self.eat(&token
::Comma
);
2150 let span
= pth
.span
.to(self.token
.span
);
2151 self.expect(&token
::CloseDelim(token
::Brace
))?
;
2152 let expr
= if recover_async { ExprKind::Err }
else { ExprKind::Struct(pth, fields, base) }
;
2153 Ok(self.mk_expr(span
, expr
, attrs
))
2156 /// Use in case of error after field-looking code: `S { foo: () with a }`.
2157 fn find_struct_error_after_field_looking_code(&self) -> Option
<Field
> {
2158 match self.token
.ident() {
2159 Some((ident
, is_raw
))
2160 if (is_raw
|| !ident
.is_reserved())
2161 && self.look_ahead(1, |t
| *t
== token
::Colon
) =>
2165 span
: self.token
.span
,
2166 expr
: self.mk_expr_err(self.token
.span
),
2167 is_shorthand
: false,
2168 attrs
: AttrVec
::new(),
2170 is_placeholder
: false,
2177 fn recover_struct_comma_after_dotdot(&mut self, span
: Span
) {
2178 if self.token
!= token
::Comma
{
2181 self.struct_span_err(
2182 span
.to(self.prev_token
.span
),
2183 "cannot use a comma after the base struct",
2185 .span_suggestion_short(
2187 "remove this comma",
2189 Applicability
::MachineApplicable
,
2191 .note("the base struct must always be the last field")
2193 self.recover_stmt();
2196 /// Parses `ident (COLON expr)?`.
2197 fn parse_field(&mut self) -> PResult
<'a
, Field
> {
2198 let attrs
= self.parse_outer_attributes()?
.into();
2199 let lo
= self.token
.span
;
2201 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2202 let is_shorthand
= !self.look_ahead(1, |t
| t
== &token
::Colon
|| t
== &token
::Eq
);
2203 let (ident
, expr
) = if is_shorthand
{
2204 // Mimic `x: x` for the `x` field shorthand.
2205 let ident
= self.parse_ident_common(false)?
;
2206 let path
= ast
::Path
::from_ident(ident
);
2207 (ident
, self.mk_expr(ident
.span
, ExprKind
::Path(None
, path
), AttrVec
::new()))
2209 let ident
= self.parse_field_name()?
;
2210 self.error_on_eq_field_init(ident
);
2212 (ident
, self.parse_expr()?
)
2216 span
: lo
.to(expr
.span
),
2221 is_placeholder
: false,
2225 /// Check for `=`. This means the source incorrectly attempts to
2226 /// initialize a field with an eq rather than a colon.
2227 fn error_on_eq_field_init(&self, field_name
: Ident
) {
2228 if self.token
!= token
::Eq
{
2232 self.struct_span_err(self.token
.span
, "expected `:`, found `=`")
2234 field_name
.span
.shrink_to_hi().to(self.token
.span
),
2235 "replace equals symbol with a colon",
2237 Applicability
::MachineApplicable
,
2242 fn err_dotdotdot_syntax(&self, span
: Span
) {
2243 self.struct_span_err(span
, "unexpected token: `...`")
2246 "use `..` for an exclusive range",
2248 Applicability
::MaybeIncorrect
,
2252 "or `..=` for an inclusive range",
2254 Applicability
::MaybeIncorrect
,
2259 fn err_larrow_operator(&self, span
: Span
) {
2260 self.struct_span_err(span
, "unexpected token: `<-`")
2263 "if you meant to write a comparison against a negative value, add a \
2264 space in between `<` and `-`",
2266 Applicability
::MaybeIncorrect
,
2271 fn mk_assign_op(&self, binop
: BinOp
, lhs
: P
<Expr
>, rhs
: P
<Expr
>) -> ExprKind
{
2272 ExprKind
::AssignOp(binop
, lhs
, rhs
)
2277 start
: Option
<P
<Expr
>>,
2278 end
: Option
<P
<Expr
>>,
2279 limits
: RangeLimits
,
2280 ) -> PResult
<'a
, ExprKind
> {
2281 if end
.is_none() && limits
== RangeLimits
::Closed
{
2282 self.error_inclusive_range_with_no_end(self.prev_token
.span
);
2285 Ok(ExprKind
::Range(start
, end
, limits
))
2289 fn mk_unary(&self, unop
: UnOp
, expr
: P
<Expr
>) -> ExprKind
{
2290 ExprKind
::Unary(unop
, expr
)
2293 fn mk_binary(&self, binop
: BinOp
, lhs
: P
<Expr
>, rhs
: P
<Expr
>) -> ExprKind
{
2294 ExprKind
::Binary(binop
, lhs
, rhs
)
2297 fn mk_index(&self, expr
: P
<Expr
>, idx
: P
<Expr
>) -> ExprKind
{
2298 ExprKind
::Index(expr
, idx
)
2301 fn mk_call(&self, f
: P
<Expr
>, args
: Vec
<P
<Expr
>>) -> ExprKind
{
2302 ExprKind
::Call(f
, args
)
2305 fn mk_await_expr(&mut self, self_arg
: P
<Expr
>, lo
: Span
) -> PResult
<'a
, P
<Expr
>> {
2306 let span
= lo
.to(self.prev_token
.span
);
2307 let await_expr
= self.mk_expr(span
, ExprKind
::Await(self_arg
), AttrVec
::new());
2308 self.recover_from_await_method_call();
2312 crate fn mk_expr(&self, span
: Span
, kind
: ExprKind
, attrs
: AttrVec
) -> P
<Expr
> {
2313 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None }
)
2316 pub(super) fn mk_expr_err(&self, span
: Span
) -> P
<Expr
> {
2317 self.mk_expr(span
, ExprKind
::Err
, AttrVec
::new())