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