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