1 use super::{Parser, PResult, Restrictions, PrevTokenKind, TokenType, PathStyle, BlockMode}
;
2 use super::{SemiColonMode, SeqSep, TokenExpectType}
;
3 use super::pat
::{GateOr, PARAM_EXPECTED}
;
4 use super::diagnostics
::Error
;
6 use crate::parse
::literal
::LitError
;
9 self, DUMMY_NODE_ID
, Attribute
, AttrStyle
, Ident
, CaptureBy
, BlockCheckMode
,
10 Expr
, ExprKind
, RangeLimits
, Label
, Movability
, IsAsync
, Arm
, Ty
, TyKind
,
11 FunctionRetTy
, Param
, FnDecl
, BinOpKind
, BinOp
, UnOp
, Mac
, AnonConst
, Field
, Lit
,
13 use crate::maybe_recover_from_interpolated_ty_qpath
;
14 use crate::parse
::classify
;
15 use crate::parse
::token
::{self, Token, TokenKind}
;
16 use crate::print
::pprust
;
18 use crate::source_map
::{self, Span}
;
19 use crate::symbol
::{kw, sym}
;
20 use crate::util
::parser
::{AssocOp, Fixity, prec_let_scrutinee_needs_par}
;
22 use errors
::Applicability
;
23 use syntax_pos
::Symbol
;
25 use rustc_data_structures
::thin_vec
::ThinVec
;
27 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
28 /// dropped into the token stream, which happens while parsing the result of
29 /// macro expansion). Placement of these is not as complex as I feared it would
30 /// be. The important thing is to make sure that lookahead doesn't balk at
31 /// `token::Interpolated` tokens.
32 macro_rules
! maybe_whole_expr
{
34 if let token
::Interpolated(nt
) = &$p
.token
.kind
{
36 token
::NtExpr(e
) | token
::NtLiteral(e
) => {
41 token
::NtPath(path
) => {
42 let path
= path
.clone();
45 $p
.token
.span
, ExprKind
::Path(None
, path
), ThinVec
::new()
48 token
::NtBlock(block
) => {
49 let block
= block
.clone();
52 $p
.token
.span
, ExprKind
::Block(block
, None
), ThinVec
::new()
55 // N.B., `NtIdent(ident)` is normalized to `Ident` in `fn bump`.
63 pub(super) enum LhsExpr
{
65 AttributesParsed(ThinVec
<Attribute
>),
66 AlreadyParsed(P
<Expr
>),
69 impl From
<Option
<ThinVec
<Attribute
>>> 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
<ThinVec
<Attribute
>>) -> Self {
75 if let Some(attrs
) = o
{
76 LhsExpr
::AttributesParsed(attrs
)
83 impl From
<P
<Expr
>> for LhsExpr
{
84 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
86 /// This conversion does not allocate.
87 fn from(expr
: P
<Expr
>) -> Self {
88 LhsExpr
::AlreadyParsed(expr
)
93 /// Parses an expression.
95 pub fn parse_expr(&mut self) -> PResult
<'a
, P
<Expr
>> {
96 self.parse_expr_res(Restrictions
::empty(), None
)
99 fn parse_paren_expr_seq(&mut self) -> PResult
<'a
, Vec
<P
<Expr
>>> {
100 self.parse_paren_comma_seq(|p
| {
101 match p
.parse_expr() {
102 Ok(expr
) => Ok(expr
),
103 Err(mut err
) => match p
.token
.kind
{
104 token
::Ident(name
, false)
105 if name
== kw
::Underscore
&& p
.look_ahead(1, |t
| {
108 // Special-case handling of `foo(_, _, _)`
110 let sp
= p
.token
.span
;
112 Ok(p
.mk_expr(sp
, ExprKind
::Err
, ThinVec
::new()))
120 /// Parses an expression, subject to the given restrictions.
122 pub(super) fn parse_expr_res(
125 already_parsed_attrs
: Option
<ThinVec
<Attribute
>>
126 ) -> PResult
<'a
, P
<Expr
>> {
127 self.with_res(r
, |this
| this
.parse_assoc_expr(already_parsed_attrs
))
130 /// Parses an associative expression.
132 /// This parses an expression accounting for associativity and precedence of the operators in
137 already_parsed_attrs
: Option
<ThinVec
<Attribute
>>,
138 ) -> PResult
<'a
, P
<Expr
>> {
139 self.parse_assoc_expr_with(0, already_parsed_attrs
.into())
142 /// Parses an associative expression with operators of at least `min_prec` precedence.
143 pub(super) fn parse_assoc_expr_with(
147 ) -> PResult
<'a
, P
<Expr
>> {
148 let mut lhs
= if let LhsExpr
::AlreadyParsed(expr
) = lhs
{
151 let attrs
= match lhs
{
152 LhsExpr
::AttributesParsed(attrs
) => Some(attrs
),
155 if [token
::DotDot
, token
::DotDotDot
, token
::DotDotEq
].contains(&self.token
.kind
) {
156 return self.parse_prefix_range_expr(attrs
);
158 self.parse_prefix_expr(attrs
)?
161 let last_type_ascription_set
= self.last_type_ascription
.is_some();
163 match (self.expr_is_complete(&lhs
), AssocOp
::from_token(&self.token
)) {
165 self.last_type_ascription
= None
;
166 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
169 (false, _
) => {}
// continue parsing the expression
170 // An exhaustive check is done in the following block, but these are checked first
171 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
172 // want to keep their span info to improve diagnostics in these cases in a later stage.
173 (true, Some(AssocOp
::Multiply
)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
174 (true, Some(AssocOp
::Subtract
)) | // `{ 42 } -5`
175 (true, Some(AssocOp
::LAnd
)) | // `{ 42 } &&x` (#61475)
176 (true, Some(AssocOp
::Add
)) // `{ 42 } + 42
177 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
178 // `if x { a } else { b } && if y { c } else { d }`
179 if !self.look_ahead(1, |t
| t
.is_reserved_ident()) => {
180 self.last_type_ascription
= None
;
181 // These cases are ambiguous and can't be identified in the parser alone
182 let sp
= self.sess
.source_map().start_point(self.token
.span
);
183 self.sess
.ambiguous_block_expr_parse
.borrow_mut().insert(sp
, lhs
.span
);
186 (true, Some(ref op
)) if !op
.can_continue_expr_unambiguously() => {
187 self.last_type_ascription
= None
;
191 // We've found an expression that would be parsed as a statement, but the next
192 // token implies this should be parsed as an expression.
193 // For example: `if let Some(x) = x { x } else { 0 } / 2`
194 let mut err
= self.struct_span_err(self.token
.span
, &format
!(
195 "expected expression, found `{}`",
196 pprust
::token_to_string(&self.token
),
198 err
.span_label(self.token
.span
, "expected expression");
199 self.sess
.expr_parentheses_needed(
202 Some(pprust
::expr_to_string(&lhs
),
207 self.expected_tokens
.push(TokenType
::Operator
);
208 while let Some(op
) = AssocOp
::from_token(&self.token
) {
210 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
211 // it refers to. Interpolated identifiers are unwrapped early and never show up here
212 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
213 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
214 let lhs_span
= match (self.prev_token_kind
, &lhs
.kind
) {
215 (PrevTokenKind
::Interpolated
, _
) => self.prev_span
,
216 (PrevTokenKind
::Ident
, &ExprKind
::Path(None
, ref path
))
217 if path
.segments
.len() == 1 => self.prev_span
,
221 let cur_op_span
= self.token
.span
;
222 let restrictions
= if op
.is_assign_like() {
223 self.restrictions
& Restrictions
::NO_STRUCT_LITERAL
227 let prec
= op
.precedence();
231 // Check for deprecated `...` syntax
232 if self.token
== token
::DotDotDot
&& op
== AssocOp
::DotDotEq
{
233 self.err_dotdotdot_syntax(self.token
.span
);
236 if self.token
== token
::LArrow
{
237 self.err_larrow_operator(self.token
.span
);
241 if op
.is_comparison() {
242 if let Some(expr
) = self.check_no_chained_comparison(&lhs
, &op
)?
{
247 if op
== AssocOp
::As
{
248 lhs
= self.parse_assoc_op_cast(lhs
, lhs_span
, ExprKind
::Cast
)?
;
250 } else if op
== AssocOp
::Colon
{
251 let maybe_path
= self.could_ascription_be_path(&lhs
.kind
);
252 self.last_type_ascription
= Some((self.prev_span
, maybe_path
));
254 lhs
= self.parse_assoc_op_cast(lhs
, lhs_span
, ExprKind
::Type
)?
;
255 self.sess
.gated_spans
.type_ascription
.borrow_mut().push(lhs
.span
);
257 } else if op
== AssocOp
::DotDot
|| op
== AssocOp
::DotDotEq
{
258 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
259 // generalise it to the Fixity::None code.
261 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
262 // two variants are handled with `parse_prefix_range_expr` call above.
263 let rhs
= if self.is_at_start_of_range_notation_rhs() {
264 Some(self.parse_assoc_expr_with(prec
+ 1, LhsExpr
::NotYetParsed
)?
)
268 let (lhs_span
, rhs_span
) = (lhs
.span
, if let Some(ref x
) = rhs
{
273 let limits
= if op
== AssocOp
::DotDot
{
274 RangeLimits
::HalfOpen
279 let r
= self.mk_range(Some(lhs
), rhs
, limits
)?
;
280 lhs
= self.mk_expr(lhs_span
.to(rhs_span
), r
, ThinVec
::new());
284 let fixity
= op
.fixity();
285 let prec_adjustment
= match fixity
{
288 // We currently have no non-associative operators that are not handled above by
289 // the special cases. The code is here only for future convenience.
292 let rhs
= self.with_res(
293 restrictions
- Restrictions
::STMT_EXPR
,
294 |this
| this
.parse_assoc_expr_with(prec
+ prec_adjustment
, LhsExpr
::NotYetParsed
)
297 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
298 // including the attributes.
302 .filter(|a
| a
.style
== AttrStyle
::Outer
)
304 .map_or(lhs_span
, |a
| a
.span
);
305 let span
= lhs_span
.to(rhs
.span
);
307 AssocOp
::Add
| AssocOp
::Subtract
| AssocOp
::Multiply
| AssocOp
::Divide
|
308 AssocOp
::Modulus
| AssocOp
::LAnd
| AssocOp
::LOr
| AssocOp
::BitXor
|
309 AssocOp
::BitAnd
| AssocOp
::BitOr
| AssocOp
::ShiftLeft
| AssocOp
::ShiftRight
|
310 AssocOp
::Equal
| AssocOp
::Less
| AssocOp
::LessEqual
| AssocOp
::NotEqual
|
311 AssocOp
::Greater
| AssocOp
::GreaterEqual
=> {
312 let ast_op
= op
.to_ast_binop().unwrap();
313 let binary
= self.mk_binary(source_map
::respan(cur_op_span
, ast_op
), lhs
, rhs
);
314 self.mk_expr(span
, binary
, ThinVec
::new())
316 AssocOp
::Assign
=> self.mk_expr(span
, ExprKind
::Assign(lhs
, rhs
), ThinVec
::new()),
317 AssocOp
::AssignOp(k
) => {
319 token
::Plus
=> BinOpKind
::Add
,
320 token
::Minus
=> BinOpKind
::Sub
,
321 token
::Star
=> BinOpKind
::Mul
,
322 token
::Slash
=> BinOpKind
::Div
,
323 token
::Percent
=> BinOpKind
::Rem
,
324 token
::Caret
=> BinOpKind
::BitXor
,
325 token
::And
=> BinOpKind
::BitAnd
,
326 token
::Or
=> BinOpKind
::BitOr
,
327 token
::Shl
=> BinOpKind
::Shl
,
328 token
::Shr
=> BinOpKind
::Shr
,
330 let aopexpr
= self.mk_assign_op(source_map
::respan(cur_op_span
, aop
), lhs
, rhs
);
331 self.mk_expr(span
, aopexpr
, ThinVec
::new())
333 AssocOp
::As
| AssocOp
::Colon
| AssocOp
::DotDot
| AssocOp
::DotDotEq
=> {
334 self.bug("AssocOp should have been handled by special case")
338 if let Fixity
::None
= fixity { break }
340 if last_type_ascription_set
{
341 self.last_type_ascription
= None
;
346 /// Checks if this expression is a successfully parsed statement.
347 fn expr_is_complete(&self, e
: &Expr
) -> bool
{
348 self.restrictions
.contains(Restrictions
::STMT_EXPR
) &&
349 !classify
::expr_requires_semi_to_be_stmt(e
)
352 fn is_at_start_of_range_notation_rhs(&self) -> bool
{
353 if self.token
.can_begin_expr() {
354 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
355 if self.token
== token
::OpenDelim(token
::Brace
) {
356 return !self.restrictions
.contains(Restrictions
::NO_STRUCT_LITERAL
);
364 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
365 fn parse_prefix_range_expr(
367 already_parsed_attrs
: Option
<ThinVec
<Attribute
>>
368 ) -> PResult
<'a
, P
<Expr
>> {
369 // Check for deprecated `...` syntax.
370 if self.token
== token
::DotDotDot
{
371 self.err_dotdotdot_syntax(self.token
.span
);
374 debug_assert
!([token
::DotDot
, token
::DotDotDot
, token
::DotDotEq
].contains(&self.token
.kind
),
375 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
377 let tok
= self.token
.clone();
378 let attrs
= self.parse_or_use_outer_attributes(already_parsed_attrs
)?
;
379 let lo
= self.token
.span
;
380 let mut hi
= self.token
.span
;
382 let opt_end
= if self.is_at_start_of_range_notation_rhs() {
383 // RHS must be parsed with more associativity than the dots.
384 let next_prec
= AssocOp
::from_token(&tok
).unwrap().precedence() + 1;
385 Some(self.parse_assoc_expr_with(next_prec
, LhsExpr
::NotYetParsed
)
393 let limits
= if tok
== token
::DotDot
{
394 RangeLimits
::HalfOpen
399 let r
= self.mk_range(None
, opt_end
, limits
)?
;
400 Ok(self.mk_expr(lo
.to(hi
), r
, attrs
))
403 /// Parses a prefix-unary-operator expr.
404 fn parse_prefix_expr(
406 already_parsed_attrs
: Option
<ThinVec
<Attribute
>>
407 ) -> PResult
<'a
, P
<Expr
>> {
408 let attrs
= self.parse_or_use_outer_attributes(already_parsed_attrs
)?
;
409 let lo
= self.token
.span
;
410 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
411 let (hi
, ex
) = match self.token
.kind
{
414 let e
= self.parse_prefix_expr(None
);
415 let (span
, e
) = self.interpolated_or_expr_span(e
)?
;
416 (lo
.to(span
), self.mk_unary(UnOp
::Not
, e
))
418 // Suggest `!` for bitwise negation when encountering a `~`
421 let e
= self.parse_prefix_expr(None
);
422 let (span
, e
) = self.interpolated_or_expr_span(e
)?
;
423 let span_of_tilde
= lo
;
424 self.struct_span_err(span_of_tilde
, "`~` cannot be used as a unary operator")
425 .span_suggestion_short(
427 "use `!` to perform bitwise not",
429 Applicability
::MachineApplicable
432 (lo
.to(span
), self.mk_unary(UnOp
::Not
, e
))
434 token
::BinOp(token
::Minus
) => {
436 let e
= self.parse_prefix_expr(None
);
437 let (span
, e
) = self.interpolated_or_expr_span(e
)?
;
438 (lo
.to(span
), self.mk_unary(UnOp
::Neg
, e
))
440 token
::BinOp(token
::Star
) => {
442 let e
= self.parse_prefix_expr(None
);
443 let (span
, e
) = self.interpolated_or_expr_span(e
)?
;
444 (lo
.to(span
), self.mk_unary(UnOp
::Deref
, e
))
446 token
::BinOp(token
::And
) | token
::AndAnd
=> {
448 let m
= self.parse_mutability();
449 let e
= self.parse_prefix_expr(None
);
450 let (span
, e
) = self.interpolated_or_expr_span(e
)?
;
451 (lo
.to(span
), ExprKind
::AddrOf(m
, e
))
453 token
::Ident(..) if self.token
.is_keyword(kw
::Box
) => {
455 let e
= self.parse_prefix_expr(None
);
456 let (span
, e
) = self.interpolated_or_expr_span(e
)?
;
457 let span
= lo
.to(span
);
458 self.sess
.gated_spans
.box_syntax
.borrow_mut().push(span
);
459 (span
, ExprKind
::Box(e
))
461 token
::Ident(..) if self.token
.is_ident_named(sym
::not
) => {
462 // `not` is just an ordinary identifier in Rust-the-language,
463 // but as `rustc`-the-compiler, we can issue clever diagnostics
464 // for confused users who really want to say `!`
465 let token_cannot_continue_expr
= |t
: &Token
| match t
.kind
{
466 // These tokens can start an expression after `!`, but
467 // can't continue an expression after an ident
468 token
::Ident(name
, is_raw
) => token
::ident_can_begin_expr(name
, t
.span
, is_raw
),
469 token
::Literal(..) | token
::Pound
=> true,
470 _
=> t
.is_whole_expr(),
472 let cannot_continue_expr
= self.look_ahead(1, token_cannot_continue_expr
);
473 if cannot_continue_expr
{
475 // Emit the error ...
476 self.struct_span_err(
478 &format
!("unexpected {} after identifier",self.this_token_descr())
480 .span_suggestion_short(
481 // Span the `not` plus trailing whitespace to avoid
482 // trailing whitespace after the `!` in our suggestion
483 self.sess
.source_map()
484 .span_until_non_whitespace(lo
.to(self.token
.span
)),
485 "use `!` to perform logical negation",
487 Applicability
::MachineApplicable
490 // —and recover! (just as if we were in the block
491 // for the `token::Not` arm)
492 let e
= self.parse_prefix_expr(None
);
493 let (span
, e
) = self.interpolated_or_expr_span(e
)?
;
494 (lo
.to(span
), self.mk_unary(UnOp
::Not
, e
))
496 return self.parse_dot_or_call_expr(Some(attrs
));
499 _
=> { return self.parse_dot_or_call_expr(Some(attrs)); }
501 return Ok(self.mk_expr(lo
.to(hi
), ex
, attrs
));
504 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
505 fn interpolated_or_expr_span(
507 expr
: PResult
<'a
, P
<Expr
>>,
508 ) -> PResult
<'a
, (Span
, P
<Expr
>)> {
510 if self.prev_token_kind
== PrevTokenKind
::Interpolated
{
518 fn parse_assoc_op_cast(&mut self, lhs
: P
<Expr
>, lhs_span
: Span
,
519 expr_kind
: fn(P
<Expr
>, P
<Ty
>) -> ExprKind
)
520 -> PResult
<'a
, P
<Expr
>> {
521 let mk_expr
= |this
: &mut Self, rhs
: P
<Ty
>| {
522 this
.mk_expr(lhs_span
.to(rhs
.span
), expr_kind(lhs
, rhs
), ThinVec
::new())
525 // Save the state of the parser before parsing type normally, in case there is a
526 // LessThan comparison after this cast.
527 let parser_snapshot_before_type
= self.clone();
528 match self.parse_ty_no_plus() {
530 Ok(mk_expr(self, rhs
))
532 Err(mut type_err
) => {
533 // Rewind to before attempting to parse the type with generics, to recover
534 // from situations like `x as usize < y` in which we first tried to parse
535 // `usize < y` as a type with generic arguments.
536 let parser_snapshot_after_type
= self.clone();
537 mem
::replace(self, parser_snapshot_before_type
);
539 match self.parse_path(PathStyle
::Expr
) {
541 let (op_noun
, op_verb
) = match self.token
.kind
{
542 token
::Lt
=> ("comparison", "comparing"),
543 token
::BinOp(token
::Shl
) => ("shift", "shifting"),
545 // We can end up here even without `<` being the next token, for
546 // example because `parse_ty_no_plus` returns `Err` on keywords,
547 // but `parse_path` returns `Ok` on them due to error recovery.
548 // Return original error and parser state.
549 mem
::replace(self, parser_snapshot_after_type
);
550 return Err(type_err
);
554 // Successfully parsed the type path leaving a `<` yet to parse.
557 // Report non-fatal diagnostics, keep `x as usize` as an expression
558 // in AST and continue parsing.
560 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
561 pprust
::path_to_string(&path
),
564 let span_after_type
= parser_snapshot_after_type
.token
.span
;
565 let expr
= mk_expr(self, P(Ty
{
567 kind
: TyKind
::Path(None
, path
),
571 let expr_str
= self.span_to_snippet(expr
.span
)
572 .unwrap_or_else(|_
| pprust
::expr_to_string(&expr
));
574 self.struct_span_err(self.token
.span
, &msg
)
576 self.look_ahead(1, |t
| t
.span
).to(span_after_type
),
577 "interpreted as generic arguments"
579 .span_label(self.token
.span
, format
!("not interpreted as {}", op_noun
))
582 &format
!("try {} the cast value", op_verb
),
583 format
!("({})", expr_str
),
584 Applicability
::MachineApplicable
,
590 Err(mut path_err
) => {
591 // Couldn't parse as a path, return original error and parser state.
593 mem
::replace(self, parser_snapshot_after_type
);
601 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
602 fn parse_dot_or_call_expr(
604 already_parsed_attrs
: Option
<ThinVec
<Attribute
>>,
605 ) -> PResult
<'a
, P
<Expr
>> {
606 let attrs
= self.parse_or_use_outer_attributes(already_parsed_attrs
)?
;
608 let b
= self.parse_bottom_expr();
609 let (span
, b
) = self.interpolated_or_expr_span(b
)?
;
610 self.parse_dot_or_call_expr_with(b
, span
, attrs
)
613 pub(super) fn parse_dot_or_call_expr_with(
617 mut attrs
: ThinVec
<Attribute
>,
618 ) -> PResult
<'a
, P
<Expr
>> {
619 // Stitch the list of outer attributes onto the return value.
620 // A little bit ugly, but the best way given the current code
622 self.parse_dot_or_call_expr_with_(e0
, lo
).map(|expr
|
623 expr
.map(|mut expr
| {
624 attrs
.extend
::<Vec
<_
>>(expr
.attrs
.into());
627 ExprKind
::If(..) if !expr
.attrs
.is_empty() => {
628 // Just point to the first attribute in there...
629 let span
= expr
.attrs
[0].span
;
630 self.span_err(span
, "attributes are not yet allowed on `if` expressions");
639 fn parse_dot_or_call_expr_with_(&mut self, e0
: P
<Expr
>, lo
: Span
) -> PResult
<'a
, P
<Expr
>> {
644 while self.eat(&token
::Question
) {
645 let hi
= self.prev_span
;
646 e
= self.mk_expr(lo
.to(hi
), ExprKind
::Try(e
), ThinVec
::new());
650 if self.eat(&token
::Dot
) {
651 match self.token
.kind
{
652 token
::Ident(..) => {
653 e
= self.parse_dot_suffix(e
, lo
)?
;
655 token
::Literal(token
::Lit { kind: token::Integer, symbol, suffix }
) => {
656 let span
= self.token
.span
;
658 let field
= ExprKind
::Field(e
, Ident
::new(symbol
, span
));
659 e
= self.mk_expr(lo
.to(span
), field
, ThinVec
::new());
661 self.expect_no_suffix(span
, "a tuple index", suffix
);
663 token
::Literal(token
::Lit { kind: token::Float, symbol, .. }
) => {
665 let fstr
= symbol
.as_str();
666 let msg
= format
!("unexpected token: `{}`", symbol
);
667 let mut err
= self.diagnostic().struct_span_err(self.prev_span
, &msg
);
668 err
.span_label(self.prev_span
, "unexpected token");
669 if fstr
.chars().all(|x
| "0123456789.".contains(x
)) {
670 let float
= match fstr
.parse
::<f64>().ok() {
674 let sugg
= pprust
::to_string(|s
| {
678 s
.print_usize(float
.trunc() as usize);
681 s
.s
.word(fstr
.splitn(2, ".").last().unwrap().to_string())
684 lo
.to(self.prev_span
),
685 "try parenthesizing the first index",
687 Applicability
::MachineApplicable
694 // FIXME Could factor this out into non_fatal_unexpected or something.
695 let actual
= self.this_token_to_string();
696 self.span_err(self.token
.span
, &format
!("unexpected token: `{}`", actual
));
701 if self.expr_is_complete(&e
) { break; }
702 match self.token
.kind
{
704 token
::OpenDelim(token
::Paren
) => {
705 let seq
= self.parse_paren_expr_seq().map(|es
| {
706 let nd
= self.mk_call(e
, es
);
707 let hi
= self.prev_span
;
708 self.mk_expr(lo
.to(hi
), nd
, ThinVec
::new())
710 e
= self.recover_seq_parse_error(token
::Paren
, lo
, seq
);
714 // Could be either an index expression or a slicing expression.
715 token
::OpenDelim(token
::Bracket
) => {
717 let ix
= self.parse_expr()?
;
718 hi
= self.token
.span
;
719 self.expect(&token
::CloseDelim(token
::Bracket
))?
;
720 let index
= self.mk_index(e
, ix
);
721 e
= self.mk_expr(lo
.to(hi
), index
, ThinVec
::new())
729 /// Assuming we have just parsed `.`, continue parsing into an expression.
730 fn parse_dot_suffix(&mut self, self_arg
: P
<Expr
>, lo
: Span
) -> PResult
<'a
, P
<Expr
>> {
731 if self.token
.span
.rust_2018() && self.eat_keyword(kw
::Await
) {
732 return self.mk_await_expr(self_arg
, lo
);
735 let segment
= self.parse_path_segment(PathStyle
::Expr
)?
;
736 self.check_trailing_angle_brackets(&segment
, token
::OpenDelim(token
::Paren
));
738 Ok(match self.token
.kind
{
739 token
::OpenDelim(token
::Paren
) => {
740 // Method call `expr.f()`
741 let mut args
= self.parse_paren_expr_seq()?
;
742 args
.insert(0, self_arg
);
744 let span
= lo
.to(self.prev_span
);
745 self.mk_expr(span
, ExprKind
::MethodCall(segment
, args
), ThinVec
::new())
748 // Field access `expr.f`
749 if let Some(args
) = segment
.args
{
750 self.span_err(args
.span(),
751 "field expressions may not have generic arguments");
754 let span
= lo
.to(self.prev_span
);
755 self.mk_expr(span
, ExprKind
::Field(self_arg
, segment
.ident
), ThinVec
::new())
760 /// At the bottom (top?) of the precedence hierarchy,
761 /// Parses things like parenthesized exprs, macros, `return`, etc.
763 /// N.B., this does not parse outer attributes, and is private because it only works
764 /// correctly if called from `parse_dot_or_call_expr()`.
765 fn parse_bottom_expr(&mut self) -> PResult
<'a
, P
<Expr
>> {
766 maybe_recover_from_interpolated_ty_qpath
!(self, true);
767 maybe_whole_expr
!(self);
769 // Outer attributes are already parsed and will be
770 // added to the return value after the fact.
772 // Therefore, prevent sub-parser from parsing
773 // attributes by giving them a empty "already-parsed" list.
774 let mut attrs
= ThinVec
::new();
776 let lo
= self.token
.span
;
777 let mut hi
= self.token
.span
;
781 macro_rules
! parse_lit
{
783 match self.parse_lit() {
786 ex
= ExprKind
::Lit(literal
);
790 return Err(self.expected_expression_found());
796 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
797 match self.token
.kind
{
798 // This match arm is a special-case of the `_` match arm below and
799 // could be removed without changing functionality, but it's faster
800 // to have it here, especially for programs with large constants.
801 token
::Literal(_
) => {
804 token
::OpenDelim(token
::Paren
) => {
807 attrs
.extend(self.parse_inner_attributes()?
);
809 // `(e)` is parenthesized `e`.
810 // `(e,)` is a tuple with only one field, `e`.
812 let mut trailing_comma
= false;
813 let mut recovered
= false;
814 while self.token
!= token
::CloseDelim(token
::Paren
) {
815 es
.push(match self.parse_expr() {
818 // Recover from parse error in tuple list.
819 match self.token
.kind
{
820 token
::Ident(name
, false)
821 if name
== kw
::Underscore
&& self.look_ahead(1, |t
| {
824 // Special-case handling of `Foo<(_, _, _)>`
826 let sp
= self.token
.span
;
828 self.mk_expr(sp
, ExprKind
::Err
, ThinVec
::new())
831 self.recover_seq_parse_error(token
::Paren
, lo
, Err(err
)),
836 recovered
= self.expect_one_of(
838 &[token
::Comma
, token
::CloseDelim(token
::Paren
)],
840 if self.eat(&token
::Comma
) {
841 trailing_comma
= true;
843 trailing_comma
= false;
852 ex
= if es
.len() == 1 && !trailing_comma
{
853 ExprKind
::Paren(es
.into_iter().nth(0).unwrap())
858 token
::OpenDelim(token
::Brace
) => {
859 return self.parse_block_expr(None
, lo
, BlockCheckMode
::Default
, attrs
);
861 token
::BinOp(token
::Or
) | token
::OrOr
=> {
862 return self.parse_closure_expr(attrs
);
864 token
::OpenDelim(token
::Bracket
) => {
867 attrs
.extend(self.parse_inner_attributes()?
);
869 if self.eat(&token
::CloseDelim(token
::Bracket
)) {
871 ex
= ExprKind
::Array(Vec
::new());
874 let first_expr
= self.parse_expr()?
;
875 if self.eat(&token
::Semi
) {
876 // Repeating array syntax: `[ 0; 512 ]`
877 let count
= AnonConst
{
879 value
: self.parse_expr()?
,
881 self.expect(&token
::CloseDelim(token
::Bracket
))?
;
882 ex
= ExprKind
::Repeat(first_expr
, count
);
883 } else if self.eat(&token
::Comma
) {
884 // Vector with two or more elements
885 let remaining_exprs
= self.parse_seq_to_end(
886 &token
::CloseDelim(token
::Bracket
),
887 SeqSep
::trailing_allowed(token
::Comma
),
888 |p
| Ok(p
.parse_expr()?
)
890 let mut exprs
= vec
![first_expr
];
891 exprs
.extend(remaining_exprs
);
892 ex
= ExprKind
::Array(exprs
);
894 // Vector with one element
895 self.expect(&token
::CloseDelim(token
::Bracket
))?
;
896 ex
= ExprKind
::Array(vec
![first_expr
]);
903 let (qself
, path
) = self.parse_qpath(PathStyle
::Expr
)?
;
905 return Ok(self.mk_expr(lo
.to(hi
), ExprKind
::Path(Some(qself
), path
), attrs
));
907 if self.token
.is_path_start() {
908 let path
= self.parse_path(PathStyle
::Expr
)?
;
910 // `!`, as an operator, is prefix, so we know this isn't that.
911 if self.eat(&token
::Not
) {
912 // MACRO INVOCATION expression
913 let (delim
, tts
) = self.expect_delimited_token_tree()?
;
915 ex
= ExprKind
::Mac(Mac
{
920 prior_type_ascription
: self.last_type_ascription
,
922 } else if self.check(&token
::OpenDelim(token
::Brace
)) {
923 if let Some(expr
) = self.maybe_parse_struct_expr(lo
, &path
, &attrs
) {
927 ex
= ExprKind
::Path(None
, path
);
931 ex
= ExprKind
::Path(None
, path
);
934 let expr
= self.mk_expr(lo
.to(hi
), ex
, attrs
);
935 return self.maybe_recover_from_bad_qpath(expr
, true);
937 if self.check_keyword(kw
::Move
) || self.check_keyword(kw
::Static
) {
938 return self.parse_closure_expr(attrs
);
940 if self.eat_keyword(kw
::If
) {
941 return self.parse_if_expr(attrs
);
943 if self.eat_keyword(kw
::For
) {
944 let lo
= self.prev_span
;
945 return self.parse_for_expr(None
, lo
, attrs
);
947 if self.eat_keyword(kw
::While
) {
948 let lo
= self.prev_span
;
949 return self.parse_while_expr(None
, lo
, attrs
);
951 if let Some(label
) = self.eat_label() {
952 let lo
= label
.ident
.span
;
953 self.expect(&token
::Colon
)?
;
954 if self.eat_keyword(kw
::While
) {
955 return self.parse_while_expr(Some(label
), lo
, attrs
)
957 if self.eat_keyword(kw
::For
) {
958 return self.parse_for_expr(Some(label
), lo
, attrs
)
960 if self.eat_keyword(kw
::Loop
) {
961 return self.parse_loop_expr(Some(label
), lo
, attrs
)
963 if self.token
== token
::OpenDelim(token
::Brace
) {
964 return self.parse_block_expr(Some(label
),
966 BlockCheckMode
::Default
,
969 let msg
= "expected `while`, `for`, `loop` or `{` after a label";
970 let mut err
= self.fatal(msg
);
971 err
.span_label(self.token
.span
, msg
);
974 if self.eat_keyword(kw
::Loop
) {
975 let lo
= self.prev_span
;
976 return self.parse_loop_expr(None
, lo
, attrs
);
978 if self.eat_keyword(kw
::Continue
) {
979 let label
= self.eat_label();
980 let ex
= ExprKind
::Continue(label
);
981 let hi
= self.prev_span
;
982 return Ok(self.mk_expr(lo
.to(hi
), ex
, attrs
));
984 if self.eat_keyword(kw
::Match
) {
985 let match_sp
= self.prev_span
;
986 return self.parse_match_expr(attrs
).map_err(|mut err
| {
987 err
.span_label(match_sp
, "while parsing this match expression");
991 if self.eat_keyword(kw
::Unsafe
) {
992 return self.parse_block_expr(
995 BlockCheckMode
::Unsafe(ast
::UserProvided
),
998 if self.is_do_catch_block() {
999 let mut db
= self.fatal("found removed `do catch` syntax");
1000 db
.help("following RFC #2388, the new non-placeholder syntax is `try`");
1003 if self.is_try_block() {
1004 let lo
= self.token
.span
;
1005 assert
!(self.eat_keyword(kw
::Try
));
1006 return self.parse_try_block(lo
, attrs
);
1009 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1010 let is_span_rust_2018
= self.token
.span
.rust_2018();
1011 if is_span_rust_2018
&& self.check_keyword(kw
::Async
) {
1012 return if self.is_async_block() { // Check for `async {` and `async move {`.
1013 self.parse_async_block(attrs
)
1015 self.parse_closure_expr(attrs
)
1018 if self.eat_keyword(kw
::Return
) {
1019 if self.token
.can_begin_expr() {
1020 let e
= self.parse_expr()?
;
1022 ex
= ExprKind
::Ret(Some(e
));
1024 ex
= ExprKind
::Ret(None
);
1026 } else if self.eat_keyword(kw
::Break
) {
1027 let label
= self.eat_label();
1028 let e
= if self.token
.can_begin_expr()
1029 && !(self.token
== token
::OpenDelim(token
::Brace
)
1030 && self.restrictions
.contains(
1031 Restrictions
::NO_STRUCT_LITERAL
)) {
1032 Some(self.parse_expr()?
)
1036 ex
= ExprKind
::Break(label
, e
);
1037 hi
= self.prev_span
;
1038 } else if self.eat_keyword(kw
::Yield
) {
1039 if self.token
.can_begin_expr() {
1040 let e
= self.parse_expr()?
;
1042 ex
= ExprKind
::Yield(Some(e
));
1044 ex
= ExprKind
::Yield(None
);
1047 let span
= lo
.to(hi
);
1048 self.sess
.gated_spans
.yields
.borrow_mut().push(span
);
1049 } else if self.eat_keyword(kw
::Let
) {
1050 return self.parse_let_expr(attrs
);
1051 } else if is_span_rust_2018
&& self.eat_keyword(kw
::Await
) {
1052 let (await_hi
, e_kind
) = self.parse_incorrect_await_syntax(lo
, self.prev_span
)?
;
1056 if !self.unclosed_delims
.is_empty() && self.check(&token
::Semi
) {
1057 // Don't complain about bare semicolons after unclosed braces
1058 // recovery in order to keep the error count down. Fixing the
1059 // delimiters will possibly also fix the bare semicolon found in
1060 // expression context. For example, silence the following error:
1062 // error: expected expression, found `;`
1066 // | ^ expected expression
1068 return Ok(self.mk_expr(self.token
.span
, ExprKind
::Err
, ThinVec
::new()));
1075 let expr
= self.mk_expr(lo
.to(hi
), ex
, attrs
);
1076 self.maybe_recover_from_bad_qpath(expr
, true)
1079 /// Matches `lit = true | false | token_lit`.
1080 pub(super) fn parse_lit(&mut self) -> PResult
<'a
, Lit
> {
1081 let mut recovered
= None
;
1082 if self.token
== token
::Dot
{
1083 // Attempt to recover `.4` as `0.4`.
1084 recovered
= self.look_ahead(1, |next_token
| {
1085 if let token
::Literal(token
::Lit { kind: token::Integer, symbol, suffix }
)
1087 if self.token
.span
.hi() == next_token
.span
.lo() {
1088 let s
= String
::from("0.") + &symbol
.as_str();
1089 let kind
= TokenKind
::lit(token
::Float
, Symbol
::intern(&s
), suffix
);
1090 return Some(Token
::new(kind
, self.token
.span
.to(next_token
.span
)));
1095 if let Some(token
) = &recovered
{
1097 self.struct_span_err(token
.span
, "float literals must have an integer part")
1100 "must have an integer part",
1101 pprust
::token_to_string(token
),
1102 Applicability
::MachineApplicable
,
1108 let token
= recovered
.as_ref().unwrap_or(&self.token
);
1109 match Lit
::from_token(token
) {
1114 Err(LitError
::NotLiteral
) => {
1115 let msg
= format
!("unexpected token: {}", self.this_token_descr());
1116 Err(self.span_fatal(token
.span
, &msg
))
1119 let (lit
, span
) = (token
.expect_lit(), token
.span
);
1121 self.error_literal_from_token(err
, lit
, span
);
1122 // Pack possible quotes and prefixes from the original literal into
1123 // the error literal's symbol so they can be pretty-printed faithfully.
1124 let suffixless_lit
= token
::Lit
::new(lit
.kind
, lit
.symbol
, None
);
1125 let symbol
= Symbol
::intern(&suffixless_lit
.to_string());
1126 let lit
= token
::Lit
::new(token
::Err
, symbol
, lit
.suffix
);
1127 Lit
::from_lit_token(lit
, span
).map_err(|_
| unreachable
!())
1132 fn error_literal_from_token(&self, err
: LitError
, lit
: token
::Lit
, span
: Span
) {
1133 // Checks if `s` looks like i32 or u1234 etc.
1134 fn looks_like_width_suffix(first_chars
: &[char], s
: &str) -> bool
{
1136 && s
.starts_with(first_chars
)
1137 && s
[1..].chars().all(|c
| c
.is_ascii_digit())
1140 let token
::Lit { kind, suffix, .. }
= lit
;
1142 // `NotLiteral` is not an error by itself, so we don't report
1143 // it and give the parser opportunity to try something else.
1144 LitError
::NotLiteral
=> {}
1145 // `LexerError` *is* an error, but it was already reported
1146 // by lexer, so here we don't report it the second time.
1147 LitError
::LexerError
=> {}
1148 LitError
::InvalidSuffix
=> {
1149 self.expect_no_suffix(
1151 &format
!("{} {} literal", kind
.article(), kind
.descr()),
1155 LitError
::InvalidIntSuffix
=> {
1156 let suf
= suffix
.expect("suffix error with no suffix").as_str();
1157 if looks_like_width_suffix(&['i'
, 'u'
], &suf
) {
1158 // If it looks like a width, try to be helpful.
1159 let msg
= format
!("invalid width `{}` for integer literal", &suf
[1..]);
1160 self.struct_span_err(span
, &msg
)
1161 .help("valid widths are 8, 16, 32, 64 and 128")
1164 let msg
= format
!("invalid suffix `{}` for integer literal", suf
);
1165 self.struct_span_err(span
, &msg
)
1166 .span_label(span
, format
!("invalid suffix `{}`", suf
))
1167 .help("the suffix must be one of the integral types (`u32`, `isize`, etc)")
1171 LitError
::InvalidFloatSuffix
=> {
1172 let suf
= suffix
.expect("suffix error with no suffix").as_str();
1173 if looks_like_width_suffix(&['f'
], &suf
) {
1174 // If it looks like a width, try to be helpful.
1175 let msg
= format
!("invalid width `{}` for float literal", &suf
[1..]);
1176 self.struct_span_err(span
, &msg
)
1177 .help("valid widths are 32 and 64")
1180 let msg
= format
!("invalid suffix `{}` for float literal", suf
);
1181 self.struct_span_err(span
, &msg
)
1182 .span_label(span
, format
!("invalid suffix `{}`", suf
))
1183 .help("valid suffixes are `f32` and `f64`")
1187 LitError
::NonDecimalFloat(base
) => {
1188 let descr
= match base
{
1189 16 => "hexadecimal",
1192 _
=> unreachable
!(),
1194 self.struct_span_err(span
, &format
!("{} float literal is not supported", descr
))
1195 .span_label(span
, "not supported")
1198 LitError
::IntTooLarge
=> {
1199 self.struct_span_err(span
, "integer literal is too large")
1205 pub(super) fn expect_no_suffix(&self, sp
: Span
, kind
: &str, suffix
: Option
<Symbol
>) {
1206 if let Some(suf
) = suffix
{
1207 let mut err
= if kind
== "a tuple index"
1208 && [sym
::i32, sym
::u32, sym
::isize, sym
::usize].contains(&suf
)
1210 // #59553: warn instead of reject out of hand to allow the fix to percolate
1211 // through the ecosystem when people fix their macros
1212 let mut err
= self.sess
.span_diagnostic
.struct_span_warn(
1214 &format
!("suffixes on {} are invalid", kind
),
1217 "`{}` is *temporarily* accepted on tuple index fields as it was \
1218 incorrectly accepted on stable for a few releases",
1222 "on proc macros, you'll want to use `syn::Index::from` or \
1223 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1224 to tuple field access",
1227 "for more context, see https://github.com/rust-lang/rust/issues/60210",
1231 self.struct_span_err(sp
, &format
!("suffixes on {} are invalid", kind
))
1233 err
.span_label(sp
, format
!("invalid suffix `{}`", suf
));
1238 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1239 pub fn parse_literal_maybe_minus(&mut self) -> PResult
<'a
, P
<Expr
>> {
1240 maybe_whole_expr
!(self);
1242 let minus_lo
= self.token
.span
;
1243 let minus_present
= self.eat(&token
::BinOp(token
::Minus
));
1244 let lo
= self.token
.span
;
1245 let literal
= self.parse_lit()?
;
1246 let hi
= self.prev_span
;
1247 let expr
= self.mk_expr(lo
.to(hi
), ExprKind
::Lit(literal
), ThinVec
::new());
1250 let minus_hi
= self.prev_span
;
1251 let unary
= self.mk_unary(UnOp
::Neg
, expr
);
1252 Ok(self.mk_expr(minus_lo
.to(minus_hi
), unary
, ThinVec
::new()))
1258 /// Parses a block or unsafe block.
1259 pub(super) fn parse_block_expr(
1261 opt_label
: Option
<Label
>,
1263 blk_mode
: BlockCheckMode
,
1264 outer_attrs
: ThinVec
<Attribute
>,
1265 ) -> PResult
<'a
, P
<Expr
>> {
1266 if let Some(label
) = opt_label
{
1267 self.sess
.gated_spans
.label_break_value
.borrow_mut().push(label
.ident
.span
);
1270 self.expect(&token
::OpenDelim(token
::Brace
))?
;
1272 let mut attrs
= outer_attrs
;
1273 attrs
.extend(self.parse_inner_attributes()?
);
1275 let blk
= self.parse_block_tail(lo
, blk_mode
)?
;
1276 Ok(self.mk_expr(blk
.span
, ExprKind
::Block(blk
, opt_label
), attrs
))
1279 /// Parses a closure expression (e.g., `move |args| expr`).
1280 fn parse_closure_expr(&mut self, attrs
: ThinVec
<Attribute
>) -> PResult
<'a
, P
<Expr
>> {
1281 let lo
= self.token
.span
;
1283 let movability
= if self.eat_keyword(kw
::Static
) {
1289 let asyncness
= if self.token
.span
.rust_2018() {
1290 self.parse_asyncness()
1294 if asyncness
.is_async() {
1295 // Feature-gate `async ||` closures.
1296 self.sess
.gated_spans
.async_closure
.borrow_mut().push(self.prev_span
);
1299 let capture_clause
= self.parse_capture_clause();
1300 let decl
= self.parse_fn_block_decl()?
;
1301 let decl_hi
= self.prev_span
;
1302 let body
= match decl
.output
{
1303 FunctionRetTy
::Default(_
) => {
1304 let restrictions
= self.restrictions
- Restrictions
::STMT_EXPR
;
1305 self.parse_expr_res(restrictions
, None
)?
1308 // If an explicit return type is given, require a block to appear (RFC 968).
1309 let body_lo
= self.token
.span
;
1310 self.parse_block_expr(None
, body_lo
, BlockCheckMode
::Default
, ThinVec
::new())?
1316 ExprKind
::Closure(capture_clause
, asyncness
, movability
, decl
, body
, lo
.to(decl_hi
)),
1320 /// Parses an optional `move` prefix to a closure lke construct.
1321 fn parse_capture_clause(&mut self) -> CaptureBy
{
1322 if self.eat_keyword(kw
::Move
) {
1329 /// Parses the `|arg, arg|` header of a closure.
1330 fn parse_fn_block_decl(&mut self) -> PResult
<'a
, P
<FnDecl
>> {
1331 let inputs_captures
= {
1332 if self.eat(&token
::OrOr
) {
1335 self.expect(&token
::BinOp(token
::Or
))?
;
1336 let args
= self.parse_seq_to_before_tokens(
1337 &[&token
::BinOp(token
::Or
), &token
::OrOr
],
1338 SeqSep
::trailing_allowed(token
::Comma
),
1339 TokenExpectType
::NoExpect
,
1340 |p
| p
.parse_fn_block_param()
1346 let output
= self.parse_ret_ty(true)?
;
1349 inputs
: inputs_captures
,
1354 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1355 fn parse_fn_block_param(&mut self) -> PResult
<'a
, Param
> {
1356 let lo
= self.token
.span
;
1357 let attrs
= self.parse_outer_attributes()?
;
1358 let pat
= self.parse_pat(PARAM_EXPECTED
)?
;
1359 let t
= if self.eat(&token
::Colon
) {
1364 kind
: TyKind
::Infer
,
1365 span
: self.prev_span
,
1368 let span
= lo
.to(self.token
.span
);
1370 attrs
: attrs
.into(),
1375 is_placeholder
: false,
1379 /// Parses an `if` expression (`if` token already eaten).
1380 fn parse_if_expr(&mut self, attrs
: ThinVec
<Attribute
>) -> PResult
<'a
, P
<Expr
>> {
1381 let lo
= self.prev_span
;
1382 let cond
= self.parse_cond_expr()?
;
1384 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1385 // verify that the last statement is either an implicit return (no `;`) or an explicit
1386 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1387 // the dead code lint.
1388 if self.eat_keyword(kw
::Else
) || !cond
.returns() {
1389 let sp
= self.sess
.source_map().next_point(lo
);
1390 let mut err
= self.diagnostic()
1391 .struct_span_err(sp
, "missing condition for `if` expression");
1392 err
.span_label(sp
, "expected if condition here");
1395 let not_block
= self.token
!= token
::OpenDelim(token
::Brace
);
1396 let thn
= self.parse_block().map_err(|mut err
| {
1398 err
.span_label(lo
, "this `if` statement has a condition, but no block");
1402 let mut els
: Option
<P
<Expr
>> = None
;
1403 let mut hi
= thn
.span
;
1404 if self.eat_keyword(kw
::Else
) {
1405 let elexpr
= self.parse_else_expr()?
;
1409 Ok(self.mk_expr(lo
.to(hi
), ExprKind
::If(cond
, thn
, els
), attrs
))
1412 /// Parses the condition of a `if` or `while` expression.
1413 fn parse_cond_expr(&mut self) -> PResult
<'a
, P
<Expr
>> {
1414 let cond
= self.parse_expr_res(Restrictions
::NO_STRUCT_LITERAL
, None
)?
;
1416 if let ExprKind
::Let(..) = cond
.kind
{
1417 // Remove the last feature gating of a `let` expression since it's stable.
1418 let last
= self.sess
.gated_spans
.let_chains
.borrow_mut().pop();
1419 debug_assert_eq
!(cond
.span
, last
.unwrap());
1425 /// Parses a `let $pat = $expr` pseudo-expression.
1426 /// The `let` token has already been eaten.
1427 fn parse_let_expr(&mut self, attrs
: ThinVec
<Attribute
>) -> PResult
<'a
, P
<Expr
>> {
1428 let lo
= self.prev_span
;
1429 let pat
= self.parse_top_pat(GateOr
::No
)?
;
1430 self.expect(&token
::Eq
)?
;
1431 let expr
= self.with_res(
1432 Restrictions
::NO_STRUCT_LITERAL
,
1433 |this
| this
.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None
.into())
1435 let span
= lo
.to(expr
.span
);
1436 self.sess
.gated_spans
.let_chains
.borrow_mut().push(span
);
1437 Ok(self.mk_expr(span
, ExprKind
::Let(pat
, expr
), attrs
))
1440 /// Parses an `else { ... }` expression (`else` token already eaten).
1441 fn parse_else_expr(&mut self) -> PResult
<'a
, P
<Expr
>> {
1442 if self.eat_keyword(kw
::If
) {
1443 return self.parse_if_expr(ThinVec
::new());
1445 let blk
= self.parse_block()?
;
1446 return Ok(self.mk_expr(blk
.span
, ExprKind
::Block(blk
, None
), ThinVec
::new()));
1450 /// Parses a `for ... in` expression (`for` token already eaten).
1453 opt_label
: Option
<Label
>,
1455 mut attrs
: ThinVec
<Attribute
>
1456 ) -> PResult
<'a
, P
<Expr
>> {
1457 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
1459 // Record whether we are about to parse `for (`.
1460 // This is used below for recovery in case of `for ( $stuff ) $block`
1461 // in which case we will suggest `for $stuff $block`.
1462 let begin_paren
= match self.token
.kind
{
1463 token
::OpenDelim(token
::Paren
) => Some(self.token
.span
),
1467 let pat
= self.parse_top_pat(GateOr
::Yes
)?
;
1468 if !self.eat_keyword(kw
::In
) {
1469 let in_span
= self.prev_span
.between(self.token
.span
);
1470 self.struct_span_err(in_span
, "missing `in` in `for` loop")
1471 .span_suggestion_short(
1473 "try adding `in` here", " in ".into(),
1474 // has been misleading, at least in the past (closed Issue #48492)
1475 Applicability
::MaybeIncorrect
1479 let in_span
= self.prev_span
;
1480 self.check_for_for_in_in_typo(in_span
);
1481 let expr
= self.parse_expr_res(Restrictions
::NO_STRUCT_LITERAL
, None
)?
;
1483 let pat
= self.recover_parens_around_for_head(pat
, &expr
, begin_paren
);
1485 let (iattrs
, loop_block
) = self.parse_inner_attrs_and_block()?
;
1486 attrs
.extend(iattrs
);
1488 let hi
= self.prev_span
;
1489 Ok(self.mk_expr(span_lo
.to(hi
), ExprKind
::ForLoop(pat
, expr
, loop_block
, opt_label
), attrs
))
1492 /// Parses a `while` or `while let` expression (`while` token already eaten).
1493 fn parse_while_expr(
1495 opt_label
: Option
<Label
>,
1497 mut attrs
: ThinVec
<Attribute
>
1498 ) -> PResult
<'a
, P
<Expr
>> {
1499 let cond
= self.parse_cond_expr()?
;
1500 let (iattrs
, body
) = self.parse_inner_attrs_and_block()?
;
1501 attrs
.extend(iattrs
);
1502 let span
= span_lo
.to(body
.span
);
1503 Ok(self.mk_expr(span
, ExprKind
::While(cond
, body
, opt_label
), attrs
))
1506 /// Parses `loop { ... }` (`loop` token already eaten).
1509 opt_label
: Option
<Label
>,
1511 mut attrs
: ThinVec
<Attribute
>
1512 ) -> PResult
<'a
, P
<Expr
>> {
1513 let (iattrs
, body
) = self.parse_inner_attrs_and_block()?
;
1514 attrs
.extend(iattrs
);
1515 let span
= span_lo
.to(body
.span
);
1516 Ok(self.mk_expr(span
, ExprKind
::Loop(body
, opt_label
), attrs
))
1519 fn eat_label(&mut self) -> Option
<Label
> {
1520 if let Some(ident
) = self.token
.lifetime() {
1521 let span
= self.token
.span
;
1523 Some(Label { ident: Ident::new(ident.name, span) }
)
1529 /// Parses a `match ... { ... }` expression (`match` token already eaten).
1530 fn parse_match_expr(&mut self, mut attrs
: ThinVec
<Attribute
>) -> PResult
<'a
, P
<Expr
>> {
1531 let match_span
= self.prev_span
;
1532 let lo
= self.prev_span
;
1533 let discriminant
= self.parse_expr_res(Restrictions
::NO_STRUCT_LITERAL
, None
)?
;
1534 if let Err(mut e
) = self.expect(&token
::OpenDelim(token
::Brace
)) {
1535 if self.token
== token
::Semi
{
1536 e
.span_suggestion_short(
1538 "try removing this `match`",
1540 Applicability
::MaybeIncorrect
// speculative
1545 attrs
.extend(self.parse_inner_attributes()?
);
1547 let mut arms
: Vec
<Arm
> = Vec
::new();
1548 while self.token
!= token
::CloseDelim(token
::Brace
) {
1549 match self.parse_arm() {
1550 Ok(arm
) => arms
.push(arm
),
1552 // Recover by skipping to the end of the block.
1554 self.recover_stmt();
1555 let span
= lo
.to(self.token
.span
);
1556 if self.token
== token
::CloseDelim(token
::Brace
) {
1559 return Ok(self.mk_expr(span
, ExprKind
::Match(discriminant
, arms
), attrs
));
1563 let hi
= self.token
.span
;
1565 return Ok(self.mk_expr(lo
.to(hi
), ExprKind
::Match(discriminant
, arms
), attrs
));
1568 pub(super) fn parse_arm(&mut self) -> PResult
<'a
, Arm
> {
1569 let attrs
= self.parse_outer_attributes()?
;
1570 let lo
= self.token
.span
;
1571 let pat
= self.parse_top_pat(GateOr
::No
)?
;
1572 let guard
= if self.eat_keyword(kw
::If
) {
1573 Some(self.parse_expr()?
)
1577 let arrow_span
= self.token
.span
;
1578 self.expect(&token
::FatArrow
)?
;
1579 let arm_start_span
= self.token
.span
;
1581 let expr
= self.parse_expr_res(Restrictions
::STMT_EXPR
, None
)
1582 .map_err(|mut err
| {
1583 err
.span_label(arrow_span
, "while parsing the `match` arm starting here");
1587 let require_comma
= classify
::expr_requires_semi_to_be_stmt(&expr
)
1588 && self.token
!= token
::CloseDelim(token
::Brace
);
1590 let hi
= self.token
.span
;
1593 let cm
= self.sess
.source_map();
1594 self.expect_one_of(&[token
::Comma
], &[token
::CloseDelim(token
::Brace
)])
1595 .map_err(|mut err
| {
1596 match (cm
.span_to_lines(expr
.span
), cm
.span_to_lines(arm_start_span
)) {
1597 (Ok(ref expr_lines
), Ok(ref arm_start_lines
))
1598 if arm_start_lines
.lines
[0].end_col
== expr_lines
.lines
[0].end_col
1599 && expr_lines
.lines
.len() == 2
1600 && self.token
== token
::FatArrow
=> {
1601 // We check whether there's any trailing code in the parse span,
1602 // if there isn't, we very likely have the following:
1605 // | -- - missing comma
1609 // | - ^^ self.token.span
1611 // | parsed until here as `"y" & X`
1612 err
.span_suggestion_short(
1613 cm
.next_point(arm_start_span
),
1614 "missing a comma here to end this `match` arm",
1616 Applicability
::MachineApplicable
1620 err
.span_label(arrow_span
,
1621 "while parsing the `match` arm starting here");
1627 self.eat(&token
::Comma
);
1637 is_placeholder
: false,
1641 /// Parses a `try {...}` expression (`try` token already eaten).
1645 mut attrs
: ThinVec
<Attribute
>
1646 ) -> PResult
<'a
, P
<Expr
>> {
1647 let (iattrs
, body
) = self.parse_inner_attrs_and_block()?
;
1648 attrs
.extend(iattrs
);
1649 if self.eat_keyword(kw
::Catch
) {
1650 let mut error
= self.struct_span_err(self.prev_span
,
1651 "keyword `catch` cannot follow a `try` block");
1652 error
.help("try using `match` on the result of the `try` block instead");
1656 let span
= span_lo
.to(body
.span
);
1657 self.sess
.gated_spans
.try_blocks
.borrow_mut().push(span
);
1658 Ok(self.mk_expr(span
, ExprKind
::TryBlock(body
), attrs
))
1662 fn is_do_catch_block(&self) -> bool
{
1663 self.token
.is_keyword(kw
::Do
) &&
1664 self.is_keyword_ahead(1, &[kw
::Catch
]) &&
1665 self.look_ahead(2, |t
| *t
== token
::OpenDelim(token
::Brace
)) &&
1666 !self.restrictions
.contains(Restrictions
::NO_STRUCT_LITERAL
)
1669 fn is_try_block(&self) -> bool
{
1670 self.token
.is_keyword(kw
::Try
) &&
1671 self.look_ahead(1, |t
| *t
== token
::OpenDelim(token
::Brace
)) &&
1672 self.token
.span
.rust_2018() &&
1673 // Prevent `while try {} {}`, `if try {} {} else {}`, etc.
1674 !self.restrictions
.contains(Restrictions
::NO_STRUCT_LITERAL
)
1677 /// Parses an `async move? {...}` expression.
1678 fn parse_async_block(&mut self, mut attrs
: ThinVec
<Attribute
>) -> PResult
<'a
, P
<Expr
>> {
1679 let span_lo
= self.token
.span
;
1680 self.expect_keyword(kw
::Async
)?
;
1681 let capture_clause
= self.parse_capture_clause();
1682 let (iattrs
, body
) = self.parse_inner_attrs_and_block()?
;
1683 attrs
.extend(iattrs
);
1685 span_lo
.to(body
.span
),
1686 ExprKind
::Async(capture_clause
, DUMMY_NODE_ID
, body
), attrs
))
1689 fn is_async_block(&self) -> bool
{
1690 self.token
.is_keyword(kw
::Async
) &&
1693 self.is_keyword_ahead(1, &[kw
::Move
]) &&
1694 self.look_ahead(2, |t
| *t
== token
::OpenDelim(token
::Brace
))
1696 self.look_ahead(1, |t
| *t
== token
::OpenDelim(token
::Brace
))
1701 fn maybe_parse_struct_expr(
1705 attrs
: &ThinVec
<Attribute
>,
1706 ) -> Option
<PResult
<'a
, P
<Expr
>>> {
1707 let struct_allowed
= !self.restrictions
.contains(Restrictions
::NO_STRUCT_LITERAL
);
1708 let certainly_not_a_block
= || self.look_ahead(1, |t
| t
.is_ident()) && (
1709 // `{ ident, ` cannot start a block.
1710 self.look_ahead(2, |t
| t
== &token
::Comma
) ||
1711 self.look_ahead(2, |t
| t
== &token
::Colon
) && (
1712 // `{ ident: token, ` cannot start a block.
1713 self.look_ahead(4, |t
| t
== &token
::Comma
) ||
1714 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
1715 self.look_ahead(3, |t
| !t
.can_begin_type())
1719 if struct_allowed
|| certainly_not_a_block() {
1720 // This is a struct literal, but we don't can't accept them here.
1721 let expr
= self.parse_struct_expr(lo
, path
.clone(), attrs
.clone());
1722 if let (Ok(expr
), false) = (&expr
, struct_allowed
) {
1723 self.struct_span_err(
1725 "struct literals are not allowed here",
1727 .multipart_suggestion(
1728 "surround the struct literal with parentheses",
1730 (lo
.shrink_to_lo(), "(".to_string()),
1731 (expr
.span
.shrink_to_hi(), ")".to_string()),
1733 Applicability
::MachineApplicable
,
1742 pub(super) fn parse_struct_expr(
1746 mut attrs
: ThinVec
<Attribute
>
1747 ) -> PResult
<'a
, P
<Expr
>> {
1748 let struct_sp
= lo
.to(self.prev_span
);
1750 let mut fields
= Vec
::new();
1751 let mut base
= None
;
1753 attrs
.extend(self.parse_inner_attributes()?
);
1755 while self.token
!= token
::CloseDelim(token
::Brace
) {
1756 if self.eat(&token
::DotDot
) {
1757 let exp_span
= self.prev_span
;
1758 match self.parse_expr() {
1764 self.recover_stmt();
1767 if self.token
== token
::Comma
{
1768 self.struct_span_err(
1769 exp_span
.to(self.prev_span
),
1770 "cannot use a comma after the base struct",
1772 .span_suggestion_short(
1774 "remove this comma",
1776 Applicability
::MachineApplicable
1778 .note("the base struct must always be the last field")
1780 self.recover_stmt();
1785 let mut recovery_field
= None
;
1786 if let token
::Ident(name
, _
) = self.token
.kind
{
1787 if !self.token
.is_reserved_ident() && self.look_ahead(1, |t
| *t
== token
::Colon
) {
1788 // Use in case of error after field-looking code: `S { foo: () with a }`.
1789 recovery_field
= Some(ast
::Field
{
1790 ident
: Ident
::new(name
, self.token
.span
),
1791 span
: self.token
.span
,
1792 expr
: self.mk_expr(self.token
.span
, ExprKind
::Err
, ThinVec
::new()),
1793 is_shorthand
: false,
1794 attrs
: ThinVec
::new(),
1796 is_placeholder
: false,
1800 let mut parsed_field
= None
;
1801 match self.parse_field() {
1802 Ok(f
) => parsed_field
= Some(f
),
1804 e
.span_label(struct_sp
, "while parsing this struct");
1807 // If the next token is a comma, then try to parse
1808 // what comes next as additional fields, rather than
1809 // bailing out until next `}`.
1810 if self.token
!= token
::Comma
{
1811 self.recover_stmt_(SemiColonMode
::Comma
, BlockMode
::Ignore
);
1812 if self.token
!= token
::Comma
{
1819 match self.expect_one_of(&[token
::Comma
],
1820 &[token
::CloseDelim(token
::Brace
)]) {
1821 Ok(_
) => if let Some(f
) = parsed_field
.or(recovery_field
) {
1822 // Only include the field if there's no parse error for the field name.
1826 if let Some(f
) = recovery_field
{
1829 e
.span_label(struct_sp
, "while parsing this struct");
1831 self.recover_stmt_(SemiColonMode
::Comma
, BlockMode
::Ignore
);
1832 self.eat(&token
::Comma
);
1837 let span
= lo
.to(self.token
.span
);
1838 self.expect(&token
::CloseDelim(token
::Brace
))?
;
1839 return Ok(self.mk_expr(span
, ExprKind
::Struct(pth
, fields
, base
), attrs
));
1842 /// Parses `ident (COLON expr)?`.
1843 fn parse_field(&mut self) -> PResult
<'a
, Field
> {
1844 let attrs
= self.parse_outer_attributes()?
;
1845 let lo
= self.token
.span
;
1847 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1848 let (fieldname
, expr
, is_shorthand
) = if self.look_ahead(1, |t
| {
1849 t
== &token
::Colon
|| t
== &token
::Eq
1851 let fieldname
= self.parse_field_name()?
;
1853 // Check for an equals token. This means the source incorrectly attempts to
1854 // initialize a field with an eq rather than a colon.
1855 if self.token
== token
::Eq
{
1857 .struct_span_err(self.token
.span
, "expected `:`, found `=`")
1859 fieldname
.span
.shrink_to_hi().to(self.token
.span
),
1860 "replace equals symbol with a colon",
1862 Applicability
::MachineApplicable
,
1867 (fieldname
, self.parse_expr()?
, false)
1869 let fieldname
= self.parse_ident_common(false)?
;
1871 // Mimic `x: x` for the `x` field shorthand.
1872 let path
= ast
::Path
::from_ident(fieldname
);
1873 let expr
= self.mk_expr(fieldname
.span
, ExprKind
::Path(None
, path
), ThinVec
::new());
1874 (fieldname
, expr
, true)
1878 span
: lo
.to(expr
.span
),
1881 attrs
: attrs
.into(),
1883 is_placeholder
: false,
1887 fn err_dotdotdot_syntax(&self, span
: Span
) {
1888 self.struct_span_err(span
, "unexpected token: `...`")
1891 "use `..` for an exclusive range", "..".to_owned(),
1892 Applicability
::MaybeIncorrect
1896 "or `..=` for an inclusive range", "..=".to_owned(),
1897 Applicability
::MaybeIncorrect
1902 fn err_larrow_operator(&self, span
: Span
) {
1903 self.struct_span_err(
1905 "unexpected token: `<-`"
1908 "if you meant to write a comparison against a negative value, add a \
1909 space in between `<` and `-`",
1911 Applicability
::MaybeIncorrect
1915 fn mk_assign_op(&self, binop
: BinOp
, lhs
: P
<Expr
>, rhs
: P
<Expr
>) -> ExprKind
{
1916 ExprKind
::AssignOp(binop
, lhs
, rhs
)
1921 start
: Option
<P
<Expr
>>,
1922 end
: Option
<P
<Expr
>>,
1924 ) -> PResult
<'a
, ExprKind
> {
1925 if end
.is_none() && limits
== RangeLimits
::Closed
{
1926 Err(self.span_fatal_err(self.token
.span
, Error
::InclusiveRangeWithNoEnd
))
1928 Ok(ExprKind
::Range(start
, end
, limits
))
1932 fn mk_unary(&self, unop
: UnOp
, expr
: P
<Expr
>) -> ExprKind
{
1933 ExprKind
::Unary(unop
, expr
)
1936 fn mk_binary(&self, binop
: BinOp
, lhs
: P
<Expr
>, rhs
: P
<Expr
>) -> ExprKind
{
1937 ExprKind
::Binary(binop
, lhs
, rhs
)
1940 fn mk_index(&self, expr
: P
<Expr
>, idx
: P
<Expr
>) -> ExprKind
{
1941 ExprKind
::Index(expr
, idx
)
1944 fn mk_call(&self, f
: P
<Expr
>, args
: Vec
<P
<Expr
>>) -> ExprKind
{
1945 ExprKind
::Call(f
, args
)
1948 fn mk_await_expr(&mut self, self_arg
: P
<Expr
>, lo
: Span
) -> PResult
<'a
, P
<Expr
>> {
1949 let span
= lo
.to(self.prev_span
);
1950 let await_expr
= self.mk_expr(span
, ExprKind
::Await(self_arg
), ThinVec
::new());
1951 self.recover_from_await_method_call();
1955 crate fn mk_expr(&self, span
: Span
, kind
: ExprKind
, attrs
: ThinVec
<Attribute
>) -> P
<Expr
> {
1956 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID }
)
1959 pub(super) fn mk_expr_err(&self, span
: Span
) -> P
<Expr
> {
1960 self.mk_expr(span
, ExprKind
::Err
, ThinVec
::new())