]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/stmt.rs
Improves parser diagnostics, fixes #93867
[rust.git] / compiler / rustc_parse / src / parser / stmt.rs
1 use super::attr::DEFAULT_INNER_ATTR_FORBIDDEN;
2 use super::diagnostics::{AttemptLocalParseRecovery, Error};
3 use super::expr::LhsExpr;
4 use super::pat::RecoverComma;
5 use super::path::PathStyle;
6 use super::TrailingToken;
7 use super::{
8     AttrWrapper, BlockMode, FnParseMode, ForceCollect, Parser, Restrictions, SemiColonMode,
9 };
10 use crate::maybe_whole;
11
12 use rustc_ast as ast;
13 use rustc_ast::ptr::P;
14 use rustc_ast::token::{self, Delimiter, TokenKind};
15 use rustc_ast::util::classify;
16 use rustc_ast::{
17     AstLike, AttrStyle, AttrVec, Attribute, LocalKind, MacCall, MacCallStmt, MacStmtStyle,
18 };
19 use rustc_ast::{Block, BlockCheckMode, Expr, ExprKind, Local, Stmt};
20 use rustc_ast::{StmtKind, DUMMY_NODE_ID};
21 use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed, PResult};
22 use rustc_span::source_map::{BytePos, Span};
23 use rustc_span::symbol::{kw, sym};
24
25 use std::mem;
26
27 impl<'a> Parser<'a> {
28     /// Parses a statement. This stops just before trailing semicolons on everything but items.
29     /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
30     // Public for rustfmt usage.
31     pub fn parse_stmt(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<Stmt>> {
32         Ok(self.parse_stmt_without_recovery(false, force_collect).unwrap_or_else(|mut e| {
33             e.emit();
34             self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
35             None
36         }))
37     }
38
39     /// If `force_capture` is true, forces collection of tokens regardless of whether
40     /// or not we have attributes
41     crate fn parse_stmt_without_recovery(
42         &mut self,
43         capture_semi: bool,
44         force_collect: ForceCollect,
45     ) -> PResult<'a, Option<Stmt>> {
46         let attrs = self.parse_outer_attributes()?;
47         let lo = self.token.span;
48
49         // Don't use `maybe_whole` so that we have precise control
50         // over when we bump the parser
51         if let token::Interpolated(nt) = &self.token.kind && let token::NtStmt(stmt) = &**nt {
52             let mut stmt = stmt.clone();
53             self.bump();
54             stmt.visit_attrs(|stmt_attrs| {
55                 attrs.prepend_to_nt_inner(stmt_attrs);
56             });
57             return Ok(Some(stmt.into_inner()));
58         }
59
60         Ok(Some(if self.token.is_keyword(kw::Let) {
61             self.parse_local_mk(lo, attrs, capture_semi, force_collect)?
62         } else if self.is_kw_followed_by_ident(kw::Mut) {
63             self.recover_stmt_local(lo, attrs, "missing keyword", "let mut")?
64         } else if self.is_kw_followed_by_ident(kw::Auto) {
65             self.bump(); // `auto`
66             let msg = "write `let` instead of `auto` to introduce a new variable";
67             self.recover_stmt_local(lo, attrs, msg, "let")?
68         } else if self.is_kw_followed_by_ident(sym::var) {
69             self.bump(); // `var`
70             let msg = "write `let` instead of `var` to introduce a new variable";
71             self.recover_stmt_local(lo, attrs, msg, "let")?
72         } else if self.check_path() && !self.token.is_qpath_start() && !self.is_path_start_item() {
73             // We have avoided contextual keywords like `union`, items with `crate` visibility,
74             // or `auto trait` items. We aim to parse an arbitrary path `a::b` but not something
75             // that starts like a path (1 token), but it fact not a path.
76             // Also, we avoid stealing syntax from `parse_item_`.
77             if force_collect == ForceCollect::Yes {
78                 self.collect_tokens_no_attrs(|this| this.parse_stmt_path_start(lo, attrs))
79             } else {
80                 self.parse_stmt_path_start(lo, attrs)
81             }?
82         } else if let Some(item) = self.parse_item_common(
83             attrs.clone(),
84             false,
85             true,
86             FnParseMode { req_name: |_| true, req_body: true },
87             force_collect,
88         )? {
89             // FIXME: Bad copy of attrs
90             self.mk_stmt(lo.to(item.span), StmtKind::Item(P(item)))
91         } else if self.eat(&token::Semi) {
92             // Do not attempt to parse an expression if we're done here.
93             self.error_outer_attrs(&attrs.take_for_recovery());
94             self.mk_stmt(lo, StmtKind::Empty)
95         } else if self.token != token::CloseDelim(Delimiter::Brace) {
96             // Remainder are line-expr stmts.
97             let e = if force_collect == ForceCollect::Yes {
98                 self.collect_tokens_no_attrs(|this| {
99                     this.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs))
100                 })
101             } else {
102                 self.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs))
103             }?;
104             if matches!(e.kind, ExprKind::Assign(..)) && self.eat_keyword(kw::Else) {
105                 let bl = self.parse_block()?;
106                 // Destructuring assignment ... else.
107                 // This is not allowed, but point it out in a nice way.
108                 let mut err = self.struct_span_err(
109                     e.span.to(bl.span),
110                     "<assignment> ... else { ... } is not allowed",
111                 );
112                 err.emit();
113             }
114             self.mk_stmt(lo.to(e.span), StmtKind::Expr(e))
115         } else {
116             self.error_outer_attrs(&attrs.take_for_recovery());
117             return Ok(None);
118         }))
119     }
120
121     fn parse_stmt_path_start(&mut self, lo: Span, attrs: AttrWrapper) -> PResult<'a, Stmt> {
122         let stmt = self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
123             let path = this.parse_path(PathStyle::Expr)?;
124
125             if this.eat(&token::Not) {
126                 let stmt_mac = this.parse_stmt_mac(lo, attrs.into(), path)?;
127                 if this.token == token::Semi {
128                     return Ok((stmt_mac, TrailingToken::Semi));
129                 } else {
130                     return Ok((stmt_mac, TrailingToken::None));
131                 }
132             }
133
134             let expr = if this.eat(&token::OpenDelim(Delimiter::Brace)) {
135                 this.parse_struct_expr(None, path, AttrVec::new(), true)?
136             } else {
137                 let hi = this.prev_token.span;
138                 this.mk_expr(lo.to(hi), ExprKind::Path(None, path), AttrVec::new())
139             };
140
141             let expr = this.with_res(Restrictions::STMT_EXPR, |this| {
142                 this.parse_dot_or_call_expr_with(expr, lo, attrs)
143             })?;
144             // `DUMMY_SP` will get overwritten later in this function
145             Ok((this.mk_stmt(rustc_span::DUMMY_SP, StmtKind::Expr(expr)), TrailingToken::None))
146         })?;
147
148         if let StmtKind::Expr(expr) = stmt.kind {
149             // Perform this outside of the `collect_tokens_trailing_token` closure,
150             // since our outer attributes do not apply to this part of the expression
151             let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
152                 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
153             })?;
154             Ok(self.mk_stmt(lo.to(self.prev_token.span), StmtKind::Expr(expr)))
155         } else {
156             Ok(stmt)
157         }
158     }
159
160     /// Parses a statement macro `mac!(args)` provided a `path` representing `mac`.
161     /// At this point, the `!` token after the path has already been eaten.
162     fn parse_stmt_mac(&mut self, lo: Span, attrs: AttrVec, path: ast::Path) -> PResult<'a, Stmt> {
163         let args = self.parse_mac_args()?;
164         let delim = args.delim();
165         let hi = self.prev_token.span;
166
167         let style = match delim {
168             Some(Delimiter::Brace) => MacStmtStyle::Braces,
169             Some(_) => MacStmtStyle::NoBraces,
170             None => unreachable!(),
171         };
172
173         let mac = MacCall { path, args, prior_type_ascription: self.last_type_ascription };
174
175         let kind = if (style == MacStmtStyle::Braces
176             && self.token != token::Dot
177             && self.token != token::Question)
178             || self.token == token::Semi
179             || self.token == token::Eof
180         {
181             StmtKind::MacCall(P(MacCallStmt { mac, style, attrs, tokens: None }))
182         } else {
183             // Since none of the above applied, this is an expression statement macro.
184             let e = self.mk_expr(lo.to(hi), ExprKind::MacCall(mac), AttrVec::new());
185             let e = self.maybe_recover_from_bad_qpath(e, true)?;
186             let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
187             let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
188             StmtKind::Expr(e)
189         };
190         Ok(self.mk_stmt(lo.to(hi), kind))
191     }
192
193     /// Error on outer attributes in this context.
194     /// Also error if the previous token was a doc comment.
195     fn error_outer_attrs(&self, attrs: &[Attribute]) {
196         if let [.., last] = attrs {
197             if last.is_doc_comment() {
198                 self.span_err(last.span, Error::UselessDocComment).emit();
199             } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
200                 self.struct_span_err(last.span, "expected statement after outer attribute").emit();
201             }
202         }
203     }
204
205     fn recover_stmt_local(
206         &mut self,
207         lo: Span,
208         attrs: AttrWrapper,
209         msg: &str,
210         sugg: &str,
211     ) -> PResult<'a, Stmt> {
212         let stmt = self.recover_local_after_let(lo, attrs)?;
213         self.struct_span_err(lo, "invalid variable declaration")
214             .span_suggestion(lo, msg, sugg.to_string(), Applicability::MachineApplicable)
215             .emit();
216         Ok(stmt)
217     }
218
219     fn parse_local_mk(
220         &mut self,
221         lo: Span,
222         attrs: AttrWrapper,
223         capture_semi: bool,
224         force_collect: ForceCollect,
225     ) -> PResult<'a, Stmt> {
226         self.collect_tokens_trailing_token(attrs, force_collect, |this, attrs| {
227             this.expect_keyword(kw::Let)?;
228             let local = this.parse_local(attrs.into())?;
229             let trailing = if capture_semi && this.token.kind == token::Semi {
230                 TrailingToken::Semi
231             } else {
232                 TrailingToken::None
233             };
234             Ok((this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Local(local)), trailing))
235         })
236     }
237
238     fn recover_local_after_let(&mut self, lo: Span, attrs: AttrWrapper) -> PResult<'a, Stmt> {
239         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
240             let local = this.parse_local(attrs.into())?;
241             // FIXME - maybe capture semicolon in recovery?
242             Ok((
243                 this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Local(local)),
244                 TrailingToken::None,
245             ))
246         })
247     }
248
249     /// Parses a local variable declaration.
250     fn parse_local(&mut self, attrs: AttrVec) -> PResult<'a, P<Local>> {
251         let lo = self.prev_token.span;
252         let (pat, colon) = self.parse_pat_before_ty(None, RecoverComma::Yes, "`let` bindings")?;
253
254         let (err, ty) = if colon {
255             // Save the state of the parser before parsing type normally, in case there is a `:`
256             // instead of an `=` typo.
257             let parser_snapshot_before_type = self.clone();
258             let colon_sp = self.prev_token.span;
259             match self.parse_ty() {
260                 Ok(ty) => (None, Some(ty)),
261                 Err(mut err) => {
262                     if let Ok(snip) = self.span_to_snippet(pat.span) {
263                         err.span_label(pat.span, format!("while parsing the type for `{}`", snip));
264                     }
265                     // we use noexpect here because we don't actually expect Eq to be here
266                     // but we are still checking for it in order to be able to handle it if
267                     // it is there
268                     let err = if self.check_noexpect(&token::Eq) {
269                         err.emit();
270                         None
271                     } else {
272                         // Rewind to before attempting to parse the type and continue parsing.
273                         let parser_snapshot_after_type =
274                             mem::replace(self, parser_snapshot_before_type);
275                         Some((parser_snapshot_after_type, colon_sp, err))
276                     };
277                     (err, None)
278                 }
279             }
280         } else {
281             (None, None)
282         };
283         let init = match (self.parse_initializer(err.is_some()), err) {
284             (Ok(init), None) => {
285                 // init parsed, ty parsed
286                 init
287             }
288             (Ok(init), Some((_, colon_sp, mut err))) => {
289                 // init parsed, ty error
290                 // Could parse the type as if it were the initializer, it is likely there was a
291                 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
292                 err.span_suggestion_short(
293                     colon_sp,
294                     "use `=` if you meant to assign",
295                     " =".to_string(),
296                     Applicability::MachineApplicable,
297                 );
298                 err.emit();
299                 // As this was parsed successfully, continue as if the code has been fixed for the
300                 // rest of the file. It will still fail due to the emitted error, but we avoid
301                 // extra noise.
302                 init
303             }
304             (Err(init_err), Some((snapshot, _, ty_err))) => {
305                 // init error, ty error
306                 init_err.cancel();
307                 // Couldn't parse the type nor the initializer, only raise the type error and
308                 // return to the parser state before parsing the type as the initializer.
309                 // let x: <parse_error>;
310                 *self = snapshot;
311                 return Err(ty_err);
312             }
313             (Err(err), None) => {
314                 // init error, ty parsed
315                 // Couldn't parse the initializer and we're not attempting to recover a failed
316                 // parse of the type, return the error.
317                 return Err(err);
318             }
319         };
320         let kind = match init {
321             None => LocalKind::Decl,
322             Some(init) => {
323                 if self.eat_keyword(kw::Else) {
324                     if self.token.is_keyword(kw::If) {
325                         // `let...else if`. Emit the same error that `parse_block()` would,
326                         // but explicitly point out that this pattern is not allowed.
327                         let msg = "conditional `else if` is not supported for `let...else`";
328                         return Err(self.error_block_no_opening_brace_msg(msg));
329                     }
330                     let els = self.parse_block()?;
331                     self.check_let_else_init_bool_expr(&init);
332                     self.check_let_else_init_trailing_brace(&init);
333                     LocalKind::InitElse(init, els)
334                 } else {
335                     LocalKind::Init(init)
336                 }
337             }
338         };
339         let hi = if self.token == token::Semi { self.token.span } else { self.prev_token.span };
340         Ok(P(ast::Local { ty, pat, kind, id: DUMMY_NODE_ID, span: lo.to(hi), attrs, tokens: None }))
341     }
342
343     fn check_let_else_init_bool_expr(&self, init: &ast::Expr) {
344         if let ast::ExprKind::Binary(op, ..) = init.kind {
345             if op.node.lazy() {
346                 let suggs = vec![
347                     (init.span.shrink_to_lo(), "(".to_string()),
348                     (init.span.shrink_to_hi(), ")".to_string()),
349                 ];
350                 self.struct_span_err(
351                     init.span,
352                     &format!(
353                         "a `{}` expression cannot be directly assigned in `let...else`",
354                         op.node.to_string()
355                     ),
356                 )
357                 .multipart_suggestion(
358                     "wrap the expression in parentheses",
359                     suggs,
360                     Applicability::MachineApplicable,
361                 )
362                 .emit();
363             }
364         }
365     }
366
367     fn check_let_else_init_trailing_brace(&self, init: &ast::Expr) {
368         if let Some(trailing) = classify::expr_trailing_brace(init) {
369             let err_span = trailing.span.with_lo(trailing.span.hi() - BytePos(1));
370             let suggs = vec![
371                 (trailing.span.shrink_to_lo(), "(".to_string()),
372                 (trailing.span.shrink_to_hi(), ")".to_string()),
373             ];
374             self.struct_span_err(
375                 err_span,
376                 "right curly brace `}` before `else` in a `let...else` statement not allowed",
377             )
378             .multipart_suggestion(
379                 "try wrapping the expression in parentheses",
380                 suggs,
381                 Applicability::MachineApplicable,
382             )
383             .emit();
384         }
385     }
386
387     /// Parses the RHS of a local variable declaration (e.g., `= 14;`).
388     fn parse_initializer(&mut self, eq_optional: bool) -> PResult<'a, Option<P<Expr>>> {
389         let eq_consumed = match self.token.kind {
390             token::BinOpEq(..) => {
391                 // Recover `let x <op>= 1` as `let x = 1`
392                 self.struct_span_err(
393                     self.token.span,
394                     "can't reassign to an uninitialized variable",
395                 )
396                 .span_suggestion_short(
397                     self.token.span,
398                     "initialize the variable",
399                     "=".to_string(),
400                     Applicability::MaybeIncorrect,
401                 )
402                 .help("if you meant to overwrite, remove the `let` binding")
403                 .emit();
404                 self.bump();
405                 true
406             }
407             _ => self.eat(&token::Eq),
408         };
409
410         Ok(if eq_consumed || eq_optional { Some(self.parse_expr()?) } else { None })
411     }
412
413     /// Parses a block. No inner attributes are allowed.
414     pub(super) fn parse_block(&mut self) -> PResult<'a, P<Block>> {
415         let (attrs, block) = self.parse_inner_attrs_and_block()?;
416         if let [.., last] = &*attrs {
417             self.error_on_forbidden_inner_attr(last.span, DEFAULT_INNER_ATTR_FORBIDDEN);
418         }
419         Ok(block)
420     }
421
422     fn error_block_no_opening_brace_msg(
423         &mut self,
424         msg: &str,
425     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
426         let sp = self.token.span;
427         let mut e = self.struct_span_err(sp, msg);
428         let do_not_suggest_help = self.token.is_keyword(kw::In) || self.token == token::Colon;
429
430         // Check to see if the user has written something like
431         //
432         //    if (cond)
433         //      bar;
434         //
435         // which is valid in other languages, but not Rust.
436         match self.parse_stmt_without_recovery(false, ForceCollect::No) {
437             // If the next token is an open brace (e.g., `if a b {`), the place-
438             // inside-a-block suggestion would be more likely wrong than right.
439             Ok(Some(_))
440                 if self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Brace))
441                     || do_not_suggest_help => {}
442             // Do not suggest `if foo println!("") {;}` (as would be seen in test for #46836).
443             Ok(Some(Stmt { kind: StmtKind::Empty, .. })) => {}
444             Ok(Some(stmt)) => {
445                 let stmt_own_line = self.sess.source_map().is_line_before_span_empty(sp);
446                 let stmt_span = if stmt_own_line && self.eat(&token::Semi) {
447                     // Expand the span to include the semicolon.
448                     stmt.span.with_hi(self.prev_token.span.hi())
449                 } else {
450                     stmt.span
451                 };
452                 e.multipart_suggestion(
453                     "try placing this code inside a block",
454                     vec![
455                         (stmt_span.shrink_to_lo(), "{ ".to_string()),
456                         (stmt_span.shrink_to_hi(), " }".to_string()),
457                     ],
458                     // Speculative; has been misleading in the past (#46836).
459                     Applicability::MaybeIncorrect,
460                 );
461             }
462             Err(e) => {
463                 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
464                 e.cancel();
465             }
466             _ => {}
467         }
468         e.span_label(sp, "expected `{`");
469         e
470     }
471
472     fn error_block_no_opening_brace<T>(&mut self) -> PResult<'a, T> {
473         let tok = super::token_descr(&self.token);
474         let msg = format!("expected `{{`, found {}", tok);
475         Err(self.error_block_no_opening_brace_msg(&msg))
476     }
477
478     /// Parses a block. Inner attributes are allowed.
479     pub(super) fn parse_inner_attrs_and_block(
480         &mut self,
481     ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
482         self.parse_block_common(self.token.span, BlockCheckMode::Default)
483     }
484
485     /// Parses a block. Inner attributes are allowed.
486     pub(super) fn parse_block_common(
487         &mut self,
488         lo: Span,
489         blk_mode: BlockCheckMode,
490     ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
491         maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
492
493         self.maybe_recover_unexpected_block_label();
494         if !self.eat(&token::OpenDelim(Delimiter::Brace)) {
495             return self.error_block_no_opening_brace();
496         }
497
498         let attrs = self.parse_inner_attributes()?;
499         let tail = match self.maybe_suggest_struct_literal(lo, blk_mode) {
500             Some(tail) => tail?,
501             None => self.parse_block_tail(lo, blk_mode, AttemptLocalParseRecovery::Yes)?,
502         };
503         Ok((attrs, tail))
504     }
505
506     /// Parses the rest of a block expression or function body.
507     /// Precondition: already parsed the '{'.
508     crate fn parse_block_tail(
509         &mut self,
510         lo: Span,
511         s: BlockCheckMode,
512         recover: AttemptLocalParseRecovery,
513     ) -> PResult<'a, P<Block>> {
514         let mut stmts = vec![];
515         while !self.eat(&token::CloseDelim(Delimiter::Brace)) {
516             if self.token == token::Eof {
517                 break;
518             }
519             let stmt = match self.parse_full_stmt(recover) {
520                 Err(mut err) if recover.yes() => {
521                     self.maybe_annotate_with_ascription(&mut err, false);
522                     err.emit();
523                     self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
524                     Some(self.mk_stmt_err(self.token.span))
525                 }
526                 Ok(stmt) => stmt,
527                 Err(err) => return Err(err),
528             };
529             if let Some(stmt) = stmt {
530                 stmts.push(stmt);
531             } else {
532                 // Found only `;` or `}`.
533                 continue;
534             };
535         }
536         Ok(self.mk_block(stmts, s, lo.to(self.prev_token.span)))
537     }
538
539     /// Parses a statement, including the trailing semicolon.
540     pub fn parse_full_stmt(
541         &mut self,
542         recover: AttemptLocalParseRecovery,
543     ) -> PResult<'a, Option<Stmt>> {
544         // Skip looking for a trailing semicolon when we have an interpolated statement.
545         maybe_whole!(self, NtStmt, |x| Some(x.into_inner()));
546
547         let Some(mut stmt) = self.parse_stmt_without_recovery(true, ForceCollect::No)? else {
548             return Ok(None);
549         };
550
551         let mut eat_semi = true;
552         match stmt.kind {
553             // Expression without semicolon.
554             StmtKind::Expr(ref mut expr)
555                 if self.token != token::Eof && classify::expr_requires_semi_to_be_stmt(expr) =>
556             {
557                 // Just check for errors and recover; do not eat semicolon yet.
558                 if let Err(mut e) =
559                     self.expect_one_of(&[], &[token::Semi, token::CloseDelim(Delimiter::Brace)])
560                 {
561                     if let TokenKind::DocComment(..) = self.token.kind {
562                         if let Ok(snippet) = self.span_to_snippet(self.token.span) {
563                             let sp = self.token.span;
564                             let marker = &snippet[..3];
565                             let (comment_marker, doc_comment_marker) = marker.split_at(2);
566
567                             e.span_suggestion(
568                                 sp.with_hi(sp.lo() + BytePos(marker.len() as u32)),
569                                 &format!(
570                                     "add a space before `{}` to use a regular comment",
571                                     doc_comment_marker,
572                                 ),
573                                 format!("{} {}", comment_marker, doc_comment_marker),
574                                 Applicability::MaybeIncorrect,
575                             );
576                         }
577                     }
578                     if let Err(mut e) =
579                         self.check_mistyped_turbofish_with_multiple_type_params(e, expr)
580                     {
581                         if recover.no() {
582                             return Err(e);
583                         }
584                         e.emit();
585                         self.recover_stmt();
586                     }
587                     // Don't complain about type errors in body tail after parse error (#57383).
588                     let sp = expr.span.to(self.prev_token.span);
589                     *expr = self.mk_expr_err(sp);
590                 }
591             }
592             StmtKind::Expr(_) | StmtKind::MacCall(_) => {}
593             StmtKind::Local(ref mut local) if let Err(e) = self.expect_semi() => {
594                 // We might be at the `,` in `let x = foo<bar, baz>;`. Try to recover.
595                 match &mut local.kind {
596                     LocalKind::Init(expr) | LocalKind::InitElse(expr, _) => {
597                         self.check_mistyped_turbofish_with_multiple_type_params(e, expr)?;
598                         // We found `foo<bar, baz>`, have we fully recovered?
599                         self.expect_semi()?;
600                     }
601                     LocalKind::Decl => return Err(e),
602                 }
603                 eat_semi = false;
604             }
605             StmtKind::Empty | StmtKind::Item(_) | StmtKind::Local(_) | StmtKind::Semi(_) => eat_semi = false,
606         }
607
608         if eat_semi && self.eat(&token::Semi) {
609             stmt = stmt.add_trailing_semicolon();
610         }
611         stmt.span = stmt.span.to(self.prev_token.span);
612         Ok(Some(stmt))
613     }
614
615     pub(super) fn mk_block(&self, stmts: Vec<Stmt>, rules: BlockCheckMode, span: Span) -> P<Block> {
616         P(Block {
617             stmts,
618             id: DUMMY_NODE_ID,
619             rules,
620             span,
621             tokens: None,
622             could_be_bare_literal: false,
623         })
624     }
625
626     pub(super) fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt {
627         Stmt { id: DUMMY_NODE_ID, kind, span }
628     }
629
630     pub(super) fn mk_stmt_err(&self, span: Span) -> Stmt {
631         self.mk_stmt(span, StmtKind::Expr(self.mk_expr_err(span)))
632     }
633
634     pub(super) fn mk_block_err(&self, span: Span) -> P<Block> {
635         self.mk_block(vec![self.mk_stmt_err(span)], BlockCheckMode::Default, span)
636     }
637 }