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