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