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