]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser/expr.rs
Rollup merge of #64157 - gilescope:opaque-type-location, r=cramertj,Centril
[rust.git] / src / libsyntax / parse / parser / expr.rs
1 use super::{Parser, PResult, Restrictions, PrevTokenKind, TokenType, PathStyle};
2 use super::{BlockMode, SemiColonMode};
3 use super::{SeqSep, TokenExpectType};
4 use super::pat::{GateOr, PARAM_EXPECTED};
5
6 use crate::maybe_recover_from_interpolated_ty_qpath;
7 use crate::ptr::P;
8 use crate::ast::{self, Attribute, AttrStyle, Ident, CaptureBy, BlockCheckMode};
9 use crate::ast::{Expr, ExprKind, RangeLimits, Label, Movability, IsAsync, Arm};
10 use crate::ast::{Ty, TyKind, FunctionRetTy, Param, FnDecl};
11 use crate::ast::{BinOpKind, BinOp, UnOp};
12 use crate::ast::{Mac, AnonConst, Field};
13
14 use crate::parse::classify;
15 use crate::parse::token::{self, Token};
16 use crate::parse::diagnostics::{Error};
17 use crate::print::pprust;
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 std::mem;
23 use errors::Applicability;
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     /// Parse 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     /// Parse 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: ast::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
745     /// At the bottom (top?) of the precedence hierarchy,
746     /// Parses things like parenthesized exprs, macros, `return`, etc.
747     ///
748     /// N.B., this does not parse outer attributes, and is private because it only works
749     /// correctly if called from `parse_dot_or_call_expr()`.
750     fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
751         maybe_recover_from_interpolated_ty_qpath!(self, true);
752         maybe_whole_expr!(self);
753
754         // Outer attributes are already parsed and will be
755         // added to the return value after the fact.
756         //
757         // Therefore, prevent sub-parser from parsing
758         // attributes by giving them a empty "already parsed" list.
759         let mut attrs = ThinVec::new();
760
761         let lo = self.token.span;
762         let mut hi = self.token.span;
763
764         let ex: ExprKind;
765
766         macro_rules! parse_lit {
767             () => {
768                 match self.parse_lit() {
769                     Ok(literal) => {
770                         hi = self.prev_span;
771                         ex = ExprKind::Lit(literal);
772                     }
773                     Err(mut err) => {
774                         self.cancel(&mut err);
775                         return Err(self.expected_expression_found());
776                     }
777                 }
778             }
779         }
780
781         // Note: when adding new syntax here, don't forget to adjust TokenKind::can_begin_expr().
782         match self.token.kind {
783             // This match arm is a special-case of the `_` match arm below and
784             // could be removed without changing functionality, but it's faster
785             // to have it here, especially for programs with large constants.
786             token::Literal(_) => {
787                 parse_lit!()
788             }
789             token::OpenDelim(token::Paren) => {
790                 self.bump();
791
792                 attrs.extend(self.parse_inner_attributes()?);
793
794                 // (e) is parenthesized e
795                 // (e,) is a tuple with only one field, e
796                 let mut es = vec![];
797                 let mut trailing_comma = false;
798                 let mut recovered = false;
799                 while self.token != token::CloseDelim(token::Paren) {
800                     es.push(match self.parse_expr() {
801                         Ok(es) => es,
802                         Err(mut err) => {
803                             // recover from parse error in tuple list
804                             match self.token.kind {
805                                 token::Ident(name, false)
806                                 if name == kw::Underscore && self.look_ahead(1, |t| {
807                                     t == &token::Comma
808                                 }) => {
809                                     // Special-case handling of `Foo<(_, _, _)>`
810                                     err.emit();
811                                     let sp = self.token.span;
812                                     self.bump();
813                                     self.mk_expr(sp, ExprKind::Err, ThinVec::new())
814                                 }
815                                 _ => return Ok(
816                                     self.recover_seq_parse_error(token::Paren, lo, Err(err)),
817                                 ),
818                             }
819                         }
820                     });
821                     recovered = self.expect_one_of(
822                         &[],
823                         &[token::Comma, token::CloseDelim(token::Paren)],
824                     )?;
825                     if self.eat(&token::Comma) {
826                         trailing_comma = true;
827                     } else {
828                         trailing_comma = false;
829                         break;
830                     }
831                 }
832                 if !recovered {
833                     self.bump();
834                 }
835
836                 hi = self.prev_span;
837                 ex = if es.len() == 1 && !trailing_comma {
838                     ExprKind::Paren(es.into_iter().nth(0).unwrap())
839                 } else {
840                     ExprKind::Tup(es)
841                 };
842             }
843             token::OpenDelim(token::Brace) => {
844                 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
845             }
846             token::BinOp(token::Or) | token::OrOr => {
847                 return self.parse_lambda_expr(attrs);
848             }
849             token::OpenDelim(token::Bracket) => {
850                 self.bump();
851
852                 attrs.extend(self.parse_inner_attributes()?);
853
854                 if self.eat(&token::CloseDelim(token::Bracket)) {
855                     // Empty vector.
856                     ex = ExprKind::Array(Vec::new());
857                 } else {
858                     // Nonempty vector.
859                     let first_expr = self.parse_expr()?;
860                     if self.eat(&token::Semi) {
861                         // Repeating array syntax: [ 0; 512 ]
862                         let count = AnonConst {
863                             id: ast::DUMMY_NODE_ID,
864                             value: self.parse_expr()?,
865                         };
866                         self.expect(&token::CloseDelim(token::Bracket))?;
867                         ex = ExprKind::Repeat(first_expr, count);
868                     } else if self.eat(&token::Comma) {
869                         // Vector with two or more elements.
870                         let remaining_exprs = self.parse_seq_to_end(
871                             &token::CloseDelim(token::Bracket),
872                             SeqSep::trailing_allowed(token::Comma),
873                             |p| Ok(p.parse_expr()?)
874                         )?;
875                         let mut exprs = vec![first_expr];
876                         exprs.extend(remaining_exprs);
877                         ex = ExprKind::Array(exprs);
878                     } else {
879                         // Vector with one element.
880                         self.expect(&token::CloseDelim(token::Bracket))?;
881                         ex = ExprKind::Array(vec![first_expr]);
882                     }
883                 }
884                 hi = self.prev_span;
885             }
886             _ => {
887                 if self.eat_lt() {
888                     let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
889                     hi = path.span;
890                     return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
891                 }
892                 if self.token.is_path_start() {
893                     let path = self.parse_path(PathStyle::Expr)?;
894
895                     // `!`, as an operator, is prefix, so we know this isn't that
896                     if self.eat(&token::Not) {
897                         // MACRO INVOCATION expression
898                         let (delim, tts) = self.expect_delimited_token_tree()?;
899                         hi = self.prev_span;
900                         ex = ExprKind::Mac(Mac {
901                             path,
902                             tts,
903                             delim,
904                             span: lo.to(hi),
905                             prior_type_ascription: self.last_type_ascription,
906                         });
907                     } else if self.check(&token::OpenDelim(token::Brace)) {
908                         if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
909                             return expr;
910                         } else {
911                             hi = path.span;
912                             ex = ExprKind::Path(None, path);
913                         }
914                     } else {
915                         hi = path.span;
916                         ex = ExprKind::Path(None, path);
917                     }
918
919                     let expr = self.mk_expr(lo.to(hi), ex, attrs);
920                     return self.maybe_recover_from_bad_qpath(expr, true);
921                 }
922                 if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
923                     return self.parse_lambda_expr(attrs);
924                 }
925                 if self.eat_keyword(kw::If) {
926                     return self.parse_if_expr(attrs);
927                 }
928                 if self.eat_keyword(kw::For) {
929                     let lo = self.prev_span;
930                     return self.parse_for_expr(None, lo, attrs);
931                 }
932                 if self.eat_keyword(kw::While) {
933                     let lo = self.prev_span;
934                     return self.parse_while_expr(None, lo, attrs);
935                 }
936                 if let Some(label) = self.eat_label() {
937                     let lo = label.ident.span;
938                     self.expect(&token::Colon)?;
939                     if self.eat_keyword(kw::While) {
940                         return self.parse_while_expr(Some(label), lo, attrs)
941                     }
942                     if self.eat_keyword(kw::For) {
943                         return self.parse_for_expr(Some(label), lo, attrs)
944                     }
945                     if self.eat_keyword(kw::Loop) {
946                         return self.parse_loop_expr(Some(label), lo, attrs)
947                     }
948                     if self.token == token::OpenDelim(token::Brace) {
949                         return self.parse_block_expr(Some(label),
950                                                      lo,
951                                                      BlockCheckMode::Default,
952                                                      attrs);
953                     }
954                     let msg = "expected `while`, `for`, `loop` or `{` after a label";
955                     let mut err = self.fatal(msg);
956                     err.span_label(self.token.span, msg);
957                     return Err(err);
958                 }
959                 if self.eat_keyword(kw::Loop) {
960                     let lo = self.prev_span;
961                     return self.parse_loop_expr(None, lo, attrs);
962                 }
963                 if self.eat_keyword(kw::Continue) {
964                     let label = self.eat_label();
965                     let ex = ExprKind::Continue(label);
966                     let hi = self.prev_span;
967                     return Ok(self.mk_expr(lo.to(hi), ex, attrs));
968                 }
969                 if self.eat_keyword(kw::Match) {
970                     let match_sp = self.prev_span;
971                     return self.parse_match_expr(attrs).map_err(|mut err| {
972                         err.span_label(match_sp, "while parsing this match expression");
973                         err
974                     });
975                 }
976                 if self.eat_keyword(kw::Unsafe) {
977                     return self.parse_block_expr(
978                         None,
979                         lo,
980                         BlockCheckMode::Unsafe(ast::UserProvided),
981                         attrs);
982                 }
983                 if self.is_do_catch_block() {
984                     let mut db = self.fatal("found removed `do catch` syntax");
985                     db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
986                     return Err(db);
987                 }
988                 if self.is_try_block() {
989                     let lo = self.token.span;
990                     assert!(self.eat_keyword(kw::Try));
991                     return self.parse_try_block(lo, attrs);
992                 }
993
994                 // Span::rust_2018() is somewhat expensive; don't get it repeatedly.
995                 let is_span_rust_2018 = self.token.span.rust_2018();
996                 if is_span_rust_2018 && self.check_keyword(kw::Async) {
997                     return if self.is_async_block() { // check for `async {` and `async move {`
998                         self.parse_async_block(attrs)
999                     } else {
1000                         self.parse_lambda_expr(attrs)
1001                     };
1002                 }
1003                 if self.eat_keyword(kw::Return) {
1004                     if self.token.can_begin_expr() {
1005                         let e = self.parse_expr()?;
1006                         hi = e.span;
1007                         ex = ExprKind::Ret(Some(e));
1008                     } else {
1009                         ex = ExprKind::Ret(None);
1010                     }
1011                 } else if self.eat_keyword(kw::Break) {
1012                     let label = self.eat_label();
1013                     let e = if self.token.can_begin_expr()
1014                                && !(self.token == token::OpenDelim(token::Brace)
1015                                     && self.restrictions.contains(
1016                                            Restrictions::NO_STRUCT_LITERAL)) {
1017                         Some(self.parse_expr()?)
1018                     } else {
1019                         None
1020                     };
1021                     ex = ExprKind::Break(label, e);
1022                     hi = self.prev_span;
1023                 } else if self.eat_keyword(kw::Yield) {
1024                     if self.token.can_begin_expr() {
1025                         let e = self.parse_expr()?;
1026                         hi = e.span;
1027                         ex = ExprKind::Yield(Some(e));
1028                     } else {
1029                         ex = ExprKind::Yield(None);
1030                     }
1031
1032                     let span = lo.to(hi);
1033                     self.sess.gated_spans.yields.borrow_mut().push(span);
1034                 } else if self.eat_keyword(kw::Let) {
1035                     return self.parse_let_expr(attrs);
1036                 } else if is_span_rust_2018 && self.eat_keyword(kw::Await) {
1037                     let (await_hi, e_kind) = self.parse_incorrect_await_syntax(lo, self.prev_span)?;
1038                     hi = await_hi;
1039                     ex = e_kind;
1040                 } else {
1041                     if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1042                         // Don't complain about bare semicolons after unclosed braces
1043                         // recovery in order to keep the error count down. Fixing the
1044                         // delimiters will possibly also fix the bare semicolon found in
1045                         // expression context. For example, silence the following error:
1046                         // ```
1047                         // error: expected expression, found `;`
1048                         //  --> file.rs:2:13
1049                         //   |
1050                         // 2 |     foo(bar(;
1051                         //   |             ^ expected expression
1052                         // ```
1053                         self.bump();
1054                         return Ok(self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()));
1055                     }
1056                     parse_lit!()
1057                 }
1058             }
1059         }
1060
1061         let expr = self.mk_expr(lo.to(hi), ex, attrs);
1062         self.maybe_recover_from_bad_qpath(expr, true)
1063     }
1064
1065     /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1066     crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1067         maybe_whole_expr!(self);
1068
1069         let minus_lo = self.token.span;
1070         let minus_present = self.eat(&token::BinOp(token::Minus));
1071         let lo = self.token.span;
1072         let literal = self.parse_lit()?;
1073         let hi = self.prev_span;
1074         let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1075
1076         if minus_present {
1077             let minus_hi = self.prev_span;
1078             let unary = self.mk_unary(UnOp::Neg, expr);
1079             Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1080         } else {
1081             Ok(expr)
1082         }
1083     }
1084
1085     /// Parses a block or unsafe block.
1086     crate fn parse_block_expr(
1087         &mut self,
1088         opt_label: Option<Label>,
1089         lo: Span,
1090         blk_mode: BlockCheckMode,
1091         outer_attrs: ThinVec<Attribute>,
1092     ) -> PResult<'a, P<Expr>> {
1093         self.expect(&token::OpenDelim(token::Brace))?;
1094
1095         let mut attrs = outer_attrs;
1096         attrs.extend(self.parse_inner_attributes()?);
1097
1098         let blk = self.parse_block_tail(lo, blk_mode)?;
1099         return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
1100     }
1101
1102     /// Parses `move |args| expr`.
1103     fn parse_lambda_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1104         let lo = self.token.span;
1105
1106         let movability = if self.eat_keyword(kw::Static) {
1107             Movability::Static
1108         } else {
1109             Movability::Movable
1110         };
1111
1112         let asyncness = if self.token.span.rust_2018() {
1113             self.parse_asyncness()
1114         } else {
1115             IsAsync::NotAsync
1116         };
1117         if asyncness.is_async() {
1118             // Feature gate `async ||` closures.
1119             self.sess.gated_spans.async_closure.borrow_mut().push(self.prev_span);
1120         }
1121
1122         let capture_clause = self.parse_capture_clause();
1123         let decl = self.parse_fn_block_decl()?;
1124         let decl_hi = self.prev_span;
1125         let body = match decl.output {
1126             FunctionRetTy::Default(_) => {
1127                 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
1128                 self.parse_expr_res(restrictions, None)?
1129             },
1130             _ => {
1131                 // If an explicit return type is given, require a
1132                 // block to appear (RFC 968).
1133                 let body_lo = self.token.span;
1134                 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
1135             }
1136         };
1137
1138         Ok(self.mk_expr(
1139             lo.to(body.span),
1140             ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
1141             attrs))
1142     }
1143
1144     /// Parse an optional `move` prefix to a closure lke construct.
1145     fn parse_capture_clause(&mut self) -> CaptureBy {
1146         if self.eat_keyword(kw::Move) {
1147             CaptureBy::Value
1148         } else {
1149             CaptureBy::Ref
1150         }
1151     }
1152
1153     /// Parses the `|arg, arg|` header of a closure.
1154     fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
1155         let inputs_captures = {
1156             if self.eat(&token::OrOr) {
1157                 Vec::new()
1158             } else {
1159                 self.expect(&token::BinOp(token::Or))?;
1160                 let args = self.parse_seq_to_before_tokens(
1161                     &[&token::BinOp(token::Or), &token::OrOr],
1162                     SeqSep::trailing_allowed(token::Comma),
1163                     TokenExpectType::NoExpect,
1164                     |p| p.parse_fn_block_param()
1165                 )?.0;
1166                 self.expect_or()?;
1167                 args
1168             }
1169         };
1170         let output = self.parse_ret_ty(true)?;
1171
1172         Ok(P(FnDecl {
1173             inputs: inputs_captures,
1174             output,
1175             c_variadic: false
1176         }))
1177     }
1178
1179     /// Parses a parameter in a lambda header (e.g., `|arg, arg|`).
1180     fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
1181         let lo = self.token.span;
1182         let attrs = self.parse_param_attributes()?;
1183         let pat = self.parse_pat(PARAM_EXPECTED)?;
1184         let t = if self.eat(&token::Colon) {
1185             self.parse_ty()?
1186         } else {
1187             P(Ty {
1188                 id: ast::DUMMY_NODE_ID,
1189                 node: TyKind::Infer,
1190                 span: self.prev_span,
1191             })
1192         };
1193         let span = lo.to(self.token.span);
1194         Ok(Param {
1195             attrs: attrs.into(),
1196             ty: t,
1197             pat,
1198             span,
1199             id: ast::DUMMY_NODE_ID
1200         })
1201     }
1202
1203     /// Parses an `if` expression (`if` token already eaten).
1204     fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1205         let lo = self.prev_span;
1206         let cond = self.parse_cond_expr()?;
1207
1208         // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1209         // verify that the last statement is either an implicit return (no `;`) or an explicit
1210         // return. This won't catch blocks with an explicit `return`, but that would be caught by
1211         // the dead code lint.
1212         if self.eat_keyword(kw::Else) || !cond.returns() {
1213             let sp = self.sess.source_map().next_point(lo);
1214             let mut err = self.diagnostic()
1215                 .struct_span_err(sp, "missing condition for `if` expression");
1216             err.span_label(sp, "expected if condition here");
1217             return Err(err)
1218         }
1219         let not_block = self.token != token::OpenDelim(token::Brace);
1220         let thn = self.parse_block().map_err(|mut err| {
1221             if not_block {
1222                 err.span_label(lo, "this `if` statement has a condition, but no block");
1223             }
1224             err
1225         })?;
1226         let mut els: Option<P<Expr>> = None;
1227         let mut hi = thn.span;
1228         if self.eat_keyword(kw::Else) {
1229             let elexpr = self.parse_else_expr()?;
1230             hi = elexpr.span;
1231             els = Some(elexpr);
1232         }
1233         Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
1234     }
1235
1236     /// Parse the condition of a `if`- or `while`-expression
1237     fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
1238         let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1239
1240         if let ExprKind::Let(..) = cond.node {
1241             // Remove the last feature gating of a `let` expression since it's stable.
1242             let last = self.sess.gated_spans.let_chains.borrow_mut().pop();
1243             debug_assert_eq!(cond.span, last.unwrap());
1244         }
1245
1246         Ok(cond)
1247     }
1248
1249     /// Parses a `let $pat = $expr` pseudo-expression.
1250     /// The `let` token has already been eaten.
1251     fn parse_let_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1252         let lo = self.prev_span;
1253         // FIXME(or_patterns, Centril | dlrobertson): use `parse_top_pat` instead.
1254         let pat = self.parse_top_pat_unpack(GateOr::No)?;
1255         self.expect(&token::Eq)?;
1256         let expr = self.with_res(
1257             Restrictions::NO_STRUCT_LITERAL,
1258             |this| this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
1259         )?;
1260         let span = lo.to(expr.span);
1261         self.sess.gated_spans.let_chains.borrow_mut().push(span);
1262         Ok(self.mk_expr(span, ExprKind::Let(pat, expr), attrs))
1263     }
1264
1265     /// `else` token already eaten
1266     fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
1267         if self.eat_keyword(kw::If) {
1268             return self.parse_if_expr(ThinVec::new());
1269         } else {
1270             let blk = self.parse_block()?;
1271             return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
1272         }
1273     }
1274
1275     /// Parse a 'for' .. 'in' expression ('for' token already eaten)
1276     fn parse_for_expr(
1277         &mut self,
1278         opt_label: Option<Label>,
1279         span_lo: Span,
1280         mut attrs: ThinVec<Attribute>
1281     ) -> PResult<'a, P<Expr>> {
1282         // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
1283
1284         // Record whether we are about to parse `for (`.
1285         // This is used below for recovery in case of `for ( $stuff ) $block`
1286         // in which case we will suggest `for $stuff $block`.
1287         let begin_paren = match self.token.kind {
1288             token::OpenDelim(token::Paren) => Some(self.token.span),
1289             _ => None,
1290         };
1291
1292         let pat = self.parse_top_pat(GateOr::Yes)?;
1293         if !self.eat_keyword(kw::In) {
1294             let in_span = self.prev_span.between(self.token.span);
1295             self.struct_span_err(in_span, "missing `in` in `for` loop")
1296                 .span_suggestion_short(
1297                     in_span,
1298                     "try adding `in` here", " in ".into(),
1299                     // has been misleading, at least in the past (closed Issue #48492)
1300                     Applicability::MaybeIncorrect
1301                 )
1302                 .emit();
1303         }
1304         let in_span = self.prev_span;
1305         self.check_for_for_in_in_typo(in_span);
1306         let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1307
1308         let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
1309
1310         let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
1311         attrs.extend(iattrs);
1312
1313         let hi = self.prev_span;
1314         Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
1315     }
1316
1317     /// Parses a `while` or `while let` expression (`while` token already eaten).
1318     fn parse_while_expr(
1319         &mut self,
1320         opt_label: Option<Label>,
1321         span_lo: Span,
1322         mut attrs: ThinVec<Attribute>
1323     ) -> PResult<'a, P<Expr>> {
1324         let cond = self.parse_cond_expr()?;
1325         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1326         attrs.extend(iattrs);
1327         let span = span_lo.to(body.span);
1328         Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs))
1329     }
1330
1331     /// Parse `loop {...}`, `loop` token already eaten.
1332     fn parse_loop_expr(
1333         &mut self,
1334         opt_label: Option<Label>,
1335         span_lo: Span,
1336         mut attrs: ThinVec<Attribute>
1337     ) -> PResult<'a, P<Expr>> {
1338         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1339         attrs.extend(iattrs);
1340         let span = span_lo.to(body.span);
1341         Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
1342     }
1343
1344     fn eat_label(&mut self) -> Option<Label> {
1345         if let Some(ident) = self.token.lifetime() {
1346             let span = self.token.span;
1347             self.bump();
1348             Some(Label { ident: Ident::new(ident.name, span) })
1349         } else {
1350             None
1351         }
1352     }
1353
1354     // `match` token already eaten
1355     fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1356         let match_span = self.prev_span;
1357         let lo = self.prev_span;
1358         let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1359         if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
1360             if self.token == token::Semi {
1361                 e.span_suggestion_short(
1362                     match_span,
1363                     "try removing this `match`",
1364                     String::new(),
1365                     Applicability::MaybeIncorrect // speculative
1366                 );
1367             }
1368             return Err(e)
1369         }
1370         attrs.extend(self.parse_inner_attributes()?);
1371
1372         let mut arms: Vec<Arm> = Vec::new();
1373         while self.token != token::CloseDelim(token::Brace) {
1374             match self.parse_arm() {
1375                 Ok(arm) => arms.push(arm),
1376                 Err(mut e) => {
1377                     // Recover by skipping to the end of the block.
1378                     e.emit();
1379                     self.recover_stmt();
1380                     let span = lo.to(self.token.span);
1381                     if self.token == token::CloseDelim(token::Brace) {
1382                         self.bump();
1383                     }
1384                     return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
1385                 }
1386             }
1387         }
1388         let hi = self.token.span;
1389         self.bump();
1390         return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
1391     }
1392
1393     crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
1394         let attrs = self.parse_outer_attributes()?;
1395         let lo = self.token.span;
1396         // FIXME(or_patterns, Centril | dlrobertson): use `parse_top_pat` instead.
1397         let pat = self.parse_top_pat_unpack(GateOr::No)?;
1398         let guard = if self.eat_keyword(kw::If) {
1399             Some(self.parse_expr()?)
1400         } else {
1401             None
1402         };
1403         let arrow_span = self.token.span;
1404         self.expect(&token::FatArrow)?;
1405         let arm_start_span = self.token.span;
1406
1407         let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
1408             .map_err(|mut err| {
1409                 err.span_label(arrow_span, "while parsing the `match` arm starting here");
1410                 err
1411             })?;
1412
1413         let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
1414             && self.token != token::CloseDelim(token::Brace);
1415
1416         let hi = self.token.span;
1417
1418         if require_comma {
1419             let cm = self.sess.source_map();
1420             self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
1421                 .map_err(|mut err| {
1422                     match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
1423                         (Ok(ref expr_lines), Ok(ref arm_start_lines))
1424                         if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
1425                             && expr_lines.lines.len() == 2
1426                             && self.token == token::FatArrow => {
1427                             // We check whether there's any trailing code in the parse span,
1428                             // if there isn't, we very likely have the following:
1429                             //
1430                             // X |     &Y => "y"
1431                             //   |        --    - missing comma
1432                             //   |        |
1433                             //   |        arrow_span
1434                             // X |     &X => "x"
1435                             //   |      - ^^ self.token.span
1436                             //   |      |
1437                             //   |      parsed until here as `"y" & X`
1438                             err.span_suggestion_short(
1439                                 cm.next_point(arm_start_span),
1440                                 "missing a comma here to end this `match` arm",
1441                                 ",".to_owned(),
1442                                 Applicability::MachineApplicable
1443                             );
1444                         }
1445                         _ => {
1446                             err.span_label(arrow_span,
1447                                            "while parsing the `match` arm starting here");
1448                         }
1449                     }
1450                     err
1451                 })?;
1452         } else {
1453             self.eat(&token::Comma);
1454         }
1455
1456         Ok(ast::Arm {
1457             attrs,
1458             pats: pat, // FIXME(or_patterns, Centril | dlrobertson): this should just be `pat,`.
1459             guard,
1460             body: expr,
1461             span: lo.to(hi),
1462             id: ast::DUMMY_NODE_ID,
1463         })
1464     }
1465
1466     /// Parses a `try {...}` expression (`try` token already eaten).
1467     fn parse_try_block(
1468         &mut self,
1469         span_lo: Span,
1470         mut attrs: ThinVec<Attribute>
1471     ) -> PResult<'a, P<Expr>> {
1472         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1473         attrs.extend(iattrs);
1474         if self.eat_keyword(kw::Catch) {
1475             let mut error = self.struct_span_err(self.prev_span,
1476                                                  "keyword `catch` cannot follow a `try` block");
1477             error.help("try using `match` on the result of the `try` block instead");
1478             error.emit();
1479             Err(error)
1480         } else {
1481             Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
1482         }
1483     }
1484
1485     fn is_do_catch_block(&self) -> bool {
1486         self.token.is_keyword(kw::Do) &&
1487         self.is_keyword_ahead(1, &[kw::Catch]) &&
1488         self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
1489         !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1490     }
1491
1492     fn is_try_block(&self) -> bool {
1493         self.token.is_keyword(kw::Try) &&
1494         self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
1495         self.token.span.rust_2018() &&
1496         // prevent `while try {} {}`, `if try {} {} else {}`, etc.
1497         !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1498     }
1499
1500     /// Parses an `async move? {...}` expression.
1501     pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
1502         let span_lo = self.token.span;
1503         self.expect_keyword(kw::Async)?;
1504         let capture_clause = self.parse_capture_clause();
1505         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
1506         attrs.extend(iattrs);
1507         Ok(self.mk_expr(
1508             span_lo.to(body.span),
1509             ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
1510     }
1511
1512     fn is_async_block(&self) -> bool {
1513         self.token.is_keyword(kw::Async) &&
1514         (
1515             ( // `async move {`
1516                 self.is_keyword_ahead(1, &[kw::Move]) &&
1517                 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
1518             ) || ( // `async {`
1519                 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
1520             )
1521         )
1522     }
1523
1524     fn maybe_parse_struct_expr(
1525         &mut self,
1526         lo: Span,
1527         path: &ast::Path,
1528         attrs: &ThinVec<Attribute>,
1529     ) -> Option<PResult<'a, P<Expr>>> {
1530         let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
1531         let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
1532             // `{ ident, ` cannot start a block
1533             self.look_ahead(2, |t| t == &token::Comma) ||
1534             self.look_ahead(2, |t| t == &token::Colon) && (
1535                 // `{ ident: token, ` cannot start a block
1536                 self.look_ahead(4, |t| t == &token::Comma) ||
1537                 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
1538                 self.look_ahead(3, |t| !t.can_begin_type())
1539             )
1540         );
1541
1542         if struct_allowed || certainly_not_a_block() {
1543             // This is a struct literal, but we don't can't accept them here
1544             let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
1545             if let (Ok(expr), false) = (&expr, struct_allowed) {
1546                 self.struct_span_err(
1547                     expr.span,
1548                     "struct literals are not allowed here",
1549                 )
1550                 .multipart_suggestion(
1551                     "surround the struct literal with parentheses",
1552                     vec![
1553                         (lo.shrink_to_lo(), "(".to_string()),
1554                         (expr.span.shrink_to_hi(), ")".to_string()),
1555                     ],
1556                     Applicability::MachineApplicable,
1557                 )
1558                 .emit();
1559             }
1560             return Some(expr);
1561         }
1562         None
1563     }
1564
1565     pub(super) fn parse_struct_expr(
1566         &mut self,
1567         lo: Span,
1568         pth: ast::Path,
1569         mut attrs: ThinVec<Attribute>
1570     ) -> PResult<'a, P<Expr>> {
1571         let struct_sp = lo.to(self.prev_span);
1572         self.bump();
1573         let mut fields = Vec::new();
1574         let mut base = None;
1575
1576         attrs.extend(self.parse_inner_attributes()?);
1577
1578         while self.token != token::CloseDelim(token::Brace) {
1579             if self.eat(&token::DotDot) {
1580                 let exp_span = self.prev_span;
1581                 match self.parse_expr() {
1582                     Ok(e) => {
1583                         base = Some(e);
1584                     }
1585                     Err(mut e) => {
1586                         e.emit();
1587                         self.recover_stmt();
1588                     }
1589                 }
1590                 if self.token == token::Comma {
1591                     self.struct_span_err(
1592                         exp_span.to(self.prev_span),
1593                         "cannot use a comma after the base struct",
1594                     )
1595                     .span_suggestion_short(
1596                         self.token.span,
1597                         "remove this comma",
1598                         String::new(),
1599                         Applicability::MachineApplicable
1600                     )
1601                     .note("the base struct must always be the last field")
1602                     .emit();
1603                     self.recover_stmt();
1604                 }
1605                 break;
1606             }
1607
1608             let mut recovery_field = None;
1609             if let token::Ident(name, _) = self.token.kind {
1610                 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
1611                     // Use in case of error after field-looking code: `S { foo: () with a }`
1612                     recovery_field = Some(ast::Field {
1613                         ident: Ident::new(name, self.token.span),
1614                         span: self.token.span,
1615                         expr: self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()),
1616                         is_shorthand: false,
1617                         attrs: ThinVec::new(),
1618                         id: ast::DUMMY_NODE_ID,
1619                     });
1620                 }
1621             }
1622             let mut parsed_field = None;
1623             match self.parse_field() {
1624                 Ok(f) => parsed_field = Some(f),
1625                 Err(mut e) => {
1626                     e.span_label(struct_sp, "while parsing this struct");
1627                     e.emit();
1628
1629                     // If the next token is a comma, then try to parse
1630                     // what comes next as additional fields, rather than
1631                     // bailing out until next `}`.
1632                     if self.token != token::Comma {
1633                         self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
1634                         if self.token != token::Comma {
1635                             break;
1636                         }
1637                     }
1638                 }
1639             }
1640
1641             match self.expect_one_of(&[token::Comma],
1642                                      &[token::CloseDelim(token::Brace)]) {
1643                 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
1644                     // only include the field if there's no parse error for the field name
1645                     fields.push(f);
1646                 }
1647                 Err(mut e) => {
1648                     if let Some(f) = recovery_field {
1649                         fields.push(f);
1650                     }
1651                     e.span_label(struct_sp, "while parsing this struct");
1652                     e.emit();
1653                     self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
1654                     self.eat(&token::Comma);
1655                 }
1656             }
1657         }
1658
1659         let span = lo.to(self.token.span);
1660         self.expect(&token::CloseDelim(token::Brace))?;
1661         return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
1662     }
1663
1664     /// Parse ident (COLON expr)?
1665     fn parse_field(&mut self) -> PResult<'a, Field> {
1666         let attrs = self.parse_outer_attributes()?;
1667         let lo = self.token.span;
1668
1669         // Check if a colon exists one ahead. This means we're parsing a fieldname.
1670         let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
1671             t == &token::Colon || t == &token::Eq
1672         }) {
1673             let fieldname = self.parse_field_name()?;
1674
1675             // Check for an equals token. This means the source incorrectly attempts to
1676             // initialize a field with an eq rather than a colon.
1677             if self.token == token::Eq {
1678                 self.diagnostic()
1679                     .struct_span_err(self.token.span, "expected `:`, found `=`")
1680                     .span_suggestion(
1681                         fieldname.span.shrink_to_hi().to(self.token.span),
1682                         "replace equals symbol with a colon",
1683                         ":".to_string(),
1684                         Applicability::MachineApplicable,
1685                     )
1686                     .emit();
1687             }
1688             self.bump(); // `:`
1689             (fieldname, self.parse_expr()?, false)
1690         } else {
1691             let fieldname = self.parse_ident_common(false)?;
1692
1693             // Mimic `x: x` for the `x` field shorthand.
1694             let path = ast::Path::from_ident(fieldname);
1695             let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
1696             (fieldname, expr, true)
1697         };
1698         Ok(ast::Field {
1699             ident: fieldname,
1700             span: lo.to(expr.span),
1701             expr,
1702             is_shorthand,
1703             attrs: attrs.into(),
1704             id: ast::DUMMY_NODE_ID,
1705         })
1706     }
1707
1708     fn err_dotdotdot_syntax(&self, span: Span) {
1709         self.struct_span_err(span, "unexpected token: `...`")
1710             .span_suggestion(
1711                 span,
1712                 "use `..` for an exclusive range", "..".to_owned(),
1713                 Applicability::MaybeIncorrect
1714             )
1715             .span_suggestion(
1716                 span,
1717                 "or `..=` for an inclusive range", "..=".to_owned(),
1718                 Applicability::MaybeIncorrect
1719             )
1720             .emit();
1721     }
1722
1723     fn err_larrow_operator(&self, span: Span) {
1724         self.struct_span_err(
1725             span,
1726             "unexpected token: `<-`"
1727         ).span_suggestion(
1728             span,
1729             "if you meant to write a comparison against a negative value, add a \
1730              space in between `<` and `-`",
1731             "< -".to_string(),
1732             Applicability::MaybeIncorrect
1733         ).emit();
1734     }
1735
1736     fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
1737         ExprKind::AssignOp(binop, lhs, rhs)
1738     }
1739
1740     fn mk_range(
1741         &self,
1742         start: Option<P<Expr>>,
1743         end: Option<P<Expr>>,
1744         limits: RangeLimits
1745     ) -> PResult<'a, ExprKind> {
1746         if end.is_none() && limits == RangeLimits::Closed {
1747             Err(self.span_fatal_err(self.token.span, Error::InclusiveRangeWithNoEnd))
1748         } else {
1749             Ok(ExprKind::Range(start, end, limits))
1750         }
1751     }
1752
1753     fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
1754         ExprKind::Unary(unop, expr)
1755     }
1756
1757     fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
1758         ExprKind::Binary(binop, lhs, rhs)
1759     }
1760
1761     fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
1762         ExprKind::Index(expr, idx)
1763     }
1764
1765     fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
1766         ExprKind::Call(f, args)
1767     }
1768
1769     fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
1770         let span = lo.to(self.prev_span);
1771         let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), ThinVec::new());
1772         self.recover_from_await_method_call();
1773         Ok(await_expr)
1774     }
1775
1776     crate fn mk_expr(&self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1777         P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
1778     }
1779 }