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