]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser/expr.rs
Rollup merge of #64229 - kawa-yoiko:unreachable-call-lint, r=estebank
[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         })
1198     }
1199
1200     /// Parses an `if` expression (`if` token already eaten).
1201     fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1202         let lo = self.prev_span;
1203         let cond = self.parse_cond_expr()?;
1204
1205         // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1206         // verify that the last statement is either an implicit return (no `;`) or an explicit
1207         // return. This won't catch blocks with an explicit `return`, but that would be caught by
1208         // the dead code lint.
1209         if self.eat_keyword(kw::Else) || !cond.returns() {
1210             let sp = self.sess.source_map().next_point(lo);
1211             let mut err = self.diagnostic()
1212                 .struct_span_err(sp, "missing condition for `if` expression");
1213             err.span_label(sp, "expected if condition here");
1214             return Err(err)
1215         }
1216         let not_block = self.token != token::OpenDelim(token::Brace);
1217         let thn = self.parse_block().map_err(|mut err| {
1218             if not_block {
1219                 err.span_label(lo, "this `if` statement has a condition, but no block");
1220             }
1221             err
1222         })?;
1223         let mut els: Option<P<Expr>> = None;
1224         let mut hi = thn.span;
1225         if self.eat_keyword(kw::Else) {
1226             let elexpr = self.parse_else_expr()?;
1227             hi = elexpr.span;
1228             els = Some(elexpr);
1229         }
1230         Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
1231     }
1232
1233     /// Parses the condition of a `if` or `while` expression.
1234     fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
1235         let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1236
1237         if let ExprKind::Let(..) = cond.node {
1238             // Remove the last feature gating of a `let` expression since it's stable.
1239             let last = self.sess.gated_spans.let_chains.borrow_mut().pop();
1240             debug_assert_eq!(cond.span, last.unwrap());
1241         }
1242
1243         Ok(cond)
1244     }
1245
1246     /// Parses a `let $pat = $expr` pseudo-expression.
1247     /// The `let` token has already been eaten.
1248     fn parse_let_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1249         let lo = self.prev_span;
1250         let pat = self.parse_top_pat(GateOr::No)?;
1251         self.expect(&token::Eq)?;
1252         let expr = self.with_res(
1253             Restrictions::NO_STRUCT_LITERAL,
1254             |this| this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
1255         )?;
1256         let span = lo.to(expr.span);
1257         self.sess.gated_spans.let_chains.borrow_mut().push(span);
1258         Ok(self.mk_expr(span, ExprKind::Let(pat, expr), attrs))
1259     }
1260
1261     /// Parses an `else { ... }` expression (`else` token already eaten).
1262     fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
1263         if self.eat_keyword(kw::If) {
1264             return self.parse_if_expr(ThinVec::new());
1265         } else {
1266             let blk = self.parse_block()?;
1267             return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
1268         }
1269     }
1270
1271     /// Parses a `for ... in` expression (`for` token already eaten).
1272     fn parse_for_expr(
1273         &mut self,
1274         opt_label: Option<Label>,
1275         span_lo: Span,
1276         mut attrs: ThinVec<Attribute>
1277     ) -> PResult<'a, P<Expr>> {
1278         // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
1279
1280         // Record whether we are about to parse `for (`.
1281         // This is used below for recovery in case of `for ( $stuff ) $block`
1282         // in which case we will suggest `for $stuff $block`.
1283         let begin_paren = match self.token.kind {
1284             token::OpenDelim(token::Paren) => Some(self.token.span),
1285             _ => None,
1286         };
1287
1288         let pat = self.parse_top_pat(GateOr::Yes)?;
1289         if !self.eat_keyword(kw::In) {
1290             let in_span = self.prev_span.between(self.token.span);
1291             self.struct_span_err(in_span, "missing `in` in `for` loop")
1292                 .span_suggestion_short(
1293                     in_span,
1294                     "try adding `in` here", " in ".into(),
1295                     // has been misleading, at least in the past (closed Issue #48492)
1296                     Applicability::MaybeIncorrect
1297                 )
1298                 .emit();
1299         }
1300         let in_span = self.prev_span;
1301         self.check_for_for_in_in_typo(in_span);
1302         let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1303
1304         let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
1305
1306         let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
1307         attrs.extend(iattrs);
1308
1309         let hi = self.prev_span;
1310         Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
1311     }
1312
1313     /// Parses a `while` or `while let` expression (`while` token already eaten).
1314     fn parse_while_expr(
1315         &mut self,
1316         opt_label: Option<Label>,
1317         span_lo: Span,
1318         mut attrs: ThinVec<Attribute>
1319     ) -> PResult<'a, P<Expr>> {
1320         let cond = self.parse_cond_expr()?;
1321         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1322         attrs.extend(iattrs);
1323         let span = span_lo.to(body.span);
1324         Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs))
1325     }
1326
1327     /// Parses `loop { ... }` (`loop` token already eaten).
1328     fn parse_loop_expr(
1329         &mut self,
1330         opt_label: Option<Label>,
1331         span_lo: Span,
1332         mut attrs: ThinVec<Attribute>
1333     ) -> PResult<'a, P<Expr>> {
1334         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1335         attrs.extend(iattrs);
1336         let span = span_lo.to(body.span);
1337         Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
1338     }
1339
1340     fn eat_label(&mut self) -> Option<Label> {
1341         if let Some(ident) = self.token.lifetime() {
1342             let span = self.token.span;
1343             self.bump();
1344             Some(Label { ident: Ident::new(ident.name, span) })
1345         } else {
1346             None
1347         }
1348     }
1349
1350     /// Parses a `match ... { ... }` expression (`match` token already eaten).
1351     fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1352         let match_span = self.prev_span;
1353         let lo = self.prev_span;
1354         let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1355         if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
1356             if self.token == token::Semi {
1357                 e.span_suggestion_short(
1358                     match_span,
1359                     "try removing this `match`",
1360                     String::new(),
1361                     Applicability::MaybeIncorrect // speculative
1362                 );
1363             }
1364             return Err(e)
1365         }
1366         attrs.extend(self.parse_inner_attributes()?);
1367
1368         let mut arms: Vec<Arm> = Vec::new();
1369         while self.token != token::CloseDelim(token::Brace) {
1370             match self.parse_arm() {
1371                 Ok(arm) => arms.push(arm),
1372                 Err(mut e) => {
1373                     // Recover by skipping to the end of the block.
1374                     e.emit();
1375                     self.recover_stmt();
1376                     let span = lo.to(self.token.span);
1377                     if self.token == token::CloseDelim(token::Brace) {
1378                         self.bump();
1379                     }
1380                     return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
1381                 }
1382             }
1383         }
1384         let hi = self.token.span;
1385         self.bump();
1386         return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
1387     }
1388
1389     crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
1390         let attrs = self.parse_outer_attributes()?;
1391         let lo = self.token.span;
1392         let pat = self.parse_top_pat(GateOr::No)?;
1393         let guard = if self.eat_keyword(kw::If) {
1394             Some(self.parse_expr()?)
1395         } else {
1396             None
1397         };
1398         let arrow_span = self.token.span;
1399         self.expect(&token::FatArrow)?;
1400         let arm_start_span = self.token.span;
1401
1402         let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
1403             .map_err(|mut err| {
1404                 err.span_label(arrow_span, "while parsing the `match` arm starting here");
1405                 err
1406             })?;
1407
1408         let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
1409             && self.token != token::CloseDelim(token::Brace);
1410
1411         let hi = self.token.span;
1412
1413         if require_comma {
1414             let cm = self.sess.source_map();
1415             self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
1416                 .map_err(|mut err| {
1417                     match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
1418                         (Ok(ref expr_lines), Ok(ref arm_start_lines))
1419                         if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
1420                             && expr_lines.lines.len() == 2
1421                             && self.token == token::FatArrow => {
1422                             // We check whether there's any trailing code in the parse span,
1423                             // if there isn't, we very likely have the following:
1424                             //
1425                             // X |     &Y => "y"
1426                             //   |        --    - missing comma
1427                             //   |        |
1428                             //   |        arrow_span
1429                             // X |     &X => "x"
1430                             //   |      - ^^ self.token.span
1431                             //   |      |
1432                             //   |      parsed until here as `"y" & X`
1433                             err.span_suggestion_short(
1434                                 cm.next_point(arm_start_span),
1435                                 "missing a comma here to end this `match` arm",
1436                                 ",".to_owned(),
1437                                 Applicability::MachineApplicable
1438                             );
1439                         }
1440                         _ => {
1441                             err.span_label(arrow_span,
1442                                            "while parsing the `match` arm starting here");
1443                         }
1444                     }
1445                     err
1446                 })?;
1447         } else {
1448             self.eat(&token::Comma);
1449         }
1450
1451         Ok(ast::Arm {
1452             attrs,
1453             pat,
1454             guard,
1455             body: expr,
1456             span: lo.to(hi),
1457             id: DUMMY_NODE_ID,
1458         })
1459     }
1460
1461     /// Parses a `try {...}` expression (`try` token already eaten).
1462     fn parse_try_block(
1463         &mut self,
1464         span_lo: Span,
1465         mut attrs: ThinVec<Attribute>
1466     ) -> PResult<'a, P<Expr>> {
1467         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1468         attrs.extend(iattrs);
1469         if self.eat_keyword(kw::Catch) {
1470             let mut error = self.struct_span_err(self.prev_span,
1471                                                  "keyword `catch` cannot follow a `try` block");
1472             error.help("try using `match` on the result of the `try` block instead");
1473             error.emit();
1474             Err(error)
1475         } else {
1476             Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
1477         }
1478     }
1479
1480     fn is_do_catch_block(&self) -> bool {
1481         self.token.is_keyword(kw::Do) &&
1482         self.is_keyword_ahead(1, &[kw::Catch]) &&
1483         self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
1484         !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1485     }
1486
1487     fn is_try_block(&self) -> bool {
1488         self.token.is_keyword(kw::Try) &&
1489         self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
1490         self.token.span.rust_2018() &&
1491         // Prevent `while try {} {}`, `if try {} {} else {}`, etc.
1492         !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1493     }
1494
1495     /// Parses an `async move? {...}` expression.
1496     pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1497         let span_lo = self.token.span;
1498         self.expect_keyword(kw::Async)?;
1499         let capture_clause = self.parse_capture_clause();
1500         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1501         attrs.extend(iattrs);
1502         Ok(self.mk_expr(
1503             span_lo.to(body.span),
1504             ExprKind::Async(capture_clause, DUMMY_NODE_ID, body), attrs))
1505     }
1506
1507     fn is_async_block(&self) -> bool {
1508         self.token.is_keyword(kw::Async) &&
1509         (
1510             ( // `async move {`
1511                 self.is_keyword_ahead(1, &[kw::Move]) &&
1512                 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
1513             ) || ( // `async {`
1514                 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
1515             )
1516         )
1517     }
1518
1519     fn maybe_parse_struct_expr(
1520         &mut self,
1521         lo: Span,
1522         path: &ast::Path,
1523         attrs: &ThinVec<Attribute>,
1524     ) -> Option<PResult<'a, P<Expr>>> {
1525         let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
1526         let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
1527             // `{ ident, ` cannot start a block.
1528             self.look_ahead(2, |t| t == &token::Comma) ||
1529             self.look_ahead(2, |t| t == &token::Colon) && (
1530                 // `{ ident: token, ` cannot start a block.
1531                 self.look_ahead(4, |t| t == &token::Comma) ||
1532                 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
1533                 self.look_ahead(3, |t| !t.can_begin_type())
1534             )
1535         );
1536
1537         if struct_allowed || certainly_not_a_block() {
1538             // This is a struct literal, but we don't can't accept them here.
1539             let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
1540             if let (Ok(expr), false) = (&expr, struct_allowed) {
1541                 self.struct_span_err(
1542                     expr.span,
1543                     "struct literals are not allowed here",
1544                 )
1545                 .multipart_suggestion(
1546                     "surround the struct literal with parentheses",
1547                     vec![
1548                         (lo.shrink_to_lo(), "(".to_string()),
1549                         (expr.span.shrink_to_hi(), ")".to_string()),
1550                     ],
1551                     Applicability::MachineApplicable,
1552                 )
1553                 .emit();
1554             }
1555             return Some(expr);
1556         }
1557         None
1558     }
1559
1560     pub(super) fn parse_struct_expr(
1561         &mut self,
1562         lo: Span,
1563         pth: ast::Path,
1564         mut attrs: ThinVec<Attribute>
1565     ) -> PResult<'a, P<Expr>> {
1566         let struct_sp = lo.to(self.prev_span);
1567         self.bump();
1568         let mut fields = Vec::new();
1569         let mut base = None;
1570
1571         attrs.extend(self.parse_inner_attributes()?);
1572
1573         while self.token != token::CloseDelim(token::Brace) {
1574             if self.eat(&token::DotDot) {
1575                 let exp_span = self.prev_span;
1576                 match self.parse_expr() {
1577                     Ok(e) => {
1578                         base = Some(e);
1579                     }
1580                     Err(mut e) => {
1581                         e.emit();
1582                         self.recover_stmt();
1583                     }
1584                 }
1585                 if self.token == token::Comma {
1586                     self.struct_span_err(
1587                         exp_span.to(self.prev_span),
1588                         "cannot use a comma after the base struct",
1589                     )
1590                     .span_suggestion_short(
1591                         self.token.span,
1592                         "remove this comma",
1593                         String::new(),
1594                         Applicability::MachineApplicable
1595                     )
1596                     .note("the base struct must always be the last field")
1597                     .emit();
1598                     self.recover_stmt();
1599                 }
1600                 break;
1601             }
1602
1603             let mut recovery_field = None;
1604             if let token::Ident(name, _) = self.token.kind {
1605                 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
1606                     // Use in case of error after field-looking code: `S { foo: () with a }`.
1607                     recovery_field = Some(ast::Field {
1608                         ident: Ident::new(name, self.token.span),
1609                         span: self.token.span,
1610                         expr: self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()),
1611                         is_shorthand: false,
1612                         attrs: ThinVec::new(),
1613                         id: DUMMY_NODE_ID,
1614                     });
1615                 }
1616             }
1617             let mut parsed_field = None;
1618             match self.parse_field() {
1619                 Ok(f) => parsed_field = Some(f),
1620                 Err(mut e) => {
1621                     e.span_label(struct_sp, "while parsing this struct");
1622                     e.emit();
1623
1624                     // If the next token is a comma, then try to parse
1625                     // what comes next as additional fields, rather than
1626                     // bailing out until next `}`.
1627                     if self.token != token::Comma {
1628                         self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
1629                         if self.token != token::Comma {
1630                             break;
1631                         }
1632                     }
1633                 }
1634             }
1635
1636             match self.expect_one_of(&[token::Comma],
1637                                      &[token::CloseDelim(token::Brace)]) {
1638                 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
1639                     // Only include the field if there's no parse error for the field name.
1640                     fields.push(f);
1641                 }
1642                 Err(mut e) => {
1643                     if let Some(f) = recovery_field {
1644                         fields.push(f);
1645                     }
1646                     e.span_label(struct_sp, "while parsing this struct");
1647                     e.emit();
1648                     self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
1649                     self.eat(&token::Comma);
1650                 }
1651             }
1652         }
1653
1654         let span = lo.to(self.token.span);
1655         self.expect(&token::CloseDelim(token::Brace))?;
1656         return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
1657     }
1658
1659     /// Parses `ident (COLON expr)?`.
1660     fn parse_field(&mut self) -> PResult<'a, Field> {
1661         let attrs = self.parse_outer_attributes()?;
1662         let lo = self.token.span;
1663
1664         // Check if a colon exists one ahead. This means we're parsing a fieldname.
1665         let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
1666             t == &token::Colon || t == &token::Eq
1667         }) {
1668             let fieldname = self.parse_field_name()?;
1669
1670             // Check for an equals token. This means the source incorrectly attempts to
1671             // initialize a field with an eq rather than a colon.
1672             if self.token == token::Eq {
1673                 self.diagnostic()
1674                     .struct_span_err(self.token.span, "expected `:`, found `=`")
1675                     .span_suggestion(
1676                         fieldname.span.shrink_to_hi().to(self.token.span),
1677                         "replace equals symbol with a colon",
1678                         ":".to_string(),
1679                         Applicability::MachineApplicable,
1680                     )
1681                     .emit();
1682             }
1683             self.bump(); // `:`
1684             (fieldname, self.parse_expr()?, false)
1685         } else {
1686             let fieldname = self.parse_ident_common(false)?;
1687
1688             // Mimic `x: x` for the `x` field shorthand.
1689             let path = ast::Path::from_ident(fieldname);
1690             let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
1691             (fieldname, expr, true)
1692         };
1693         Ok(ast::Field {
1694             ident: fieldname,
1695             span: lo.to(expr.span),
1696             expr,
1697             is_shorthand,
1698             attrs: attrs.into(),
1699             id: DUMMY_NODE_ID,
1700         })
1701     }
1702
1703     fn err_dotdotdot_syntax(&self, span: Span) {
1704         self.struct_span_err(span, "unexpected token: `...`")
1705             .span_suggestion(
1706                 span,
1707                 "use `..` for an exclusive range", "..".to_owned(),
1708                 Applicability::MaybeIncorrect
1709             )
1710             .span_suggestion(
1711                 span,
1712                 "or `..=` for an inclusive range", "..=".to_owned(),
1713                 Applicability::MaybeIncorrect
1714             )
1715             .emit();
1716     }
1717
1718     fn err_larrow_operator(&self, span: Span) {
1719         self.struct_span_err(
1720             span,
1721             "unexpected token: `<-`"
1722         ).span_suggestion(
1723             span,
1724             "if you meant to write a comparison against a negative value, add a \
1725              space in between `<` and `-`",
1726             "< -".to_string(),
1727             Applicability::MaybeIncorrect
1728         ).emit();
1729     }
1730
1731     fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
1732         ExprKind::AssignOp(binop, lhs, rhs)
1733     }
1734
1735     fn mk_range(
1736         &self,
1737         start: Option<P<Expr>>,
1738         end: Option<P<Expr>>,
1739         limits: RangeLimits
1740     ) -> PResult<'a, ExprKind> {
1741         if end.is_none() && limits == RangeLimits::Closed {
1742             Err(self.span_fatal_err(self.token.span, Error::InclusiveRangeWithNoEnd))
1743         } else {
1744             Ok(ExprKind::Range(start, end, limits))
1745         }
1746     }
1747
1748     fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
1749         ExprKind::Unary(unop, expr)
1750     }
1751
1752     fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
1753         ExprKind::Binary(binop, lhs, rhs)
1754     }
1755
1756     fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
1757         ExprKind::Index(expr, idx)
1758     }
1759
1760     fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
1761         ExprKind::Call(f, args)
1762     }
1763
1764     fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
1765         let span = lo.to(self.prev_span);
1766         let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), ThinVec::new());
1767         self.recover_from_await_method_call();
1768         Ok(await_expr)
1769     }
1770
1771     crate fn mk_expr(&self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1772         P(Expr { node, span, attrs, id: DUMMY_NODE_ID })
1773     }
1774 }