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