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