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