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