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