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