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