]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_parse/src/parser/expr.rs
New upstream version 1.56.0~beta.4+dfsg1
[rustc.git] / compiler / rustc_parse / src / parser / expr.rs
1 use super::pat::{RecoverColon, RecoverComma, PARAM_EXPECTED};
2 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
3 use super::{AttrWrapper, BlockMode, ForceCollect, Parser, PathStyle, Restrictions, TokenType};
4 use super::{SemiColonMode, SeqSep, TokenExpectType, TrailingToken};
5 use crate::maybe_recover_from_interpolated_ty_qpath;
6
7 use rustc_ast::ptr::P;
8 use rustc_ast::token::{self, Token, TokenKind};
9 use rustc_ast::tokenstream::Spacing;
10 use rustc_ast::util::classify;
11 use rustc_ast::util::literal::LitError;
12 use rustc_ast::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity};
13 use rustc_ast::{self as ast, AttrStyle, AttrVec, CaptureBy, ExprField, Lit, UnOp, DUMMY_NODE_ID};
14 use rustc_ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty, TyKind};
15 use rustc_ast::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits};
16 use rustc_ast_pretty::pprust;
17 use rustc_errors::{Applicability, DiagnosticBuilder, PResult};
18 use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP;
19 use rustc_session::lint::BuiltinLintDiagnostics;
20 use rustc_span::edition::LATEST_STABLE_EDITION;
21 use rustc_span::source_map::{self, Span, Spanned};
22 use rustc_span::symbol::{kw, sym, Ident, Symbol};
23 use rustc_span::{BytePos, Pos};
24 use std::mem;
25
26 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
27 /// dropped into the token stream, which happens while parsing the result of
28 /// macro expansion). Placement of these is not as complex as I feared it would
29 /// be. The important thing is to make sure that lookahead doesn't balk at
30 /// `token::Interpolated` tokens.
31 macro_rules! maybe_whole_expr {
32 ($p:expr) => {
33 if let token::Interpolated(nt) = &$p.token.kind {
34 match &**nt {
35 token::NtExpr(e) | token::NtLiteral(e) => {
36 let e = e.clone();
37 $p.bump();
38 return Ok(e);
39 }
40 token::NtPath(path) => {
41 let path = path.clone();
42 $p.bump();
43 return Ok($p.mk_expr(
44 $p.prev_token.span,
45 ExprKind::Path(None, path),
46 AttrVec::new(),
47 ));
48 }
49 token::NtBlock(block) => {
50 let block = block.clone();
51 $p.bump();
52 return Ok($p.mk_expr(
53 $p.prev_token.span,
54 ExprKind::Block(block, None),
55 AttrVec::new(),
56 ));
57 }
58 _ => {}
59 };
60 }
61 };
62 }
63
64 #[derive(Debug)]
65 pub(super) enum LhsExpr {
66 NotYetParsed,
67 AttributesParsed(AttrWrapper),
68 AlreadyParsed(P<Expr>),
69 }
70
71 impl From<Option<AttrWrapper>> for LhsExpr {
72 /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
73 /// and `None` into `LhsExpr::NotYetParsed`.
74 ///
75 /// This conversion does not allocate.
76 fn from(o: Option<AttrWrapper>) -> Self {
77 if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed }
78 }
79 }
80
81 impl From<P<Expr>> for LhsExpr {
82 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
83 ///
84 /// This conversion does not allocate.
85 fn from(expr: P<Expr>) -> Self {
86 LhsExpr::AlreadyParsed(expr)
87 }
88 }
89
90 impl<'a> Parser<'a> {
91 /// Parses an expression.
92 #[inline]
93 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
94 self.parse_expr_res(Restrictions::empty(), None)
95 }
96
97 /// Parses an expression, forcing tokens to be collected
98 pub fn parse_expr_force_collect(&mut self) -> PResult<'a, P<Expr>> {
99 self.collect_tokens_no_attrs(|this| this.parse_expr())
100 }
101
102 pub fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> {
103 self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
104 }
105
106 fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P<Expr>> {
107 match self.parse_expr() {
108 Ok(expr) => Ok(expr),
109 Err(mut err) => match self.token.ident() {
110 Some((Ident { name: kw::Underscore, .. }, false))
111 if self.look_ahead(1, |t| t == &token::Comma) =>
112 {
113 // Special-case handling of `foo(_, _, _)`
114 err.emit();
115 self.bump();
116 Ok(self.mk_expr(self.prev_token.span, ExprKind::Err, AttrVec::new()))
117 }
118 _ => Err(err),
119 },
120 }
121 }
122
123 /// Parses a sequence of expressions delimited by parentheses.
124 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
125 self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r)
126 }
127
128 /// Parses an expression, subject to the given restrictions.
129 #[inline]
130 pub(super) fn parse_expr_res(
131 &mut self,
132 r: Restrictions,
133 already_parsed_attrs: Option<AttrWrapper>,
134 ) -> PResult<'a, P<Expr>> {
135 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
136 }
137
138 /// Parses an associative expression.
139 ///
140 /// This parses an expression accounting for associativity and precedence of the operators in
141 /// the expression.
142 #[inline]
143 fn parse_assoc_expr(
144 &mut self,
145 already_parsed_attrs: Option<AttrWrapper>,
146 ) -> PResult<'a, P<Expr>> {
147 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
148 }
149
150 /// Parses an associative expression with operators of at least `min_prec` precedence.
151 pub(super) fn parse_assoc_expr_with(
152 &mut self,
153 min_prec: usize,
154 lhs: LhsExpr,
155 ) -> PResult<'a, P<Expr>> {
156 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
157 expr
158 } else {
159 let attrs = match lhs {
160 LhsExpr::AttributesParsed(attrs) => Some(attrs),
161 _ => None,
162 };
163 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
164 return self.parse_prefix_range_expr(attrs);
165 } else {
166 self.parse_prefix_expr(attrs)?
167 }
168 };
169 let last_type_ascription_set = self.last_type_ascription.is_some();
170
171 if !self.should_continue_as_assoc_expr(&lhs) {
172 self.last_type_ascription = None;
173 return Ok(lhs);
174 }
175
176 self.expected_tokens.push(TokenType::Operator);
177 while let Some(op) = self.check_assoc_op() {
178 // Adjust the span for interpolated LHS to point to the `$lhs` token
179 // and not to what it refers to.
180 let lhs_span = match self.prev_token.kind {
181 TokenKind::Interpolated(..) => self.prev_token.span,
182 _ => lhs.span,
183 };
184
185 let cur_op_span = self.token.span;
186 let restrictions = if op.node.is_assign_like() {
187 self.restrictions & Restrictions::NO_STRUCT_LITERAL
188 } else {
189 self.restrictions
190 };
191 let prec = op.node.precedence();
192 if prec < min_prec {
193 break;
194 }
195 // Check for deprecated `...` syntax
196 if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq {
197 self.err_dotdotdot_syntax(self.token.span);
198 }
199
200 if self.token == token::LArrow {
201 self.err_larrow_operator(self.token.span);
202 }
203
204 self.bump();
205 if op.node.is_comparison() {
206 if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
207 return Ok(expr);
208 }
209 }
210
211 if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual)
212 && self.token.kind == token::Eq
213 && self.prev_token.span.hi() == self.token.span.lo()
214 {
215 // Look for JS' `===` and `!==` and recover 😇
216 let sp = op.span.to(self.token.span);
217 let sugg = match op.node {
218 AssocOp::Equal => "==",
219 AssocOp::NotEqual => "!=",
220 _ => unreachable!(),
221 };
222 self.struct_span_err(sp, &format!("invalid comparison operator `{}=`", sugg))
223 .span_suggestion_short(
224 sp,
225 &format!("`{s}=` is not a valid comparison operator, use `{s}`", s = sugg),
226 sugg.to_string(),
227 Applicability::MachineApplicable,
228 )
229 .emit();
230 self.bump();
231 }
232
233 let op = op.node;
234 // Special cases:
235 if op == AssocOp::As {
236 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
237 continue;
238 } else if op == AssocOp::Colon {
239 lhs = self.parse_assoc_op_ascribe(lhs, lhs_span)?;
240 continue;
241 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
242 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
243 // generalise it to the Fixity::None code.
244 lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?;
245 break;
246 }
247
248 let fixity = op.fixity();
249 let prec_adjustment = match fixity {
250 Fixity::Right => 0,
251 Fixity::Left => 1,
252 // We currently have no non-associative operators that are not handled above by
253 // the special cases. The code is here only for future convenience.
254 Fixity::None => 1,
255 };
256 let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
257 this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
258 })?;
259
260 let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span);
261 lhs = match op {
262 AssocOp::Add
263 | AssocOp::Subtract
264 | AssocOp::Multiply
265 | AssocOp::Divide
266 | AssocOp::Modulus
267 | AssocOp::LAnd
268 | AssocOp::LOr
269 | AssocOp::BitXor
270 | AssocOp::BitAnd
271 | AssocOp::BitOr
272 | AssocOp::ShiftLeft
273 | AssocOp::ShiftRight
274 | AssocOp::Equal
275 | AssocOp::Less
276 | AssocOp::LessEqual
277 | AssocOp::NotEqual
278 | AssocOp::Greater
279 | AssocOp::GreaterEqual => {
280 let ast_op = op.to_ast_binop().unwrap();
281 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
282 self.mk_expr(span, binary, AttrVec::new())
283 }
284 AssocOp::Assign => {
285 self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span), AttrVec::new())
286 }
287 AssocOp::AssignOp(k) => {
288 let aop = match k {
289 token::Plus => BinOpKind::Add,
290 token::Minus => BinOpKind::Sub,
291 token::Star => BinOpKind::Mul,
292 token::Slash => BinOpKind::Div,
293 token::Percent => BinOpKind::Rem,
294 token::Caret => BinOpKind::BitXor,
295 token::And => BinOpKind::BitAnd,
296 token::Or => BinOpKind::BitOr,
297 token::Shl => BinOpKind::Shl,
298 token::Shr => BinOpKind::Shr,
299 };
300 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
301 self.mk_expr(span, aopexpr, AttrVec::new())
302 }
303 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
304 self.span_bug(span, "AssocOp should have been handled by special case")
305 }
306 };
307
308 if let Fixity::None = fixity {
309 break;
310 }
311 }
312 if last_type_ascription_set {
313 self.last_type_ascription = None;
314 }
315 Ok(lhs)
316 }
317
318 fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
319 match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) {
320 // Semi-statement forms are odd:
321 // See https://github.com/rust-lang/rust/issues/29071
322 (true, None) => false,
323 (false, _) => true, // Continue parsing the expression.
324 // An exhaustive check is done in the following block, but these are checked first
325 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
326 // want to keep their span info to improve diagnostics in these cases in a later stage.
327 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
328 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
329 (true, Some(AssocOp::Add)) // `{ 42 } + 42
330 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
331 // `if x { a } else { b } && if y { c } else { d }`
332 if !self.look_ahead(1, |t| t.is_used_keyword()) => {
333 // These cases are ambiguous and can't be identified in the parser alone.
334 let sp = self.sess.source_map().start_point(self.token.span);
335 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
336 false
337 }
338 (true, Some(AssocOp::LAnd)) => {
339 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`. Separated from the
340 // above due to #74233.
341 // These cases are ambiguous and can't be identified in the parser alone.
342 let sp = self.sess.source_map().start_point(self.token.span);
343 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
344 false
345 }
346 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => false,
347 (true, Some(_)) => {
348 self.error_found_expr_would_be_stmt(lhs);
349 true
350 }
351 }
352 }
353
354 /// We've found an expression that would be parsed as a statement,
355 /// but the next token implies this should be parsed as an expression.
356 /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
357 fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
358 let mut err = self.struct_span_err(
359 self.token.span,
360 &format!("expected expression, found `{}`", pprust::token_to_string(&self.token),),
361 );
362 err.span_label(self.token.span, "expected expression");
363 self.sess.expr_parentheses_needed(&mut err, lhs.span);
364 err.emit();
365 }
366
367 /// Possibly translate the current token to an associative operator.
368 /// The method does not advance the current token.
369 ///
370 /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
371 fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
372 let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
373 // When parsing const expressions, stop parsing when encountering `>`.
374 (
375 Some(
376 AssocOp::ShiftRight
377 | AssocOp::Greater
378 | AssocOp::GreaterEqual
379 | AssocOp::AssignOp(token::BinOpToken::Shr),
380 ),
381 _,
382 ) if self.restrictions.contains(Restrictions::CONST_EXPR) => {
383 return None;
384 }
385 (Some(op), _) => (op, self.token.span),
386 (None, Some((Ident { name: sym::and, span }, false))) => {
387 self.error_bad_logical_op("and", "&&", "conjunction");
388 (AssocOp::LAnd, span)
389 }
390 (None, Some((Ident { name: sym::or, span }, false))) => {
391 self.error_bad_logical_op("or", "||", "disjunction");
392 (AssocOp::LOr, span)
393 }
394 _ => return None,
395 };
396 Some(source_map::respan(span, op))
397 }
398
399 /// Error on `and` and `or` suggesting `&&` and `||` respectively.
400 fn error_bad_logical_op(&self, bad: &str, good: &str, english: &str) {
401 self.struct_span_err(self.token.span, &format!("`{}` is not a logical operator", bad))
402 .span_suggestion_short(
403 self.token.span,
404 &format!("use `{}` to perform logical {}", good, english),
405 good.to_string(),
406 Applicability::MachineApplicable,
407 )
408 .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators")
409 .emit();
410 }
411
412 /// Checks if this expression is a successfully parsed statement.
413 fn expr_is_complete(&self, e: &Expr) -> bool {
414 self.restrictions.contains(Restrictions::STMT_EXPR)
415 && !classify::expr_requires_semi_to_be_stmt(e)
416 }
417
418 /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
419 /// The other two variants are handled in `parse_prefix_range_expr` below.
420 fn parse_range_expr(
421 &mut self,
422 prec: usize,
423 lhs: P<Expr>,
424 op: AssocOp,
425 cur_op_span: Span,
426 ) -> PResult<'a, P<Expr>> {
427 let rhs = if self.is_at_start_of_range_notation_rhs() {
428 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
429 } else {
430 None
431 };
432 let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
433 let span = self.mk_expr_sp(&lhs, lhs.span, rhs_span);
434 let limits =
435 if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed };
436 let range = self.mk_range(Some(lhs), rhs, limits);
437 Ok(self.mk_expr(span, range, AttrVec::new()))
438 }
439
440 fn is_at_start_of_range_notation_rhs(&self) -> bool {
441 if self.token.can_begin_expr() {
442 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
443 if self.token == token::OpenDelim(token::Brace) {
444 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
445 }
446 true
447 } else {
448 false
449 }
450 }
451
452 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
453 fn parse_prefix_range_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
454 // Check for deprecated `...` syntax.
455 if self.token == token::DotDotDot {
456 self.err_dotdotdot_syntax(self.token.span);
457 }
458
459 debug_assert!(
460 [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
461 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
462 self.token
463 );
464
465 let limits = match self.token.kind {
466 token::DotDot => RangeLimits::HalfOpen,
467 _ => RangeLimits::Closed,
468 };
469 let op = AssocOp::from_token(&self.token);
470 // FIXME: `parse_prefix_range_expr` is called when the current
471 // token is `DotDot`, `DotDotDot`, or `DotDotEq`. If we haven't already
472 // parsed attributes, then trying to parse them here will always fail.
473 // We should figure out how we want attributes on range expressions to work.
474 let attrs = self.parse_or_use_outer_attributes(attrs)?;
475 self.collect_tokens_for_expr(attrs, |this, attrs| {
476 let lo = this.token.span;
477 this.bump();
478 let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() {
479 // RHS must be parsed with more associativity than the dots.
480 this.parse_assoc_expr_with(op.unwrap().precedence() + 1, LhsExpr::NotYetParsed)
481 .map(|x| (lo.to(x.span), Some(x)))?
482 } else {
483 (lo, None)
484 };
485 let range = this.mk_range(None, opt_end, limits);
486 Ok(this.mk_expr(span, range, attrs.into()))
487 })
488 }
489
490 /// Parses a prefix-unary-operator expr.
491 fn parse_prefix_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
492 let attrs = self.parse_or_use_outer_attributes(attrs)?;
493 let lo = self.token.span;
494
495 macro_rules! make_it {
496 ($this:ident, $attrs:expr, |this, _| $body:expr) => {
497 $this.collect_tokens_for_expr($attrs, |$this, attrs| {
498 let (hi, ex) = $body?;
499 Ok($this.mk_expr(lo.to(hi), ex, attrs.into()))
500 })
501 };
502 }
503
504 let this = self;
505
506 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
507 match this.token.uninterpolate().kind {
508 token::Not => make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Not)), // `!expr`
509 token::Tilde => make_it!(this, attrs, |this, _| this.recover_tilde_expr(lo)), // `~expr`
510 token::BinOp(token::Minus) => {
511 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Neg))
512 } // `-expr`
513 token::BinOp(token::Star) => {
514 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Deref))
515 } // `*expr`
516 token::BinOp(token::And) | token::AndAnd => {
517 make_it!(this, attrs, |this, _| this.parse_borrow_expr(lo))
518 }
519 token::Ident(..) if this.token.is_keyword(kw::Box) => {
520 make_it!(this, attrs, |this, _| this.parse_box_expr(lo))
521 }
522 token::Ident(..) if this.is_mistaken_not_ident_negation() => {
523 make_it!(this, attrs, |this, _| this.recover_not_expr(lo))
524 }
525 _ => return this.parse_dot_or_call_expr(Some(attrs)),
526 }
527 }
528
529 fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P<Expr>)> {
530 self.bump();
531 let expr = self.parse_prefix_expr(None);
532 let (span, expr) = self.interpolated_or_expr_span(expr)?;
533 Ok((lo.to(span), expr))
534 }
535
536 fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
537 let (span, expr) = self.parse_prefix_expr_common(lo)?;
538 Ok((span, self.mk_unary(op, expr)))
539 }
540
541 // Recover on `!` suggesting for bitwise negation instead.
542 fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
543 self.struct_span_err(lo, "`~` cannot be used as a unary operator")
544 .span_suggestion_short(
545 lo,
546 "use `!` to perform bitwise not",
547 "!".to_owned(),
548 Applicability::MachineApplicable,
549 )
550 .emit();
551
552 self.parse_unary_expr(lo, UnOp::Not)
553 }
554
555 /// Parse `box expr`.
556 fn parse_box_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
557 let (span, expr) = self.parse_prefix_expr_common(lo)?;
558 self.sess.gated_spans.gate(sym::box_syntax, span);
559 Ok((span, ExprKind::Box(expr)))
560 }
561
562 fn is_mistaken_not_ident_negation(&self) -> bool {
563 let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
564 // These tokens can start an expression after `!`, but
565 // can't continue an expression after an ident
566 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
567 token::Literal(..) | token::Pound => true,
568 _ => t.is_whole_expr(),
569 };
570 self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
571 }
572
573 /// Recover on `not expr` in favor of `!expr`.
574 fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
575 // Emit the error...
576 let not_token = self.look_ahead(1, |t| t.clone());
577 self.struct_span_err(
578 not_token.span,
579 &format!("unexpected {} after identifier", super::token_descr(&not_token)),
580 )
581 .span_suggestion_short(
582 // Span the `not` plus trailing whitespace to avoid
583 // trailing whitespace after the `!` in our suggestion
584 self.sess.source_map().span_until_non_whitespace(lo.to(not_token.span)),
585 "use `!` to perform logical negation",
586 "!".to_owned(),
587 Applicability::MachineApplicable,
588 )
589 .emit();
590
591 // ...and recover!
592 self.parse_unary_expr(lo, UnOp::Not)
593 }
594
595 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
596 fn interpolated_or_expr_span(
597 &self,
598 expr: PResult<'a, P<Expr>>,
599 ) -> PResult<'a, (Span, P<Expr>)> {
600 expr.map(|e| {
601 (
602 match self.prev_token.kind {
603 TokenKind::Interpolated(..) => self.prev_token.span,
604 _ => e.span,
605 },
606 e,
607 )
608 })
609 }
610
611 fn parse_assoc_op_cast(
612 &mut self,
613 lhs: P<Expr>,
614 lhs_span: Span,
615 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind,
616 ) -> PResult<'a, P<Expr>> {
617 let mk_expr = |this: &mut Self, lhs: P<Expr>, rhs: P<Ty>| {
618 this.mk_expr(
619 this.mk_expr_sp(&lhs, lhs_span, rhs.span),
620 expr_kind(lhs, rhs),
621 AttrVec::new(),
622 )
623 };
624
625 // Save the state of the parser before parsing type normally, in case there is a
626 // LessThan comparison after this cast.
627 let parser_snapshot_before_type = self.clone();
628 let cast_expr = match self.parse_ty_no_plus() {
629 Ok(rhs) => mk_expr(self, lhs, rhs),
630 Err(mut type_err) => {
631 // Rewind to before attempting to parse the type with generics, to recover
632 // from situations like `x as usize < y` in which we first tried to parse
633 // `usize < y` as a type with generic arguments.
634 let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
635
636 // Check for typo of `'a: loop { break 'a }` with a missing `'`.
637 match (&lhs.kind, &self.token.kind) {
638 (
639 // `foo: `
640 ExprKind::Path(None, ast::Path { segments, .. }),
641 TokenKind::Ident(kw::For | kw::Loop | kw::While, false),
642 ) if segments.len() == 1 => {
643 let snapshot = self.clone();
644 let label = Label {
645 ident: Ident::from_str_and_span(
646 &format!("'{}", segments[0].ident),
647 segments[0].ident.span,
648 ),
649 };
650 match self.parse_labeled_expr(label, AttrVec::new(), false) {
651 Ok(expr) => {
652 type_err.cancel();
653 self.struct_span_err(label.ident.span, "malformed loop label")
654 .span_suggestion(
655 label.ident.span,
656 "use the correct loop label format",
657 label.ident.to_string(),
658 Applicability::MachineApplicable,
659 )
660 .emit();
661 return Ok(expr);
662 }
663 Err(mut err) => {
664 err.cancel();
665 *self = snapshot;
666 }
667 }
668 }
669 _ => {}
670 }
671
672 match self.parse_path(PathStyle::Expr) {
673 Ok(path) => {
674 let (op_noun, op_verb) = match self.token.kind {
675 token::Lt => ("comparison", "comparing"),
676 token::BinOp(token::Shl) => ("shift", "shifting"),
677 _ => {
678 // We can end up here even without `<` being the next token, for
679 // example because `parse_ty_no_plus` returns `Err` on keywords,
680 // but `parse_path` returns `Ok` on them due to error recovery.
681 // Return original error and parser state.
682 *self = parser_snapshot_after_type;
683 return Err(type_err);
684 }
685 };
686
687 // Successfully parsed the type path leaving a `<` yet to parse.
688 type_err.cancel();
689
690 // Report non-fatal diagnostics, keep `x as usize` as an expression
691 // in AST and continue parsing.
692 let msg = format!(
693 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
694 pprust::path_to_string(&path),
695 op_noun,
696 );
697 let span_after_type = parser_snapshot_after_type.token.span;
698 let expr =
699 mk_expr(self, lhs, self.mk_ty(path.span, TyKind::Path(None, path)));
700
701 self.struct_span_err(self.token.span, &msg)
702 .span_label(
703 self.look_ahead(1, |t| t.span).to(span_after_type),
704 "interpreted as generic arguments",
705 )
706 .span_label(self.token.span, format!("not interpreted as {}", op_noun))
707 .multipart_suggestion(
708 &format!("try {} the cast value", op_verb),
709 vec![
710 (expr.span.shrink_to_lo(), "(".to_string()),
711 (expr.span.shrink_to_hi(), ")".to_string()),
712 ],
713 Applicability::MachineApplicable,
714 )
715 .emit();
716
717 expr
718 }
719 Err(mut path_err) => {
720 // Couldn't parse as a path, return original error and parser state.
721 path_err.cancel();
722 *self = parser_snapshot_after_type;
723 return Err(type_err);
724 }
725 }
726 }
727 };
728
729 self.parse_and_disallow_postfix_after_cast(cast_expr)
730 }
731
732 /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
733 /// then emits an error and returns the newly parsed tree.
734 /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
735 fn parse_and_disallow_postfix_after_cast(
736 &mut self,
737 cast_expr: P<Expr>,
738 ) -> PResult<'a, P<Expr>> {
739 // Save the memory location of expr before parsing any following postfix operators.
740 // This will be compared with the memory location of the output expression.
741 // If they different we can assume we parsed another expression because the existing expression is not reallocated.
742 let addr_before = &*cast_expr as *const _ as usize;
743 let span = cast_expr.span;
744 let with_postfix = self.parse_dot_or_call_expr_with_(cast_expr, span)?;
745 let changed = addr_before != &*with_postfix as *const _ as usize;
746
747 // Check if an illegal postfix operator has been added after the cast.
748 // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator.
749 if !matches!(with_postfix.kind, ExprKind::Cast(_, _) | ExprKind::Type(_, _)) || changed {
750 let msg = format!(
751 "casts cannot be followed by {}",
752 match with_postfix.kind {
753 ExprKind::Index(_, _) => "indexing",
754 ExprKind::Try(_) => "?",
755 ExprKind::Field(_, _) => "a field access",
756 ExprKind::MethodCall(_, _, _) => "a method call",
757 ExprKind::Call(_, _) => "a function call",
758 ExprKind::Await(_) => "`.await`",
759 ExprKind::Err => return Ok(with_postfix),
760 _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"),
761 }
762 );
763 let mut err = self.struct_span_err(span, &msg);
764 // If type ascription is "likely an error", the user will already be getting a useful
765 // help message, and doesn't need a second.
766 if self.last_type_ascription.map_or(false, |last_ascription| last_ascription.1) {
767 self.maybe_annotate_with_ascription(&mut err, false);
768 } else {
769 let suggestions = vec![
770 (span.shrink_to_lo(), "(".to_string()),
771 (span.shrink_to_hi(), ")".to_string()),
772 ];
773 err.multipart_suggestion(
774 "try surrounding the expression in parentheses",
775 suggestions,
776 Applicability::MachineApplicable,
777 );
778 }
779 err.emit();
780 };
781 Ok(with_postfix)
782 }
783
784 fn parse_assoc_op_ascribe(&mut self, lhs: P<Expr>, lhs_span: Span) -> PResult<'a, P<Expr>> {
785 let maybe_path = self.could_ascription_be_path(&lhs.kind);
786 self.last_type_ascription = Some((self.prev_token.span, maybe_path));
787 let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
788 self.sess.gated_spans.gate(sym::type_ascription, lhs.span);
789 Ok(lhs)
790 }
791
792 /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
793 fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
794 self.expect_and()?;
795 let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
796 let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
797 let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo);
798 let expr = self.parse_prefix_expr(None);
799 let (hi, expr) = self.interpolated_or_expr_span(expr)?;
800 let span = lo.to(hi);
801 if let Some(lt) = lifetime {
802 self.error_remove_borrow_lifetime(span, lt.ident.span);
803 }
804 Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
805 }
806
807 fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
808 self.struct_span_err(span, "borrow expressions cannot be annotated with lifetimes")
809 .span_label(lt_span, "annotated with lifetime here")
810 .span_suggestion(
811 lt_span,
812 "remove the lifetime annotation",
813 String::new(),
814 Applicability::MachineApplicable,
815 )
816 .emit();
817 }
818
819 /// Parse `mut?` or `raw [ const | mut ]`.
820 fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) {
821 if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) {
822 // `raw [ const | mut ]`.
823 let found_raw = self.eat_keyword(kw::Raw);
824 assert!(found_raw);
825 let mutability = self.parse_const_or_mut().unwrap();
826 self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span));
827 (ast::BorrowKind::Raw, mutability)
828 } else {
829 // `mut?`
830 (ast::BorrowKind::Ref, self.parse_mutability())
831 }
832 }
833
834 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
835 fn parse_dot_or_call_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
836 let attrs = self.parse_or_use_outer_attributes(attrs)?;
837 self.collect_tokens_for_expr(attrs, |this, attrs| {
838 let base = this.parse_bottom_expr();
839 let (span, base) = this.interpolated_or_expr_span(base)?;
840 this.parse_dot_or_call_expr_with(base, span, attrs)
841 })
842 }
843
844 pub(super) fn parse_dot_or_call_expr_with(
845 &mut self,
846 e0: P<Expr>,
847 lo: Span,
848 mut attrs: Vec<ast::Attribute>,
849 ) -> PResult<'a, P<Expr>> {
850 // Stitch the list of outer attributes onto the return value.
851 // A little bit ugly, but the best way given the current code
852 // structure
853 self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| {
854 expr.map(|mut expr| {
855 attrs.extend::<Vec<_>>(expr.attrs.into());
856 expr.attrs = attrs.into();
857 expr
858 })
859 })
860 }
861
862 fn parse_dot_or_call_expr_with_(&mut self, mut e: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
863 loop {
864 if self.eat(&token::Question) {
865 // `expr?`
866 e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e), AttrVec::new());
867 continue;
868 }
869 if self.eat(&token::Dot) {
870 // expr.f
871 e = self.parse_dot_suffix_expr(lo, e)?;
872 continue;
873 }
874 if self.expr_is_complete(&e) {
875 return Ok(e);
876 }
877 e = match self.token.kind {
878 token::OpenDelim(token::Paren) => self.parse_fn_call_expr(lo, e),
879 token::OpenDelim(token::Bracket) => self.parse_index_expr(lo, e)?,
880 _ => return Ok(e),
881 }
882 }
883 }
884
885 fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
886 match self.token.uninterpolate().kind {
887 token::Ident(..) => self.parse_dot_suffix(base, lo),
888 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
889 Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix, None))
890 }
891 token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => {
892 Ok(self.parse_tuple_field_access_expr_float(lo, base, symbol, suffix))
893 }
894 _ => {
895 self.error_unexpected_after_dot();
896 Ok(base)
897 }
898 }
899 }
900
901 fn error_unexpected_after_dot(&self) {
902 // FIXME Could factor this out into non_fatal_unexpected or something.
903 let actual = pprust::token_to_string(&self.token);
904 self.struct_span_err(self.token.span, &format!("unexpected token: `{}`", actual)).emit();
905 }
906
907 // We need an identifier or integer, but the next token is a float.
908 // Break the float into components to extract the identifier or integer.
909 // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
910 // parts unless those parts are processed immediately. `TokenCursor` should either
911 // support pushing "future tokens" (would be also helpful to `break_and_eat`), or
912 // we should break everything including floats into more basic proc-macro style
913 // tokens in the lexer (probably preferable).
914 fn parse_tuple_field_access_expr_float(
915 &mut self,
916 lo: Span,
917 base: P<Expr>,
918 float: Symbol,
919 suffix: Option<Symbol>,
920 ) -> P<Expr> {
921 #[derive(Debug)]
922 enum FloatComponent {
923 IdentLike(String),
924 Punct(char),
925 }
926 use FloatComponent::*;
927
928 let float_str = float.as_str();
929 let mut components = Vec::new();
930 let mut ident_like = String::new();
931 for c in float_str.chars() {
932 if c == '_' || c.is_ascii_alphanumeric() {
933 ident_like.push(c);
934 } else if matches!(c, '.' | '+' | '-') {
935 if !ident_like.is_empty() {
936 components.push(IdentLike(mem::take(&mut ident_like)));
937 }
938 components.push(Punct(c));
939 } else {
940 panic!("unexpected character in a float token: {:?}", c)
941 }
942 }
943 if !ident_like.is_empty() {
944 components.push(IdentLike(ident_like));
945 }
946
947 // With proc macros the span can refer to anything, the source may be too short,
948 // or too long, or non-ASCII. It only makes sense to break our span into components
949 // if its underlying text is identical to our float literal.
950 let span = self.token.span;
951 let can_take_span_apart =
952 || self.span_to_snippet(span).as_deref() == Ok(float_str).as_deref();
953
954 match &*components {
955 // 1e2
956 [IdentLike(i)] => {
957 self.parse_tuple_field_access_expr(lo, base, Symbol::intern(&i), suffix, None)
958 }
959 // 1.
960 [IdentLike(i), Punct('.')] => {
961 let (ident_span, dot_span) = if can_take_span_apart() {
962 let (span, ident_len) = (span.data(), BytePos::from_usize(i.len()));
963 let ident_span = span.with_hi(span.lo + ident_len);
964 let dot_span = span.with_lo(span.lo + ident_len);
965 (ident_span, dot_span)
966 } else {
967 (span, span)
968 };
969 assert!(suffix.is_none());
970 let symbol = Symbol::intern(&i);
971 self.token = Token::new(token::Ident(symbol, false), ident_span);
972 let next_token = (Token::new(token::Dot, dot_span), self.token_spacing);
973 self.parse_tuple_field_access_expr(lo, base, symbol, None, Some(next_token))
974 }
975 // 1.2 | 1.2e3
976 [IdentLike(i1), Punct('.'), IdentLike(i2)] => {
977 let (ident1_span, dot_span, ident2_span) = if can_take_span_apart() {
978 let (span, ident1_len) = (span.data(), BytePos::from_usize(i1.len()));
979 let ident1_span = span.with_hi(span.lo + ident1_len);
980 let dot_span = span
981 .with_lo(span.lo + ident1_len)
982 .with_hi(span.lo + ident1_len + BytePos(1));
983 let ident2_span = self.token.span.with_lo(span.lo + ident1_len + BytePos(1));
984 (ident1_span, dot_span, ident2_span)
985 } else {
986 (span, span, span)
987 };
988 let symbol1 = Symbol::intern(&i1);
989 self.token = Token::new(token::Ident(symbol1, false), ident1_span);
990 // This needs to be `Spacing::Alone` to prevent regressions.
991 // See issue #76399 and PR #76285 for more details
992 let next_token1 = (Token::new(token::Dot, dot_span), Spacing::Alone);
993 let base1 =
994 self.parse_tuple_field_access_expr(lo, base, symbol1, None, Some(next_token1));
995 let symbol2 = Symbol::intern(&i2);
996 let next_token2 = Token::new(token::Ident(symbol2, false), ident2_span);
997 self.bump_with((next_token2, self.token_spacing)); // `.`
998 self.parse_tuple_field_access_expr(lo, base1, symbol2, suffix, None)
999 }
1000 // 1e+ | 1e- (recovered)
1001 [IdentLike(_), Punct('+' | '-')] |
1002 // 1e+2 | 1e-2
1003 [IdentLike(_), Punct('+' | '-'), IdentLike(_)] |
1004 // 1.2e+3 | 1.2e-3
1005 [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-'), IdentLike(_)] => {
1006 // See the FIXME about `TokenCursor` above.
1007 self.error_unexpected_after_dot();
1008 base
1009 }
1010 _ => panic!("unexpected components in a float token: {:?}", components),
1011 }
1012 }
1013
1014 fn parse_tuple_field_access_expr(
1015 &mut self,
1016 lo: Span,
1017 base: P<Expr>,
1018 field: Symbol,
1019 suffix: Option<Symbol>,
1020 next_token: Option<(Token, Spacing)>,
1021 ) -> P<Expr> {
1022 match next_token {
1023 Some(next_token) => self.bump_with(next_token),
1024 None => self.bump(),
1025 }
1026 let span = self.prev_token.span;
1027 let field = ExprKind::Field(base, Ident::new(field, span));
1028 self.expect_no_suffix(span, "a tuple index", suffix);
1029 self.mk_expr(lo.to(span), field, AttrVec::new())
1030 }
1031
1032 /// Parse a function call expression, `expr(...)`.
1033 fn parse_fn_call_expr(&mut self, lo: Span, fun: P<Expr>) -> P<Expr> {
1034 let seq = self.parse_paren_expr_seq().map(|args| {
1035 self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args), AttrVec::new())
1036 });
1037 self.recover_seq_parse_error(token::Paren, lo, seq)
1038 }
1039
1040 /// Parse an indexing expression `expr[...]`.
1041 fn parse_index_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
1042 self.bump(); // `[`
1043 let index = self.parse_expr()?;
1044 self.expect(&token::CloseDelim(token::Bracket))?;
1045 Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_index(base, index), AttrVec::new()))
1046 }
1047
1048 /// Assuming we have just parsed `.`, continue parsing into an expression.
1049 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
1050 if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) {
1051 return Ok(self.mk_await_expr(self_arg, lo));
1052 }
1053
1054 let fn_span_lo = self.token.span;
1055 let mut segment = self.parse_path_segment(PathStyle::Expr)?;
1056 self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(token::Paren)]);
1057 self.check_turbofish_missing_angle_brackets(&mut segment);
1058
1059 if self.check(&token::OpenDelim(token::Paren)) {
1060 // Method call `expr.f()`
1061 let mut args = self.parse_paren_expr_seq()?;
1062 args.insert(0, self_arg);
1063
1064 let fn_span = fn_span_lo.to(self.prev_token.span);
1065 let span = lo.to(self.prev_token.span);
1066 Ok(self.mk_expr(span, ExprKind::MethodCall(segment, args, fn_span), AttrVec::new()))
1067 } else {
1068 // Field access `expr.f`
1069 if let Some(args) = segment.args {
1070 self.struct_span_err(
1071 args.span(),
1072 "field expressions cannot have generic arguments",
1073 )
1074 .emit();
1075 }
1076
1077 let span = lo.to(self.prev_token.span);
1078 Ok(self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), AttrVec::new()))
1079 }
1080 }
1081
1082 /// At the bottom (top?) of the precedence hierarchy,
1083 /// Parses things like parenthesized exprs, macros, `return`, etc.
1084 ///
1085 /// N.B., this does not parse outer attributes, and is private because it only works
1086 /// correctly if called from `parse_dot_or_call_expr()`.
1087 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1088 maybe_recover_from_interpolated_ty_qpath!(self, true);
1089 maybe_whole_expr!(self);
1090
1091 // Outer attributes are already parsed and will be
1092 // added to the return value after the fact.
1093 //
1094 // Therefore, prevent sub-parser from parsing
1095 // attributes by giving them an empty "already-parsed" list.
1096 let attrs = AttrVec::new();
1097
1098 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
1099 let lo = self.token.span;
1100 if let token::Literal(_) = self.token.kind {
1101 // This match arm is a special-case of the `_` match arm below and
1102 // could be removed without changing functionality, but it's faster
1103 // to have it here, especially for programs with large constants.
1104 self.parse_lit_expr(attrs)
1105 } else if self.check(&token::OpenDelim(token::Paren)) {
1106 self.parse_tuple_parens_expr(attrs)
1107 } else if self.check(&token::OpenDelim(token::Brace)) {
1108 self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs)
1109 } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) {
1110 self.parse_closure_expr(attrs)
1111 } else if self.check(&token::OpenDelim(token::Bracket)) {
1112 self.parse_array_or_repeat_expr(attrs)
1113 } else if self.check_path() {
1114 self.parse_path_start_expr(attrs)
1115 } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
1116 self.parse_closure_expr(attrs)
1117 } else if self.eat_keyword(kw::If) {
1118 self.parse_if_expr(attrs)
1119 } else if self.check_keyword(kw::For) {
1120 if self.choose_generics_over_qpath(1) {
1121 // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery,
1122 // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns.
1123 // When `for <Foo as Bar>::Proj in $expr $block` is wanted,
1124 // you can disambiguate in favor of a pattern with `(...)`.
1125 self.recover_quantified_closure_expr(attrs)
1126 } else {
1127 assert!(self.eat_keyword(kw::For));
1128 self.parse_for_expr(None, self.prev_token.span, attrs)
1129 }
1130 } else if self.eat_keyword(kw::While) {
1131 self.parse_while_expr(None, self.prev_token.span, attrs)
1132 } else if let Some(label) = self.eat_label() {
1133 self.parse_labeled_expr(label, attrs, true)
1134 } else if self.eat_keyword(kw::Loop) {
1135 self.parse_loop_expr(None, self.prev_token.span, attrs)
1136 } else if self.eat_keyword(kw::Continue) {
1137 let kind = ExprKind::Continue(self.eat_label());
1138 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1139 } else if self.eat_keyword(kw::Match) {
1140 let match_sp = self.prev_token.span;
1141 self.parse_match_expr(attrs).map_err(|mut err| {
1142 err.span_label(match_sp, "while parsing this match expression");
1143 err
1144 })
1145 } else if self.eat_keyword(kw::Unsafe) {
1146 self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs)
1147 } else if self.check_inline_const(0) {
1148 self.parse_const_block(lo.to(self.token.span))
1149 } else if self.is_do_catch_block() {
1150 self.recover_do_catch(attrs)
1151 } else if self.is_try_block() {
1152 self.expect_keyword(kw::Try)?;
1153 self.parse_try_block(lo, attrs)
1154 } else if self.eat_keyword(kw::Return) {
1155 self.parse_return_expr(attrs)
1156 } else if self.eat_keyword(kw::Break) {
1157 self.parse_break_expr(attrs)
1158 } else if self.eat_keyword(kw::Yield) {
1159 self.parse_yield_expr(attrs)
1160 } else if self.eat_keyword(kw::Let) {
1161 self.parse_let_expr(attrs)
1162 } else if self.eat_keyword(kw::Underscore) {
1163 self.sess.gated_spans.gate(sym::destructuring_assignment, self.prev_token.span);
1164 Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore, attrs))
1165 } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1166 // Don't complain about bare semicolons after unclosed braces
1167 // recovery in order to keep the error count down. Fixing the
1168 // delimiters will possibly also fix the bare semicolon found in
1169 // expression context. For example, silence the following error:
1170 //
1171 // error: expected expression, found `;`
1172 // --> file.rs:2:13
1173 // |
1174 // 2 | foo(bar(;
1175 // | ^ expected expression
1176 self.bump();
1177 Ok(self.mk_expr_err(self.token.span))
1178 } else if self.token.uninterpolated_span().rust_2018() {
1179 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1180 if self.check_keyword(kw::Async) {
1181 if self.is_async_block() {
1182 // Check for `async {` and `async move {`.
1183 self.parse_async_block(attrs)
1184 } else {
1185 self.parse_closure_expr(attrs)
1186 }
1187 } else if self.eat_keyword(kw::Await) {
1188 self.recover_incorrect_await_syntax(lo, self.prev_token.span, attrs)
1189 } else {
1190 self.parse_lit_expr(attrs)
1191 }
1192 } else {
1193 self.parse_lit_expr(attrs)
1194 }
1195 }
1196
1197 fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1198 let lo = self.token.span;
1199 match self.parse_opt_lit() {
1200 Some(literal) => {
1201 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs);
1202 self.maybe_recover_from_bad_qpath(expr, true)
1203 }
1204 None => self.try_macro_suggestion(),
1205 }
1206 }
1207
1208 fn parse_tuple_parens_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1209 let lo = self.token.span;
1210 self.expect(&token::OpenDelim(token::Paren))?;
1211 let (es, trailing_comma) = match self.parse_seq_to_end(
1212 &token::CloseDelim(token::Paren),
1213 SeqSep::trailing_allowed(token::Comma),
1214 |p| p.parse_expr_catch_underscore(),
1215 ) {
1216 Ok(x) => x,
1217 Err(err) => return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err))),
1218 };
1219 let kind = if es.len() == 1 && !trailing_comma {
1220 // `(e)` is parenthesized `e`.
1221 ExprKind::Paren(es.into_iter().next().unwrap())
1222 } else {
1223 // `(e,)` is a tuple with only one field, `e`.
1224 ExprKind::Tup(es)
1225 };
1226 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1227 self.maybe_recover_from_bad_qpath(expr, true)
1228 }
1229
1230 fn parse_array_or_repeat_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1231 let lo = self.token.span;
1232 self.bump(); // `[`
1233
1234 let close = &token::CloseDelim(token::Bracket);
1235 let kind = if self.eat(close) {
1236 // Empty vector
1237 ExprKind::Array(Vec::new())
1238 } else {
1239 // Non-empty vector
1240 let first_expr = self.parse_expr()?;
1241 if self.eat(&token::Semi) {
1242 // Repeating array syntax: `[ 0; 512 ]`
1243 let count = self.parse_anon_const_expr()?;
1244 self.expect(close)?;
1245 ExprKind::Repeat(first_expr, count)
1246 } else if self.eat(&token::Comma) {
1247 // Vector with two or more elements.
1248 let sep = SeqSep::trailing_allowed(token::Comma);
1249 let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1250 let mut exprs = vec![first_expr];
1251 exprs.extend(remaining_exprs);
1252 ExprKind::Array(exprs)
1253 } else {
1254 // Vector with one element
1255 self.expect(close)?;
1256 ExprKind::Array(vec![first_expr])
1257 }
1258 };
1259 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1260 self.maybe_recover_from_bad_qpath(expr, true)
1261 }
1262
1263 fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1264 let (qself, path) = if self.eat_lt() {
1265 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
1266 (Some(qself), path)
1267 } else {
1268 (None, self.parse_path(PathStyle::Expr)?)
1269 };
1270 let lo = path.span;
1271
1272 // `!`, as an operator, is prefix, so we know this isn't that.
1273 let (hi, kind) = if self.eat(&token::Not) {
1274 // MACRO INVOCATION expression
1275 if qself.is_some() {
1276 self.struct_span_err(path.span, "macros cannot use qualified paths").emit();
1277 }
1278 let mac = MacCall {
1279 path,
1280 args: self.parse_mac_args()?,
1281 prior_type_ascription: self.last_type_ascription,
1282 };
1283 (self.prev_token.span, ExprKind::MacCall(mac))
1284 } else if self.check(&token::OpenDelim(token::Brace)) {
1285 if let Some(expr) = self.maybe_parse_struct_expr(qself.as_ref(), &path, &attrs) {
1286 if qself.is_some() {
1287 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
1288 }
1289 return expr;
1290 } else {
1291 (path.span, ExprKind::Path(qself, path))
1292 }
1293 } else {
1294 (path.span, ExprKind::Path(qself, path))
1295 };
1296
1297 let expr = self.mk_expr(lo.to(hi), kind, attrs);
1298 self.maybe_recover_from_bad_qpath(expr, true)
1299 }
1300
1301 /// Parse `'label: $expr`. The label is already parsed.
1302 fn parse_labeled_expr(
1303 &mut self,
1304 label: Label,
1305 attrs: AttrVec,
1306 consume_colon: bool,
1307 ) -> PResult<'a, P<Expr>> {
1308 let lo = label.ident.span;
1309 let label = Some(label);
1310 let ate_colon = self.eat(&token::Colon);
1311 let expr = if self.eat_keyword(kw::While) {
1312 self.parse_while_expr(label, lo, attrs)
1313 } else if self.eat_keyword(kw::For) {
1314 self.parse_for_expr(label, lo, attrs)
1315 } else if self.eat_keyword(kw::Loop) {
1316 self.parse_loop_expr(label, lo, attrs)
1317 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1318 self.parse_block_expr(label, lo, BlockCheckMode::Default, attrs)
1319 } else {
1320 let msg = "expected `while`, `for`, `loop` or `{` after a label";
1321 self.struct_span_err(self.token.span, msg).span_label(self.token.span, msg).emit();
1322 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1323 self.parse_expr()
1324 }?;
1325
1326 if !ate_colon && consume_colon {
1327 self.error_labeled_expr_must_be_followed_by_colon(lo, expr.span);
1328 }
1329
1330 Ok(expr)
1331 }
1332
1333 fn error_labeled_expr_must_be_followed_by_colon(&self, lo: Span, span: Span) {
1334 self.struct_span_err(span, "labeled expression must be followed by `:`")
1335 .span_label(lo, "the label")
1336 .span_suggestion_short(
1337 lo.shrink_to_hi(),
1338 "add `:` after the label",
1339 ": ".to_string(),
1340 Applicability::MachineApplicable,
1341 )
1342 .note("labels are used before loops and blocks, allowing e.g., `break 'label` to them")
1343 .emit();
1344 }
1345
1346 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1347 fn recover_do_catch(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1348 let lo = self.token.span;
1349
1350 self.bump(); // `do`
1351 self.bump(); // `catch`
1352
1353 let span_dc = lo.to(self.prev_token.span);
1354 self.struct_span_err(span_dc, "found removed `do catch` syntax")
1355 .span_suggestion(
1356 span_dc,
1357 "replace with the new syntax",
1358 "try".to_string(),
1359 Applicability::MachineApplicable,
1360 )
1361 .note("following RFC #2388, the new non-placeholder syntax is `try`")
1362 .emit();
1363
1364 self.parse_try_block(lo, attrs)
1365 }
1366
1367 /// Parse an expression if the token can begin one.
1368 fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1369 Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1370 }
1371
1372 /// Parse `"return" expr?`.
1373 fn parse_return_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1374 let lo = self.prev_token.span;
1375 let kind = ExprKind::Ret(self.parse_expr_opt()?);
1376 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1377 self.maybe_recover_from_bad_qpath(expr, true)
1378 }
1379
1380 /// Parse `"break" (('label (:? expr)?) | expr?)` with `"break"` token already eaten.
1381 /// If the label is followed immediately by a `:` token, the label and `:` are
1382 /// parsed as part of the expression (i.e. a labeled loop). The language team has
1383 /// decided in #87026 to require parentheses as a visual aid to avoid confusion if
1384 /// the break expression of an unlabeled break is a labeled loop (as in
1385 /// `break 'lbl: loop {}`); a labeled break with an unlabeled loop as its value
1386 /// expression only gets a warning for compatibility reasons; and a labeled break
1387 /// with a labeled loop does not even get a warning because there is no ambiguity.
1388 fn parse_break_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1389 let lo = self.prev_token.span;
1390 let mut label = self.eat_label();
1391 let kind = if label.is_some() && self.token == token::Colon {
1392 // The value expression can be a labeled loop, see issue #86948, e.g.:
1393 // `loop { break 'label: loop { break 'label 42; }; }`
1394 let lexpr = self.parse_labeled_expr(label.take().unwrap(), AttrVec::new(), true)?;
1395 self.struct_span_err(
1396 lexpr.span,
1397 "parentheses are required around this expression to avoid confusion with a labeled break expression",
1398 )
1399 .multipart_suggestion(
1400 "wrap the expression in parentheses",
1401 vec![
1402 (lexpr.span.shrink_to_lo(), "(".to_string()),
1403 (lexpr.span.shrink_to_hi(), ")".to_string()),
1404 ],
1405 Applicability::MachineApplicable,
1406 )
1407 .emit();
1408 Some(lexpr)
1409 } else if self.token != token::OpenDelim(token::Brace)
1410 || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1411 {
1412 let expr = self.parse_expr_opt()?;
1413 if let Some(ref expr) = expr {
1414 if label.is_some()
1415 && matches!(
1416 expr.kind,
1417 ExprKind::While(_, _, None)
1418 | ExprKind::ForLoop(_, _, _, None)
1419 | ExprKind::Loop(_, None)
1420 | ExprKind::Block(_, None)
1421 )
1422 {
1423 self.sess.buffer_lint_with_diagnostic(
1424 BREAK_WITH_LABEL_AND_LOOP,
1425 lo.to(expr.span),
1426 ast::CRATE_NODE_ID,
1427 "this labeled break expression is easy to confuse with an unlabeled break with a labeled value expression",
1428 BuiltinLintDiagnostics::BreakWithLabelAndLoop(expr.span),
1429 );
1430 }
1431 }
1432 expr
1433 } else {
1434 None
1435 };
1436 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind), attrs);
1437 self.maybe_recover_from_bad_qpath(expr, true)
1438 }
1439
1440 /// Parse `"yield" expr?`.
1441 fn parse_yield_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1442 let lo = self.prev_token.span;
1443 let kind = ExprKind::Yield(self.parse_expr_opt()?);
1444 let span = lo.to(self.prev_token.span);
1445 self.sess.gated_spans.gate(sym::generators, span);
1446 let expr = self.mk_expr(span, kind, attrs);
1447 self.maybe_recover_from_bad_qpath(expr, true)
1448 }
1449
1450 /// Returns a string literal if the next token is a string literal.
1451 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1452 /// and returns `None` if the next token is not literal at all.
1453 pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
1454 match self.parse_opt_lit() {
1455 Some(lit) => match lit.kind {
1456 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1457 style,
1458 symbol: lit.token.symbol,
1459 suffix: lit.token.suffix,
1460 span: lit.span,
1461 symbol_unescaped,
1462 }),
1463 _ => Err(Some(lit)),
1464 },
1465 None => Err(None),
1466 }
1467 }
1468
1469 pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> {
1470 self.parse_opt_lit().ok_or_else(|| {
1471 let msg = format!("unexpected token: {}", super::token_descr(&self.token));
1472 self.struct_span_err(self.token.span, &msg)
1473 })
1474 }
1475
1476 /// Matches `lit = true | false | token_lit`.
1477 /// Returns `None` if the next token is not a literal.
1478 pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
1479 let mut recovered = None;
1480 if self.token == token::Dot {
1481 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1482 // dot would follow an optional literal, so we do this unconditionally.
1483 recovered = self.look_ahead(1, |next_token| {
1484 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1485 next_token.kind
1486 {
1487 if self.token.span.hi() == next_token.span.lo() {
1488 let s = String::from("0.") + &symbol.as_str();
1489 let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1490 return Some(Token::new(kind, self.token.span.to(next_token.span)));
1491 }
1492 }
1493 None
1494 });
1495 if let Some(token) = &recovered {
1496 self.bump();
1497 self.error_float_lits_must_have_int_part(&token);
1498 }
1499 }
1500
1501 let token = recovered.as_ref().unwrap_or(&self.token);
1502 match Lit::from_token(token) {
1503 Ok(lit) => {
1504 self.bump();
1505 Some(lit)
1506 }
1507 Err(LitError::NotLiteral) => None,
1508 Err(err) => {
1509 let span = token.span;
1510 let lit = match token.kind {
1511 token::Literal(lit) => lit,
1512 _ => unreachable!(),
1513 };
1514 self.bump();
1515 self.report_lit_error(err, lit, span);
1516 // Pack possible quotes and prefixes from the original literal into
1517 // the error literal's symbol so they can be pretty-printed faithfully.
1518 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1519 let symbol = Symbol::intern(&suffixless_lit.to_string());
1520 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1521 Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!()))
1522 }
1523 }
1524 }
1525
1526 fn error_float_lits_must_have_int_part(&self, token: &Token) {
1527 self.struct_span_err(token.span, "float literals must have an integer part")
1528 .span_suggestion(
1529 token.span,
1530 "must have an integer part",
1531 pprust::token_to_string(token).into(),
1532 Applicability::MachineApplicable,
1533 )
1534 .emit();
1535 }
1536
1537 fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) {
1538 // Checks if `s` looks like i32 or u1234 etc.
1539 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1540 s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
1541 }
1542
1543 let token::Lit { kind, suffix, .. } = lit;
1544 match err {
1545 // `NotLiteral` is not an error by itself, so we don't report
1546 // it and give the parser opportunity to try something else.
1547 LitError::NotLiteral => {}
1548 // `LexerError` *is* an error, but it was already reported
1549 // by lexer, so here we don't report it the second time.
1550 LitError::LexerError => {}
1551 LitError::InvalidSuffix => {
1552 self.expect_no_suffix(
1553 span,
1554 &format!("{} {} literal", kind.article(), kind.descr()),
1555 suffix,
1556 );
1557 }
1558 LitError::InvalidIntSuffix => {
1559 let suf = suffix.expect("suffix error with no suffix").as_str();
1560 if looks_like_width_suffix(&['i', 'u'], &suf) {
1561 // If it looks like a width, try to be helpful.
1562 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
1563 self.struct_span_err(span, &msg)
1564 .help("valid widths are 8, 16, 32, 64 and 128")
1565 .emit();
1566 } else {
1567 let msg = format!("invalid suffix `{}` for number literal", suf);
1568 self.struct_span_err(span, &msg)
1569 .span_label(span, format!("invalid suffix `{}`", suf))
1570 .help("the suffix must be one of the numeric types (`u32`, `isize`, `f32`, etc.)")
1571 .emit();
1572 }
1573 }
1574 LitError::InvalidFloatSuffix => {
1575 let suf = suffix.expect("suffix error with no suffix").as_str();
1576 if looks_like_width_suffix(&['f'], &suf) {
1577 // If it looks like a width, try to be helpful.
1578 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
1579 self.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit();
1580 } else {
1581 let msg = format!("invalid suffix `{}` for float literal", suf);
1582 self.struct_span_err(span, &msg)
1583 .span_label(span, format!("invalid suffix `{}`", suf))
1584 .help("valid suffixes are `f32` and `f64`")
1585 .emit();
1586 }
1587 }
1588 LitError::NonDecimalFloat(base) => {
1589 let descr = match base {
1590 16 => "hexadecimal",
1591 8 => "octal",
1592 2 => "binary",
1593 _ => unreachable!(),
1594 };
1595 self.struct_span_err(span, &format!("{} float literal is not supported", descr))
1596 .span_label(span, "not supported")
1597 .emit();
1598 }
1599 LitError::IntTooLarge => {
1600 self.struct_span_err(span, "integer literal is too large").emit();
1601 }
1602 }
1603 }
1604
1605 pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) {
1606 if let Some(suf) = suffix {
1607 let mut err = if kind == "a tuple index"
1608 && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf)
1609 {
1610 // #59553: warn instead of reject out of hand to allow the fix to percolate
1611 // through the ecosystem when people fix their macros
1612 let mut err = self
1613 .sess
1614 .span_diagnostic
1615 .struct_span_warn(sp, &format!("suffixes on {} are invalid", kind));
1616 err.note(&format!(
1617 "`{}` is *temporarily* accepted on tuple index fields as it was \
1618 incorrectly accepted on stable for a few releases",
1619 suf,
1620 ));
1621 err.help(
1622 "on proc macros, you'll want to use `syn::Index::from` or \
1623 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1624 to tuple field access",
1625 );
1626 err.note(
1627 "see issue #60210 <https://github.com/rust-lang/rust/issues/60210> \
1628 for more information",
1629 );
1630 err
1631 } else {
1632 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1633 };
1634 err.span_label(sp, format!("invalid suffix `{}`", suf));
1635 err.emit();
1636 }
1637 }
1638
1639 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1640 /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
1641 pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1642 maybe_whole_expr!(self);
1643
1644 let lo = self.token.span;
1645 let minus_present = self.eat(&token::BinOp(token::Minus));
1646 let lit = self.parse_lit()?;
1647 let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new());
1648
1649 if minus_present {
1650 Ok(self.mk_expr(
1651 lo.to(self.prev_token.span),
1652 self.mk_unary(UnOp::Neg, expr),
1653 AttrVec::new(),
1654 ))
1655 } else {
1656 Ok(expr)
1657 }
1658 }
1659
1660 /// Parses a block or unsafe block.
1661 pub(super) fn parse_block_expr(
1662 &mut self,
1663 opt_label: Option<Label>,
1664 lo: Span,
1665 blk_mode: BlockCheckMode,
1666 mut attrs: AttrVec,
1667 ) -> PResult<'a, P<Expr>> {
1668 if let Some(label) = opt_label {
1669 self.sess.gated_spans.gate(sym::label_break_value, label.ident.span);
1670 }
1671
1672 if self.token.is_whole_block() {
1673 self.struct_span_err(self.token.span, "cannot use a `block` macro fragment here")
1674 .span_label(lo.to(self.token.span), "the `block` fragment is within this context")
1675 .emit();
1676 }
1677
1678 let (inner_attrs, blk) = self.parse_block_common(lo, blk_mode)?;
1679 attrs.extend(inner_attrs);
1680 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs))
1681 }
1682
1683 /// Recover on an explicitly quantified closure expression, e.g., `for<'a> |x: &'a u8| *x + 1`.
1684 fn recover_quantified_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1685 let lo = self.token.span;
1686 let _ = self.parse_late_bound_lifetime_defs()?;
1687 let span_for = lo.to(self.prev_token.span);
1688 let closure = self.parse_closure_expr(attrs)?;
1689
1690 self.struct_span_err(span_for, "cannot introduce explicit parameters for a closure")
1691 .span_label(closure.span, "the parameters are attached to this closure")
1692 .span_suggestion(
1693 span_for,
1694 "remove the parameters",
1695 String::new(),
1696 Applicability::MachineApplicable,
1697 )
1698 .emit();
1699
1700 Ok(self.mk_expr_err(lo.to(closure.span)))
1701 }
1702
1703 /// Parses a closure expression (e.g., `move |args| expr`).
1704 fn parse_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1705 let lo = self.token.span;
1706
1707 let movability =
1708 if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
1709
1710 let asyncness = if self.token.uninterpolated_span().rust_2018() {
1711 self.parse_asyncness()
1712 } else {
1713 Async::No
1714 };
1715
1716 let capture_clause = self.parse_capture_clause()?;
1717 let decl = self.parse_fn_block_decl()?;
1718 let decl_hi = self.prev_token.span;
1719 let body = match decl.output {
1720 FnRetTy::Default(_) => {
1721 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
1722 self.parse_expr_res(restrictions, None)?
1723 }
1724 _ => {
1725 // If an explicit return type is given, require a block to appear (RFC 968).
1726 let body_lo = self.token.span;
1727 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, AttrVec::new())?
1728 }
1729 };
1730
1731 if let Async::Yes { span, .. } = asyncness {
1732 // Feature-gate `async ||` closures.
1733 self.sess.gated_spans.gate(sym::async_closure, span);
1734 }
1735
1736 Ok(self.mk_expr(
1737 lo.to(body.span),
1738 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
1739 attrs,
1740 ))
1741 }
1742
1743 /// Parses an optional `move` prefix to a closure-like construct.
1744 fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> {
1745 if self.eat_keyword(kw::Move) {
1746 // Check for `move async` and recover
1747 if self.check_keyword(kw::Async) {
1748 let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
1749 Err(self.incorrect_move_async_order_found(move_async_span))
1750 } else {
1751 Ok(CaptureBy::Value)
1752 }
1753 } else {
1754 Ok(CaptureBy::Ref)
1755 }
1756 }
1757
1758 /// Parses the `|arg, arg|` header of a closure.
1759 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
1760 let inputs = if self.eat(&token::OrOr) {
1761 Vec::new()
1762 } else {
1763 self.expect(&token::BinOp(token::Or))?;
1764 let args = self
1765 .parse_seq_to_before_tokens(
1766 &[&token::BinOp(token::Or), &token::OrOr],
1767 SeqSep::trailing_allowed(token::Comma),
1768 TokenExpectType::NoExpect,
1769 |p| p.parse_fn_block_param(),
1770 )?
1771 .0;
1772 self.expect_or()?;
1773 args
1774 };
1775 let output =
1776 self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes, RecoverReturnSign::Yes)?;
1777
1778 Ok(P(FnDecl { inputs, output }))
1779 }
1780
1781 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1782 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
1783 let lo = self.token.span;
1784 let attrs = self.parse_outer_attributes()?;
1785 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1786 let pat = this.parse_pat_no_top_alt(PARAM_EXPECTED)?;
1787 let ty = if this.eat(&token::Colon) {
1788 this.parse_ty()?
1789 } else {
1790 this.mk_ty(this.prev_token.span, TyKind::Infer)
1791 };
1792
1793 Ok((
1794 Param {
1795 attrs: attrs.into(),
1796 ty,
1797 pat,
1798 span: lo.to(this.token.span),
1799 id: DUMMY_NODE_ID,
1800 is_placeholder: false,
1801 },
1802 TrailingToken::MaybeComma,
1803 ))
1804 })
1805 }
1806
1807 /// Parses an `if` expression (`if` token already eaten).
1808 fn parse_if_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1809 let lo = self.prev_token.span;
1810 let cond = self.parse_cond_expr()?;
1811
1812 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1813 // verify that the last statement is either an implicit return (no `;`) or an explicit
1814 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1815 // the dead code lint.
1816 let thn = if self.eat_keyword(kw::Else) || !cond.returns() {
1817 self.error_missing_if_cond(lo, cond.span)
1818 } else {
1819 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
1820 let not_block = self.token != token::OpenDelim(token::Brace);
1821 let block = self.parse_block().map_err(|mut err| {
1822 if not_block {
1823 err.span_label(lo, "this `if` expression has a condition, but no block");
1824 if let ExprKind::Binary(_, _, ref right) = cond.kind {
1825 if let ExprKind::Block(_, _) = right.kind {
1826 err.help("maybe you forgot the right operand of the condition?");
1827 }
1828 }
1829 }
1830 err
1831 })?;
1832 self.error_on_if_block_attrs(lo, false, block.span, &attrs);
1833 block
1834 };
1835 let els = if self.eat_keyword(kw::Else) { Some(self.parse_else_expr()?) } else { None };
1836 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els), attrs))
1837 }
1838
1839 fn error_missing_if_cond(&self, lo: Span, span: Span) -> P<ast::Block> {
1840 let sp = self.sess.source_map().next_point(lo);
1841 self.struct_span_err(sp, "missing condition for `if` expression")
1842 .span_label(sp, "expected if condition here")
1843 .emit();
1844 self.mk_block_err(span)
1845 }
1846
1847 /// Parses the condition of a `if` or `while` expression.
1848 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
1849 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1850
1851 if let ExprKind::Let(..) = cond.kind {
1852 // Remove the last feature gating of a `let` expression since it's stable.
1853 self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
1854 }
1855
1856 Ok(cond)
1857 }
1858
1859 /// Parses a `let $pat = $expr` pseudo-expression.
1860 /// The `let` token has already been eaten.
1861 fn parse_let_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1862 let lo = self.prev_token.span;
1863 let pat = self.parse_pat_allow_top_alt(None, RecoverComma::Yes, RecoverColon::Yes)?;
1864 self.expect(&token::Eq)?;
1865 let expr = self.with_res(self.restrictions | Restrictions::NO_STRUCT_LITERAL, |this| {
1866 this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
1867 })?;
1868 let span = lo.to(expr.span);
1869 self.sess.gated_spans.gate(sym::let_chains, span);
1870 Ok(self.mk_expr(span, ExprKind::Let(pat, expr, span), attrs))
1871 }
1872
1873 /// Parses an `else { ... }` expression (`else` token already eaten).
1874 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
1875 let ctx_span = self.prev_token.span; // `else`
1876 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
1877 let expr = if self.eat_keyword(kw::If) {
1878 self.parse_if_expr(AttrVec::new())?
1879 } else {
1880 let blk = self.parse_block()?;
1881 self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new())
1882 };
1883 self.error_on_if_block_attrs(ctx_span, true, expr.span, &attrs);
1884 Ok(expr)
1885 }
1886
1887 fn error_on_if_block_attrs(
1888 &self,
1889 ctx_span: Span,
1890 is_ctx_else: bool,
1891 branch_span: Span,
1892 attrs: &[ast::Attribute],
1893 ) {
1894 let (span, last) = match attrs {
1895 [] => return,
1896 [x0 @ xn] | [x0, .., xn] => (x0.span.to(xn.span), xn.span),
1897 };
1898 let ctx = if is_ctx_else { "else" } else { "if" };
1899 self.struct_span_err(last, "outer attributes are not allowed on `if` and `else` branches")
1900 .span_label(branch_span, "the attributes are attached to this branch")
1901 .span_label(ctx_span, format!("the branch belongs to this `{}`", ctx))
1902 .span_suggestion(
1903 span,
1904 "remove the attributes",
1905 String::new(),
1906 Applicability::MachineApplicable,
1907 )
1908 .emit();
1909 }
1910
1911 /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
1912 fn parse_for_expr(
1913 &mut self,
1914 opt_label: Option<Label>,
1915 lo: Span,
1916 mut attrs: AttrVec,
1917 ) -> PResult<'a, P<Expr>> {
1918 // Record whether we are about to parse `for (`.
1919 // This is used below for recovery in case of `for ( $stuff ) $block`
1920 // in which case we will suggest `for $stuff $block`.
1921 let begin_paren = match self.token.kind {
1922 token::OpenDelim(token::Paren) => Some(self.token.span),
1923 _ => None,
1924 };
1925
1926 let pat = self.parse_pat_allow_top_alt(None, RecoverComma::Yes, RecoverColon::Yes)?;
1927 if !self.eat_keyword(kw::In) {
1928 self.error_missing_in_for_loop();
1929 }
1930 self.check_for_for_in_in_typo(self.prev_token.span);
1931 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1932
1933 let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
1934
1935 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
1936 attrs.extend(iattrs);
1937
1938 let kind = ExprKind::ForLoop(pat, expr, loop_block, opt_label);
1939 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1940 }
1941
1942 fn error_missing_in_for_loop(&mut self) {
1943 let (span, msg, sugg) = if self.token.is_ident_named(sym::of) {
1944 // Possibly using JS syntax (#75311).
1945 let span = self.token.span;
1946 self.bump();
1947 (span, "try using `in` here instead", "in")
1948 } else {
1949 (self.prev_token.span.between(self.token.span), "try adding `in` here", " in ")
1950 };
1951 self.struct_span_err(span, "missing `in` in `for` loop")
1952 .span_suggestion_short(
1953 span,
1954 msg,
1955 sugg.into(),
1956 // Has been misleading, at least in the past (closed Issue #48492).
1957 Applicability::MaybeIncorrect,
1958 )
1959 .emit();
1960 }
1961
1962 /// Parses a `while` or `while let` expression (`while` token already eaten).
1963 fn parse_while_expr(
1964 &mut self,
1965 opt_label: Option<Label>,
1966 lo: Span,
1967 mut attrs: AttrVec,
1968 ) -> PResult<'a, P<Expr>> {
1969 let cond = self.parse_cond_expr()?;
1970 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1971 attrs.extend(iattrs);
1972 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::While(cond, body, opt_label), attrs))
1973 }
1974
1975 /// Parses `loop { ... }` (`loop` token already eaten).
1976 fn parse_loop_expr(
1977 &mut self,
1978 opt_label: Option<Label>,
1979 lo: Span,
1980 mut attrs: AttrVec,
1981 ) -> PResult<'a, P<Expr>> {
1982 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1983 attrs.extend(iattrs);
1984 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::Loop(body, opt_label), attrs))
1985 }
1986
1987 fn eat_label(&mut self) -> Option<Label> {
1988 self.token.lifetime().map(|ident| {
1989 self.bump();
1990 Label { ident }
1991 })
1992 }
1993
1994 /// Parses a `match ... { ... }` expression (`match` token already eaten).
1995 fn parse_match_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
1996 let match_span = self.prev_token.span;
1997 let lo = self.prev_token.span;
1998 let scrutinee = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1999 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
2000 if self.token == token::Semi {
2001 e.span_suggestion_short(
2002 match_span,
2003 "try removing this `match`",
2004 String::new(),
2005 Applicability::MaybeIncorrect, // speculative
2006 );
2007 }
2008 return Err(e);
2009 }
2010 attrs.extend(self.parse_inner_attributes()?);
2011
2012 let mut arms: Vec<Arm> = Vec::new();
2013 while self.token != token::CloseDelim(token::Brace) {
2014 match self.parse_arm() {
2015 Ok(arm) => arms.push(arm),
2016 Err(mut e) => {
2017 // Recover by skipping to the end of the block.
2018 e.emit();
2019 self.recover_stmt();
2020 let span = lo.to(self.token.span);
2021 if self.token == token::CloseDelim(token::Brace) {
2022 self.bump();
2023 }
2024 return Ok(self.mk_expr(span, ExprKind::Match(scrutinee, arms), attrs));
2025 }
2026 }
2027 }
2028 let hi = self.token.span;
2029 self.bump();
2030 Ok(self.mk_expr(lo.to(hi), ExprKind::Match(scrutinee, arms), attrs))
2031 }
2032
2033 /// Attempt to recover from match arm body with statements and no surrounding braces.
2034 fn parse_arm_body_missing_braces(
2035 &mut self,
2036 first_expr: &P<Expr>,
2037 arrow_span: Span,
2038 ) -> Option<P<Expr>> {
2039 if self.token.kind != token::Semi {
2040 return None;
2041 }
2042 let start_snapshot = self.clone();
2043 let semi_sp = self.token.span;
2044 self.bump(); // `;`
2045 let mut stmts =
2046 vec![self.mk_stmt(first_expr.span, ast::StmtKind::Expr(first_expr.clone()))];
2047 let err = |this: &mut Parser<'_>, stmts: Vec<ast::Stmt>| {
2048 let span = stmts[0].span.to(stmts[stmts.len() - 1].span);
2049 let mut err = this.struct_span_err(span, "`match` arm body without braces");
2050 let (these, s, are) =
2051 if stmts.len() > 1 { ("these", "s", "are") } else { ("this", "", "is") };
2052 err.span_label(
2053 span,
2054 &format!(
2055 "{these} statement{s} {are} not surrounded by a body",
2056 these = these,
2057 s = s,
2058 are = are
2059 ),
2060 );
2061 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2062 if stmts.len() > 1 {
2063 err.multipart_suggestion(
2064 &format!("surround the statement{} with a body", s),
2065 vec![
2066 (span.shrink_to_lo(), "{ ".to_string()),
2067 (span.shrink_to_hi(), " }".to_string()),
2068 ],
2069 Applicability::MachineApplicable,
2070 );
2071 } else {
2072 err.span_suggestion(
2073 semi_sp,
2074 "use a comma to end a `match` arm expression",
2075 ",".to_string(),
2076 Applicability::MachineApplicable,
2077 );
2078 }
2079 err.emit();
2080 this.mk_expr_err(span)
2081 };
2082 // We might have either a `,` -> `;` typo, or a block without braces. We need
2083 // a more subtle parsing strategy.
2084 loop {
2085 if self.token.kind == token::CloseDelim(token::Brace) {
2086 // We have reached the closing brace of the `match` expression.
2087 return Some(err(self, stmts));
2088 }
2089 if self.token.kind == token::Comma {
2090 *self = start_snapshot;
2091 return None;
2092 }
2093 let pre_pat_snapshot = self.clone();
2094 match self.parse_pat_no_top_alt(None) {
2095 Ok(_pat) => {
2096 if self.token.kind == token::FatArrow {
2097 // Reached arm end.
2098 *self = pre_pat_snapshot;
2099 return Some(err(self, stmts));
2100 }
2101 }
2102 Err(mut err) => {
2103 err.cancel();
2104 }
2105 }
2106
2107 *self = pre_pat_snapshot;
2108 match self.parse_stmt_without_recovery(true, ForceCollect::No) {
2109 // Consume statements for as long as possible.
2110 Ok(Some(stmt)) => {
2111 stmts.push(stmt);
2112 }
2113 Ok(None) => {
2114 *self = start_snapshot;
2115 break;
2116 }
2117 // We couldn't parse either yet another statement missing it's
2118 // enclosing block nor the next arm's pattern or closing brace.
2119 Err(mut stmt_err) => {
2120 stmt_err.cancel();
2121 *self = start_snapshot;
2122 break;
2123 }
2124 }
2125 }
2126 None
2127 }
2128
2129 pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
2130 let attrs = self.parse_outer_attributes()?;
2131 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2132 let lo = this.token.span;
2133 let pat = this.parse_pat_allow_top_alt(None, RecoverComma::Yes, RecoverColon::Yes)?;
2134 let guard = if this.eat_keyword(kw::If) {
2135 let if_span = this.prev_token.span;
2136 let cond = this.parse_expr()?;
2137 if let ExprKind::Let(..) = cond.kind {
2138 // Remove the last feature gating of a `let` expression since it's stable.
2139 this.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2140 let span = if_span.to(cond.span);
2141 this.sess.gated_spans.gate(sym::if_let_guard, span);
2142 }
2143 Some(cond)
2144 } else {
2145 None
2146 };
2147 let arrow_span = this.token.span;
2148 this.expect(&token::FatArrow)?;
2149 let arm_start_span = this.token.span;
2150
2151 let expr = this.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| {
2152 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2153 err
2154 })?;
2155
2156 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
2157 && this.token != token::CloseDelim(token::Brace);
2158
2159 let hi = this.prev_token.span;
2160
2161 if require_comma {
2162 let sm = this.sess.source_map();
2163 if let Some(body) = this.parse_arm_body_missing_braces(&expr, arrow_span) {
2164 let span = body.span;
2165 return Ok((
2166 ast::Arm {
2167 attrs: attrs.into(),
2168 pat,
2169 guard,
2170 body,
2171 span,
2172 id: DUMMY_NODE_ID,
2173 is_placeholder: false,
2174 },
2175 TrailingToken::None,
2176 ));
2177 }
2178 this.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]).map_err(
2179 |mut err| {
2180 match (sm.span_to_lines(expr.span), sm.span_to_lines(arm_start_span)) {
2181 (Ok(ref expr_lines), Ok(ref arm_start_lines))
2182 if arm_start_lines.lines[0].end_col
2183 == expr_lines.lines[0].end_col
2184 && expr_lines.lines.len() == 2
2185 && this.token == token::FatArrow =>
2186 {
2187 // We check whether there's any trailing code in the parse span,
2188 // if there isn't, we very likely have the following:
2189 //
2190 // X | &Y => "y"
2191 // | -- - missing comma
2192 // | |
2193 // | arrow_span
2194 // X | &X => "x"
2195 // | - ^^ self.token.span
2196 // | |
2197 // | parsed until here as `"y" & X`
2198 err.span_suggestion_short(
2199 arm_start_span.shrink_to_hi(),
2200 "missing a comma here to end this `match` arm",
2201 ",".to_owned(),
2202 Applicability::MachineApplicable,
2203 );
2204 }
2205 _ => {
2206 err.span_label(
2207 arrow_span,
2208 "while parsing the `match` arm starting here",
2209 );
2210 }
2211 }
2212 err
2213 },
2214 )?;
2215 } else {
2216 this.eat(&token::Comma);
2217 }
2218
2219 Ok((
2220 ast::Arm {
2221 attrs: attrs.into(),
2222 pat,
2223 guard,
2224 body: expr,
2225 span: lo.to(hi),
2226 id: DUMMY_NODE_ID,
2227 is_placeholder: false,
2228 },
2229 TrailingToken::None,
2230 ))
2231 })
2232 }
2233
2234 /// Parses a `try {...}` expression (`try` token already eaten).
2235 fn parse_try_block(&mut self, span_lo: Span, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2236 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2237 attrs.extend(iattrs);
2238 if self.eat_keyword(kw::Catch) {
2239 let mut error = self.struct_span_err(
2240 self.prev_token.span,
2241 "keyword `catch` cannot follow a `try` block",
2242 );
2243 error.help("try using `match` on the result of the `try` block instead");
2244 error.emit();
2245 Err(error)
2246 } else {
2247 let span = span_lo.to(body.span);
2248 self.sess.gated_spans.gate(sym::try_blocks, span);
2249 Ok(self.mk_expr(span, ExprKind::TryBlock(body), attrs))
2250 }
2251 }
2252
2253 fn is_do_catch_block(&self) -> bool {
2254 self.token.is_keyword(kw::Do)
2255 && self.is_keyword_ahead(1, &[kw::Catch])
2256 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2257 && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
2258 }
2259
2260 fn is_try_block(&self) -> bool {
2261 self.token.is_keyword(kw::Try)
2262 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2263 && self.token.uninterpolated_span().rust_2018()
2264 }
2265
2266 /// Parses an `async move? {...}` expression.
2267 fn parse_async_block(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2268 let lo = self.token.span;
2269 self.expect_keyword(kw::Async)?;
2270 let capture_clause = self.parse_capture_clause()?;
2271 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2272 attrs.extend(iattrs);
2273 let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);
2274 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
2275 }
2276
2277 fn is_async_block(&self) -> bool {
2278 self.token.is_keyword(kw::Async)
2279 && ((
2280 // `async move {`
2281 self.is_keyword_ahead(1, &[kw::Move])
2282 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2283 ) || (
2284 // `async {`
2285 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2286 ))
2287 }
2288
2289 fn is_certainly_not_a_block(&self) -> bool {
2290 self.look_ahead(1, |t| t.is_ident())
2291 && (
2292 // `{ ident, ` cannot start a block.
2293 self.look_ahead(2, |t| t == &token::Comma)
2294 || self.look_ahead(2, |t| t == &token::Colon)
2295 && (
2296 // `{ ident: token, ` cannot start a block.
2297 self.look_ahead(4, |t| t == &token::Comma) ||
2298 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
2299 self.look_ahead(3, |t| !t.can_begin_type())
2300 )
2301 )
2302 }
2303
2304 fn maybe_parse_struct_expr(
2305 &mut self,
2306 qself: Option<&ast::QSelf>,
2307 path: &ast::Path,
2308 attrs: &AttrVec,
2309 ) -> Option<PResult<'a, P<Expr>>> {
2310 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2311 if struct_allowed || self.is_certainly_not_a_block() {
2312 if let Err(err) = self.expect(&token::OpenDelim(token::Brace)) {
2313 return Some(Err(err));
2314 }
2315 let expr = self.parse_struct_expr(qself.cloned(), path.clone(), attrs.clone(), true);
2316 if let (Ok(expr), false) = (&expr, struct_allowed) {
2317 // This is a struct literal, but we don't can't accept them here.
2318 self.error_struct_lit_not_allowed_here(path.span, expr.span);
2319 }
2320 return Some(expr);
2321 }
2322 None
2323 }
2324
2325 fn error_struct_lit_not_allowed_here(&self, lo: Span, sp: Span) {
2326 self.struct_span_err(sp, "struct literals are not allowed here")
2327 .multipart_suggestion(
2328 "surround the struct literal with parentheses",
2329 vec![(lo.shrink_to_lo(), "(".to_string()), (sp.shrink_to_hi(), ")".to_string())],
2330 Applicability::MachineApplicable,
2331 )
2332 .emit();
2333 }
2334
2335 /// Precondition: already parsed the '{'.
2336 pub(super) fn parse_struct_expr(
2337 &mut self,
2338 qself: Option<ast::QSelf>,
2339 pth: ast::Path,
2340 attrs: AttrVec,
2341 recover: bool,
2342 ) -> PResult<'a, P<Expr>> {
2343 let mut fields = Vec::new();
2344 let mut base = ast::StructRest::None;
2345 let mut recover_async = false;
2346
2347 let mut async_block_err = |e: &mut DiagnosticBuilder<'_>, span: Span| {
2348 recover_async = true;
2349 e.span_label(span, "`async` blocks are only allowed in Rust 2018 or later");
2350 e.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
2351 e.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
2352 };
2353
2354 while self.token != token::CloseDelim(token::Brace) {
2355 if self.eat(&token::DotDot) {
2356 let exp_span = self.prev_token.span;
2357 // We permit `.. }` on the left-hand side of a destructuring assignment.
2358 if self.check(&token::CloseDelim(token::Brace)) {
2359 self.sess.gated_spans.gate(sym::destructuring_assignment, self.prev_token.span);
2360 base = ast::StructRest::Rest(self.prev_token.span.shrink_to_hi());
2361 break;
2362 }
2363 match self.parse_expr() {
2364 Ok(e) => base = ast::StructRest::Base(e),
2365 Err(mut e) if recover => {
2366 e.emit();
2367 self.recover_stmt();
2368 }
2369 Err(e) => return Err(e),
2370 }
2371 self.recover_struct_comma_after_dotdot(exp_span);
2372 break;
2373 }
2374
2375 let recovery_field = self.find_struct_error_after_field_looking_code();
2376 let parsed_field = match self.parse_expr_field() {
2377 Ok(f) => Some(f),
2378 Err(mut e) => {
2379 if pth == kw::Async {
2380 async_block_err(&mut e, pth.span);
2381 } else {
2382 e.span_label(pth.span, "while parsing this struct");
2383 }
2384 e.emit();
2385
2386 // If the next token is a comma, then try to parse
2387 // what comes next as additional fields, rather than
2388 // bailing out until next `}`.
2389 if self.token != token::Comma {
2390 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2391 if self.token != token::Comma {
2392 break;
2393 }
2394 }
2395 None
2396 }
2397 };
2398
2399 match self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]) {
2400 Ok(_) => {
2401 if let Some(f) = parsed_field.or(recovery_field) {
2402 // Only include the field if there's no parse error for the field name.
2403 fields.push(f);
2404 }
2405 }
2406 Err(mut e) => {
2407 if pth == kw::Async {
2408 async_block_err(&mut e, pth.span);
2409 } else {
2410 e.span_label(pth.span, "while parsing this struct");
2411 if let Some(f) = recovery_field {
2412 fields.push(f);
2413 e.span_suggestion(
2414 self.prev_token.span.shrink_to_hi(),
2415 "try adding a comma",
2416 ",".into(),
2417 Applicability::MachineApplicable,
2418 );
2419 }
2420 }
2421 if !recover {
2422 return Err(e);
2423 }
2424 e.emit();
2425 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2426 self.eat(&token::Comma);
2427 }
2428 }
2429 }
2430
2431 let span = pth.span.to(self.token.span);
2432 self.expect(&token::CloseDelim(token::Brace))?;
2433 let expr = if recover_async {
2434 ExprKind::Err
2435 } else {
2436 ExprKind::Struct(P(ast::StructExpr { qself, path: pth, fields, rest: base }))
2437 };
2438 Ok(self.mk_expr(span, expr, attrs))
2439 }
2440
2441 /// Use in case of error after field-looking code: `S { foo: () with a }`.
2442 fn find_struct_error_after_field_looking_code(&self) -> Option<ExprField> {
2443 match self.token.ident() {
2444 Some((ident, is_raw))
2445 if (is_raw || !ident.is_reserved())
2446 && self.look_ahead(1, |t| *t == token::Colon) =>
2447 {
2448 Some(ast::ExprField {
2449 ident,
2450 span: self.token.span,
2451 expr: self.mk_expr_err(self.token.span),
2452 is_shorthand: false,
2453 attrs: AttrVec::new(),
2454 id: DUMMY_NODE_ID,
2455 is_placeholder: false,
2456 })
2457 }
2458 _ => None,
2459 }
2460 }
2461
2462 fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
2463 if self.token != token::Comma {
2464 return;
2465 }
2466 self.struct_span_err(
2467 span.to(self.prev_token.span),
2468 "cannot use a comma after the base struct",
2469 )
2470 .span_suggestion_short(
2471 self.token.span,
2472 "remove this comma",
2473 String::new(),
2474 Applicability::MachineApplicable,
2475 )
2476 .note("the base struct must always be the last field")
2477 .emit();
2478 self.recover_stmt();
2479 }
2480
2481 /// Parses `ident (COLON expr)?`.
2482 fn parse_expr_field(&mut self) -> PResult<'a, ExprField> {
2483 let attrs = self.parse_outer_attributes()?;
2484 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2485 let lo = this.token.span;
2486
2487 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2488 let is_shorthand = !this.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
2489 let (ident, expr) = if is_shorthand {
2490 // Mimic `x: x` for the `x` field shorthand.
2491 let ident = this.parse_ident_common(false)?;
2492 let path = ast::Path::from_ident(ident);
2493 (ident, this.mk_expr(ident.span, ExprKind::Path(None, path), AttrVec::new()))
2494 } else {
2495 let ident = this.parse_field_name()?;
2496 this.error_on_eq_field_init(ident);
2497 this.bump(); // `:`
2498 (ident, this.parse_expr()?)
2499 };
2500
2501 Ok((
2502 ast::ExprField {
2503 ident,
2504 span: lo.to(expr.span),
2505 expr,
2506 is_shorthand,
2507 attrs: attrs.into(),
2508 id: DUMMY_NODE_ID,
2509 is_placeholder: false,
2510 },
2511 TrailingToken::MaybeComma,
2512 ))
2513 })
2514 }
2515
2516 /// Check for `=`. This means the source incorrectly attempts to
2517 /// initialize a field with an eq rather than a colon.
2518 fn error_on_eq_field_init(&self, field_name: Ident) {
2519 if self.token != token::Eq {
2520 return;
2521 }
2522
2523 self.struct_span_err(self.token.span, "expected `:`, found `=`")
2524 .span_suggestion(
2525 field_name.span.shrink_to_hi().to(self.token.span),
2526 "replace equals symbol with a colon",
2527 ":".to_string(),
2528 Applicability::MachineApplicable,
2529 )
2530 .emit();
2531 }
2532
2533 fn err_dotdotdot_syntax(&self, span: Span) {
2534 self.struct_span_err(span, "unexpected token: `...`")
2535 .span_suggestion(
2536 span,
2537 "use `..` for an exclusive range",
2538 "..".to_owned(),
2539 Applicability::MaybeIncorrect,
2540 )
2541 .span_suggestion(
2542 span,
2543 "or `..=` for an inclusive range",
2544 "..=".to_owned(),
2545 Applicability::MaybeIncorrect,
2546 )
2547 .emit();
2548 }
2549
2550 fn err_larrow_operator(&self, span: Span) {
2551 self.struct_span_err(span, "unexpected token: `<-`")
2552 .span_suggestion(
2553 span,
2554 "if you meant to write a comparison against a negative value, add a \
2555 space in between `<` and `-`",
2556 "< -".to_string(),
2557 Applicability::MaybeIncorrect,
2558 )
2559 .emit();
2560 }
2561
2562 fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2563 ExprKind::AssignOp(binop, lhs, rhs)
2564 }
2565
2566 fn mk_range(
2567 &mut self,
2568 start: Option<P<Expr>>,
2569 end: Option<P<Expr>>,
2570 limits: RangeLimits,
2571 ) -> ExprKind {
2572 if end.is_none() && limits == RangeLimits::Closed {
2573 self.inclusive_range_with_incorrect_end(self.prev_token.span);
2574 ExprKind::Err
2575 } else {
2576 ExprKind::Range(start, end, limits)
2577 }
2578 }
2579
2580 fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
2581 ExprKind::Unary(unop, expr)
2582 }
2583
2584 fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2585 ExprKind::Binary(binop, lhs, rhs)
2586 }
2587
2588 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
2589 ExprKind::Index(expr, idx)
2590 }
2591
2592 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
2593 ExprKind::Call(f, args)
2594 }
2595
2596 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> P<Expr> {
2597 let span = lo.to(self.prev_token.span);
2598 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), AttrVec::new());
2599 self.recover_from_await_method_call();
2600 await_expr
2601 }
2602
2603 crate fn mk_expr(&self, span: Span, kind: ExprKind, attrs: AttrVec) -> P<Expr> {
2604 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None })
2605 }
2606
2607 pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
2608 self.mk_expr(span, ExprKind::Err, AttrVec::new())
2609 }
2610
2611 /// Create expression span ensuring the span of the parent node
2612 /// is larger than the span of lhs and rhs, including the attributes.
2613 fn mk_expr_sp(&self, lhs: &P<Expr>, lhs_span: Span, rhs_span: Span) -> Span {
2614 lhs.attrs
2615 .iter()
2616 .find(|a| a.style == AttrStyle::Outer)
2617 .map_or(lhs_span, |a| a.span)
2618 .to(rhs_span)
2619 }
2620
2621 fn collect_tokens_for_expr(
2622 &mut self,
2623 attrs: AttrWrapper,
2624 f: impl FnOnce(&mut Self, Vec<ast::Attribute>) -> PResult<'a, P<Expr>>,
2625 ) -> PResult<'a, P<Expr>> {
2626 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2627 let res = f(this, attrs)?;
2628 let trailing = if this.restrictions.contains(Restrictions::STMT_EXPR)
2629 && this.token.kind == token::Semi
2630 {
2631 TrailingToken::Semi
2632 } else {
2633 // FIXME - pass this through from the place where we know
2634 // we need a comma, rather than assuming that `#[attr] expr,`
2635 // always captures a trailing comma
2636 TrailingToken::MaybeComma
2637 };
2638 Ok((res, trailing))
2639 })
2640 }
2641 }