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