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