]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/stmt.rs
Rollup merge of #95749 - compiler-errors:ambig, r=oli-obk
[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, 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(token::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(token::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 =
168             if delim == token::Brace { MacStmtStyle::Braces } else { MacStmtStyle::NoBraces };
169
170         let mac = MacCall { path, args, prior_type_ascription: self.last_type_ascription };
171
172         let kind =
173             if (delim == token::Brace && self.token != token::Dot && self.token != token::Question)
174                 || self.token == token::Semi
175                 || self.token == token::Eof
176             {
177                 StmtKind::MacCall(P(MacCallStmt { mac, style, attrs, tokens: None }))
178             } else {
179                 // Since none of the above applied, this is an expression statement macro.
180                 let e = self.mk_expr(lo.to(hi), ExprKind::MacCall(mac), AttrVec::new());
181                 let e = self.maybe_recover_from_bad_qpath(e, true)?;
182                 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
183                 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
184                 StmtKind::Expr(e)
185             };
186         Ok(self.mk_stmt(lo.to(hi), kind))
187     }
188
189     /// Error on outer attributes in this context.
190     /// Also error if the previous token was a doc comment.
191     fn error_outer_attrs(&self, attrs: &[Attribute]) {
192         if let [.., last] = attrs {
193             if last.is_doc_comment() {
194                 self.span_err(last.span, Error::UselessDocComment).emit();
195             } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
196                 self.struct_span_err(last.span, "expected statement after outer attribute").emit();
197             }
198         }
199     }
200
201     fn recover_stmt_local(
202         &mut self,
203         lo: Span,
204         attrs: AttrWrapper,
205         msg: &str,
206         sugg: &str,
207     ) -> PResult<'a, Stmt> {
208         let stmt = self.recover_local_after_let(lo, attrs)?;
209         self.struct_span_err(lo, "invalid variable declaration")
210             .span_suggestion(lo, msg, sugg.to_string(), Applicability::MachineApplicable)
211             .emit();
212         Ok(stmt)
213     }
214
215     fn parse_local_mk(
216         &mut self,
217         lo: Span,
218         attrs: AttrWrapper,
219         capture_semi: bool,
220         force_collect: ForceCollect,
221     ) -> PResult<'a, Stmt> {
222         self.collect_tokens_trailing_token(attrs, force_collect, |this, attrs| {
223             this.expect_keyword(kw::Let)?;
224             let local = this.parse_local(attrs.into())?;
225             let trailing = if capture_semi && this.token.kind == token::Semi {
226                 TrailingToken::Semi
227             } else {
228                 TrailingToken::None
229             };
230             Ok((this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Local(local)), trailing))
231         })
232     }
233
234     fn recover_local_after_let(&mut self, lo: Span, attrs: AttrWrapper) -> PResult<'a, Stmt> {
235         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
236             let local = this.parse_local(attrs.into())?;
237             // FIXME - maybe capture semicolon in recovery?
238             Ok((
239                 this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Local(local)),
240                 TrailingToken::None,
241             ))
242         })
243     }
244
245     /// Parses a local variable declaration.
246     fn parse_local(&mut self, attrs: AttrVec) -> PResult<'a, P<Local>> {
247         let lo = self.prev_token.span;
248         let (pat, colon) = self.parse_pat_before_ty(None, RecoverComma::Yes, "`let` bindings")?;
249
250         let (err, ty) = if colon {
251             // Save the state of the parser before parsing type normally, in case there is a `:`
252             // instead of an `=` typo.
253             let parser_snapshot_before_type = self.clone();
254             let colon_sp = self.prev_token.span;
255             match self.parse_ty() {
256                 Ok(ty) => (None, Some(ty)),
257                 Err(mut err) => {
258                     if let Ok(snip) = self.span_to_snippet(pat.span) {
259                         err.span_label(pat.span, format!("while parsing the type for `{}`", snip));
260                     }
261                     let err = if self.check(&token::Eq) {
262                         err.emit();
263                         None
264                     } else {
265                         // Rewind to before attempting to parse the type and continue parsing.
266                         let parser_snapshot_after_type =
267                             mem::replace(self, parser_snapshot_before_type);
268                         Some((parser_snapshot_after_type, colon_sp, err))
269                     };
270                     (err, None)
271                 }
272             }
273         } else {
274             (None, None)
275         };
276         let init = match (self.parse_initializer(err.is_some()), err) {
277             (Ok(init), None) => {
278                 // init parsed, ty parsed
279                 init
280             }
281             (Ok(init), Some((_, colon_sp, mut err))) => {
282                 // init parsed, ty error
283                 // Could parse the type as if it were the initializer, it is likely there was a
284                 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
285                 err.span_suggestion_short(
286                     colon_sp,
287                     "use `=` if you meant to assign",
288                     " =".to_string(),
289                     Applicability::MachineApplicable,
290                 );
291                 err.emit();
292                 // As this was parsed successfully, continue as if the code has been fixed for the
293                 // rest of the file. It will still fail due to the emitted error, but we avoid
294                 // extra noise.
295                 init
296             }
297             (Err(init_err), Some((snapshot, _, ty_err))) => {
298                 // init error, ty error
299                 init_err.cancel();
300                 // Couldn't parse the type nor the initializer, only raise the type error and
301                 // return to the parser state before parsing the type as the initializer.
302                 // let x: <parse_error>;
303                 *self = snapshot;
304                 return Err(ty_err);
305             }
306             (Err(err), None) => {
307                 // init error, ty parsed
308                 // Couldn't parse the initializer and we're not attempting to recover a failed
309                 // parse of the type, return the error.
310                 return Err(err);
311             }
312         };
313         let kind = match init {
314             None => LocalKind::Decl,
315             Some(init) => {
316                 if self.eat_keyword(kw::Else) {
317                     if self.token.is_keyword(kw::If) {
318                         // `let...else if`. Emit the same error that `parse_block()` would,
319                         // but explicitly point out that this pattern is not allowed.
320                         let msg = "conditional `else if` is not supported for `let...else`";
321                         return Err(self.error_block_no_opening_brace_msg(msg));
322                     }
323                     let els = self.parse_block()?;
324                     self.check_let_else_init_bool_expr(&init);
325                     self.check_let_else_init_trailing_brace(&init);
326                     LocalKind::InitElse(init, els)
327                 } else {
328                     LocalKind::Init(init)
329                 }
330             }
331         };
332         let hi = if self.token == token::Semi { self.token.span } else { self.prev_token.span };
333         Ok(P(ast::Local { ty, pat, kind, id: DUMMY_NODE_ID, span: lo.to(hi), attrs, tokens: None }))
334     }
335
336     fn check_let_else_init_bool_expr(&self, init: &ast::Expr) {
337         if let ast::ExprKind::Binary(op, ..) = init.kind {
338             if op.node.lazy() {
339                 let suggs = vec![
340                     (init.span.shrink_to_lo(), "(".to_string()),
341                     (init.span.shrink_to_hi(), ")".to_string()),
342                 ];
343                 self.struct_span_err(
344                     init.span,
345                     &format!(
346                         "a `{}` expression cannot be directly assigned in `let...else`",
347                         op.node.to_string()
348                     ),
349                 )
350                 .multipart_suggestion(
351                     "wrap the expression in parentheses",
352                     suggs,
353                     Applicability::MachineApplicable,
354                 )
355                 .emit();
356             }
357         }
358     }
359
360     fn check_let_else_init_trailing_brace(&self, init: &ast::Expr) {
361         if let Some(trailing) = classify::expr_trailing_brace(init) {
362             let err_span = trailing.span.with_lo(trailing.span.hi() - BytePos(1));
363             let suggs = vec![
364                 (trailing.span.shrink_to_lo(), "(".to_string()),
365                 (trailing.span.shrink_to_hi(), ")".to_string()),
366             ];
367             self.struct_span_err(
368                 err_span,
369                 "right curly brace `}` before `else` in a `let...else` statement not allowed",
370             )
371             .multipart_suggestion(
372                 "try wrapping the expression in parentheses",
373                 suggs,
374                 Applicability::MachineApplicable,
375             )
376             .emit();
377         }
378     }
379
380     /// Parses the RHS of a local variable declaration (e.g., `= 14;`).
381     fn parse_initializer(&mut self, eq_optional: bool) -> PResult<'a, Option<P<Expr>>> {
382         let eq_consumed = match self.token.kind {
383             token::BinOpEq(..) => {
384                 // Recover `let x <op>= 1` as `let x = 1`
385                 self.struct_span_err(
386                     self.token.span,
387                     "can't reassign to an uninitialized variable",
388                 )
389                 .span_suggestion_short(
390                     self.token.span,
391                     "initialize the variable",
392                     "=".to_string(),
393                     Applicability::MaybeIncorrect,
394                 )
395                 .help("if you meant to overwrite, remove the `let` binding")
396                 .emit();
397                 self.bump();
398                 true
399             }
400             _ => self.eat(&token::Eq),
401         };
402
403         Ok(if eq_consumed || eq_optional { Some(self.parse_expr()?) } else { None })
404     }
405
406     /// Parses a block. No inner attributes are allowed.
407     pub(super) fn parse_block(&mut self) -> PResult<'a, P<Block>> {
408         let (attrs, block) = self.parse_inner_attrs_and_block()?;
409         if let [.., last] = &*attrs {
410             self.error_on_forbidden_inner_attr(last.span, DEFAULT_INNER_ATTR_FORBIDDEN);
411         }
412         Ok(block)
413     }
414
415     fn error_block_no_opening_brace_msg(
416         &mut self,
417         msg: &str,
418     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
419         let sp = self.token.span;
420         let mut e = self.struct_span_err(sp, msg);
421         let do_not_suggest_help = self.token.is_keyword(kw::In) || self.token == token::Colon;
422
423         // Check to see if the user has written something like
424         //
425         //    if (cond)
426         //      bar;
427         //
428         // which is valid in other languages, but not Rust.
429         match self.parse_stmt_without_recovery(false, ForceCollect::No) {
430             // If the next token is an open brace (e.g., `if a b {`), the place-
431             // inside-a-block suggestion would be more likely wrong than right.
432             Ok(Some(_))
433                 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
434                     || do_not_suggest_help => {}
435             // Do not suggest `if foo println!("") {;}` (as would be seen in test for #46836).
436             Ok(Some(Stmt { kind: StmtKind::Empty, .. })) => {}
437             Ok(Some(stmt)) => {
438                 let stmt_own_line = self.sess.source_map().is_line_before_span_empty(sp);
439                 let stmt_span = if stmt_own_line && self.eat(&token::Semi) {
440                     // Expand the span to include the semicolon.
441                     stmt.span.with_hi(self.prev_token.span.hi())
442                 } else {
443                     stmt.span
444                 };
445                 e.multipart_suggestion(
446                     "try placing this code inside a block",
447                     vec![
448                         (stmt_span.shrink_to_lo(), "{ ".to_string()),
449                         (stmt_span.shrink_to_hi(), " }".to_string()),
450                     ],
451                     // Speculative; has been misleading in the past (#46836).
452                     Applicability::MaybeIncorrect,
453                 );
454             }
455             Err(e) => {
456                 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
457                 e.cancel();
458             }
459             _ => {}
460         }
461         e.span_label(sp, "expected `{`");
462         e
463     }
464
465     fn error_block_no_opening_brace<T>(&mut self) -> PResult<'a, T> {
466         let tok = super::token_descr(&self.token);
467         let msg = format!("expected `{{`, found {}", tok);
468         Err(self.error_block_no_opening_brace_msg(&msg))
469     }
470
471     /// Parses a block. Inner attributes are allowed.
472     pub(super) fn parse_inner_attrs_and_block(
473         &mut self,
474     ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
475         self.parse_block_common(self.token.span, BlockCheckMode::Default)
476     }
477
478     /// Parses a block. Inner attributes are allowed.
479     pub(super) fn parse_block_common(
480         &mut self,
481         lo: Span,
482         blk_mode: BlockCheckMode,
483     ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
484         maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
485
486         self.maybe_recover_unexpected_block_label();
487         if !self.eat(&token::OpenDelim(token::Brace)) {
488             return self.error_block_no_opening_brace();
489         }
490
491         let attrs = self.parse_inner_attributes()?;
492         let tail = match self.maybe_suggest_struct_literal(lo, blk_mode) {
493             Some(tail) => tail?,
494             None => self.parse_block_tail(lo, blk_mode, AttemptLocalParseRecovery::Yes)?,
495         };
496         Ok((attrs, tail))
497     }
498
499     /// Parses the rest of a block expression or function body.
500     /// Precondition: already parsed the '{'.
501     crate fn parse_block_tail(
502         &mut self,
503         lo: Span,
504         s: BlockCheckMode,
505         recover: AttemptLocalParseRecovery,
506     ) -> PResult<'a, P<Block>> {
507         let mut stmts = vec![];
508         while !self.eat(&token::CloseDelim(token::Brace)) {
509             if self.token == token::Eof {
510                 break;
511             }
512             let stmt = match self.parse_full_stmt(recover) {
513                 Err(mut err) if recover.yes() => {
514                     self.maybe_annotate_with_ascription(&mut err, false);
515                     err.emit();
516                     self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
517                     Some(self.mk_stmt_err(self.token.span))
518                 }
519                 Ok(stmt) => stmt,
520                 Err(err) => return Err(err),
521             };
522             if let Some(stmt) = stmt {
523                 stmts.push(stmt);
524             } else {
525                 // Found only `;` or `}`.
526                 continue;
527             };
528         }
529         Ok(self.mk_block(stmts, s, lo.to(self.prev_token.span)))
530     }
531
532     /// Parses a statement, including the trailing semicolon.
533     pub fn parse_full_stmt(
534         &mut self,
535         recover: AttemptLocalParseRecovery,
536     ) -> PResult<'a, Option<Stmt>> {
537         // Skip looking for a trailing semicolon when we have an interpolated statement.
538         maybe_whole!(self, NtStmt, |x| Some(x.into_inner()));
539
540         let Some(mut stmt) = self.parse_stmt_without_recovery(true, ForceCollect::No)? else {
541             return Ok(None);
542         };
543
544         let mut eat_semi = true;
545         match stmt.kind {
546             // Expression without semicolon.
547             StmtKind::Expr(ref mut expr)
548                 if self.token != token::Eof && classify::expr_requires_semi_to_be_stmt(expr) =>
549             {
550                 // Just check for errors and recover; do not eat semicolon yet.
551                 if let Err(mut e) =
552                     self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
553                 {
554                     if let TokenKind::DocComment(..) = self.token.kind {
555                         if let Ok(snippet) = self.span_to_snippet(self.token.span) {
556                             let sp = self.token.span;
557                             let marker = &snippet[..3];
558                             let (comment_marker, doc_comment_marker) = marker.split_at(2);
559
560                             e.span_suggestion(
561                                 sp.with_hi(sp.lo() + BytePos(marker.len() as u32)),
562                                 &format!(
563                                     "add a space before `{}` to use a regular comment",
564                                     doc_comment_marker,
565                                 ),
566                                 format!("{} {}", comment_marker, doc_comment_marker),
567                                 Applicability::MaybeIncorrect,
568                             );
569                         }
570                     }
571                     if let Err(mut e) =
572                         self.check_mistyped_turbofish_with_multiple_type_params(e, expr)
573                     {
574                         if recover.no() {
575                             return Err(e);
576                         }
577                         e.emit();
578                         self.recover_stmt();
579                     }
580                     // Don't complain about type errors in body tail after parse error (#57383).
581                     let sp = expr.span.to(self.prev_token.span);
582                     *expr = self.mk_expr_err(sp);
583                 }
584             }
585             StmtKind::Expr(_) | StmtKind::MacCall(_) => {}
586             StmtKind::Local(ref mut local) if let Err(e) = self.expect_semi() => {
587                 // We might be at the `,` in `let x = foo<bar, baz>;`. Try to recover.
588                 match &mut local.kind {
589                     LocalKind::Init(expr) | LocalKind::InitElse(expr, _) => {
590                         self.check_mistyped_turbofish_with_multiple_type_params(e, expr)?;
591                         // We found `foo<bar, baz>`, have we fully recovered?
592                         self.expect_semi()?;
593                     }
594                     LocalKind::Decl => return Err(e),
595                 }
596                 eat_semi = false;
597             }
598             StmtKind::Empty | StmtKind::Item(_) | StmtKind::Local(_) | StmtKind::Semi(_) => eat_semi = false,
599         }
600
601         if eat_semi && self.eat(&token::Semi) {
602             stmt = stmt.add_trailing_semicolon();
603         }
604         stmt.span = stmt.span.to(self.prev_token.span);
605         Ok(Some(stmt))
606     }
607
608     pub(super) fn mk_block(&self, stmts: Vec<Stmt>, rules: BlockCheckMode, span: Span) -> P<Block> {
609         P(Block {
610             stmts,
611             id: DUMMY_NODE_ID,
612             rules,
613             span,
614             tokens: None,
615             could_be_bare_literal: false,
616         })
617     }
618
619     pub(super) fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt {
620         Stmt { id: DUMMY_NODE_ID, kind, span }
621     }
622
623     pub(super) fn mk_stmt_err(&self, span: Span) -> Stmt {
624         self.mk_stmt(span, StmtKind::Expr(self.mk_expr_err(span)))
625     }
626
627     pub(super) fn mk_block_err(&self, span: Span) -> P<Block> {
628         self.mk_block(vec![self.mk_stmt_err(span)], BlockCheckMode::Default, span)
629     }
630 }