]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_parse/src/parser/stmt.rs
New upstream version 1.61.0+dfsg1
[rustc.git] / compiler / rustc_parse / src / parser / stmt.rs
CommitLineData
ba9703b0 1use super::attr::DEFAULT_INNER_ATTR_FORBIDDEN;
29967ef6 2use super::diagnostics::{AttemptLocalParseRecovery, Error};
416331ca 3use super::expr::LhsExpr;
cdc7bbd5 4use super::pat::RecoverComma;
dfeec247 5use super::path::PathStyle;
6a06907d 6use super::TrailingToken;
a2a8927a
XL
7use super::{
8 AttrWrapper, BlockMode, FnParseMode, ForceCollect, Parser, Restrictions, SemiColonMode,
9};
6a06907d 10use crate::maybe_whole;
60c5eb7d 11
3dfed10e 12use rustc_ast as ast;
74b04a01
XL
13use rustc_ast::ptr::P;
14use rustc_ast::token::{self, TokenKind};
15use rustc_ast::util::classify;
94222f64
XL
16use rustc_ast::{
17 AstLike, AttrStyle, AttrVec, Attribute, LocalKind, MacCall, MacCallStmt, MacStmtStyle,
18};
6a06907d
XL
19use rustc_ast::{Block, BlockCheckMode, Expr, ExprKind, Local, Stmt};
20use rustc_ast::{StmtKind, DUMMY_NODE_ID};
ee023bcb 21use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed, PResult};
74b04a01
XL
22use rustc_span::source_map::{BytePos, Span};
23use rustc_span::symbol::{kw, sym};
416331ca
XL
24
25use std::mem;
416331ca
XL
26
27impl<'a> Parser<'a> {
e1599b0c 28 /// Parses a statement. This stops just before trailing semicolons on everything but items.
416331ca 29 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
1b1a35ee 30 // Public for rustfmt usage.
5869c6ff
XL
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| {
416331ca
XL
33 e.emit();
34 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
35 None
dfeec247 36 }))
416331ca
XL
37 }
38
5869c6ff
XL
39 /// If `force_capture` is true, forces collection of tokens regardless of whether
40 /// or not we have attributes
6a06907d 41 crate fn parse_stmt_without_recovery(
5869c6ff
XL
42 &mut self,
43 capture_semi: bool,
44 force_collect: ForceCollect,
45 ) -> PResult<'a, Option<Stmt>> {
6a06907d 46 let attrs = self.parse_outer_attributes()?;
416331ca
XL
47 let lo = self.token.span;
48
6a06907d
XL
49 // Don't use `maybe_whole` so that we have precise control
50 // over when we bump the parser
ee023bcb
FG
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));
6a06907d 58 }
fc512014 59
5869c6ff 60 Ok(Some(if self.token.is_keyword(kw::Let) {
6a06907d 61 self.parse_local_mk(lo, attrs, capture_semi, force_collect)?
5869c6ff 62 } else if self.is_kw_followed_by_ident(kw::Mut) {
cdc7bbd5 63 self.recover_stmt_local(lo, attrs, "missing keyword", "let mut")?
5869c6ff
XL
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";
cdc7bbd5 67 self.recover_stmt_local(lo, attrs, msg, "let")?
5869c6ff
XL
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";
cdc7bbd5 71 self.recover_stmt_local(lo, attrs, msg, "let")?
5869c6ff
XL
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_`.
17df50a5
XL
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 }?
a2a8927a
XL
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 )? {
5869c6ff
XL
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.
6a06907d 93 self.error_outer_attrs(&attrs.take_for_recovery());
5869c6ff
XL
94 self.mk_stmt(lo, StmtKind::Empty)
95 } else if self.token != token::CloseDelim(token::Brace) {
96 // Remainder are line-expr stmts.
17df50a5
XL
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 }?;
ee023bcb
FG
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 }
5869c6ff 114 self.mk_stmt(lo.to(e.span), StmtKind::Expr(e))
74b04a01 115 } else {
6a06907d 116 self.error_outer_attrs(&attrs.take_for_recovery());
5869c6ff
XL
117 return Ok(None);
118 }))
74b04a01 119 }
dfeec247 120
17df50a5
XL
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| {
5869c6ff 123 let path = this.parse_path(PathStyle::Expr)?;
dfeec247 124
5869c6ff
XL
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 }
dfeec247 133
5869c6ff 134 let expr = if this.eat(&token::OpenDelim(token::Brace)) {
17df50a5 135 this.parse_struct_expr(None, path, AttrVec::new(), true)?
5869c6ff
XL
136 } else {
137 let hi = this.prev_token.span;
138 this.mk_expr(lo.to(hi), ExprKind::Path(None, path), AttrVec::new())
139 };
dfeec247 140
5869c6ff 141 let expr = this.with_res(Restrictions::STMT_EXPR, |this| {
cdc7bbd5
XL
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| {
5869c6ff
XL
152 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
153 })?;
cdc7bbd5
XL
154 Ok(self.mk_stmt(lo.to(self.prev_token.span), StmtKind::Expr(expr)))
155 } else {
156 Ok(stmt)
157 }
dfeec247
XL
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.
74b04a01 162 fn parse_stmt_mac(&mut self, lo: Span, attrs: AttrVec, path: ast::Path) -> PResult<'a, Stmt> {
dfeec247
XL
163 let args = self.parse_mac_args()?;
164 let delim = args.delim();
74b04a01 165 let hi = self.prev_token.span;
dfeec247
XL
166
167 let style =
168 if delim == token::Brace { MacStmtStyle::Braces } else { MacStmtStyle::NoBraces };
169
ba9703b0 170 let mac = MacCall { path, args, prior_type_ascription: self.last_type_ascription };
dfeec247 171
c295e0f8
XL
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 };
74b04a01 186 Ok(self.mk_stmt(lo.to(hi), kind))
dfeec247 187 }
416331ca 188
dfeec247
XL
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]) {
74b04a01
XL
192 if let [.., last] = attrs {
193 if last.is_doc_comment() {
17df50a5 194 self.span_err(last.span, Error::UselessDocComment).emit();
dfeec247 195 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
74b04a01 196 self.struct_span_err(last.span, "expected statement after outer attribute").emit();
416331ca 197 }
dfeec247
XL
198 }
199 }
200
dfeec247
XL
201 fn recover_stmt_local(
202 &mut self,
203 lo: Span,
cdc7bbd5 204 attrs: AttrWrapper,
dfeec247
XL
205 msg: &str,
206 sugg: &str,
74b04a01 207 ) -> PResult<'a, Stmt> {
5869c6ff 208 let stmt = self.recover_local_after_let(lo, attrs)?;
dfeec247
XL
209 self.struct_span_err(lo, "invalid variable declaration")
210 .span_suggestion(lo, msg, sugg.to_string(), Applicability::MachineApplicable)
211 .emit();
74b04a01 212 Ok(stmt)
dfeec247
XL
213 }
214
5869c6ff
XL
215 fn parse_local_mk(
216 &mut self,
217 lo: Span,
6a06907d 218 attrs: AttrWrapper,
5869c6ff
XL
219 capture_semi: bool,
220 force_collect: ForceCollect,
221 ) -> PResult<'a, Stmt> {
6a06907d 222 self.collect_tokens_trailing_token(attrs, force_collect, |this, attrs| {
5869c6ff
XL
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
cdc7bbd5
XL
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 })
416331ca
XL
243 }
244
245 /// Parses a local variable declaration.
dfeec247 246 fn parse_local(&mut self, attrs: AttrVec) -> PResult<'a, P<Local>> {
74b04a01 247 let lo = self.prev_token.span;
cdc7bbd5 248 let (pat, colon) = self.parse_pat_before_ty(None, RecoverComma::Yes, "`let` bindings")?;
416331ca 249
6a06907d 250 let (err, ty) = if colon {
416331ca
XL
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();
74b04a01 254 let colon_sp = self.prev_token.span;
416331ca
XL
255 match self.parse_ty() {
256 Ok(ty) => (None, Some(ty)),
257 Err(mut err) => {
ba9703b0
XL
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 }
3dfed10e
XL
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)
416331ca
XL
271 }
272 }
273 } else {
274 (None, None)
275 };
276 let init = match (self.parse_initializer(err.is_some()), err) {
dfeec247
XL
277 (Ok(init), None) => {
278 // init parsed, ty parsed
416331ca
XL
279 init
280 }
dfeec247
XL
281 (Ok(init), Some((_, colon_sp, mut err))) => {
282 // init parsed, ty error
416331ca
XL
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",
e74abb32 288 " =".to_string(),
dfeec247 289 Applicability::MachineApplicable,
416331ca
XL
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 }
ee023bcb 297 (Err(init_err), Some((snapshot, _, ty_err))) => {
dfeec247 298 // init error, ty error
416331ca
XL
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>;
f9f354fc 303 *self = snapshot;
416331ca
XL
304 return Err(ty_err);
305 }
dfeec247
XL
306 (Err(err), None) => {
307 // init error, ty parsed
416331ca
XL
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 };
94222f64
XL
313 let kind = match init {
314 None => LocalKind::Decl,
315 Some(init) => {
316 if self.eat_keyword(kw::Else) {
3c0e092e
XL
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 }
94222f64
XL
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 };
74b04a01 332 let hi = if self.token == token::Semi { self.token.span } else { self.prev_token.span };
94222f64
XL
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(
3c0e092e 351 "wrap the expression in parentheses",
94222f64
XL
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(
3c0e092e 372 "try wrapping the expression in parentheses",
94222f64
XL
373 suggs,
374 Applicability::MachineApplicable,
375 )
376 .emit();
377 }
416331ca
XL
378 }
379
6a06907d 380 /// Parses the RHS of a local variable declaration (e.g., `= 14;`).
f035d41b
XL
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 )
6a06907d 395 .help("if you meant to overwrite, remove the `let` binding")
f035d41b
XL
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 })
416331ca
XL
404 }
405
416331ca 406 /// Parses a block. No inner attributes are allowed.
3dfed10e 407 pub(super) fn parse_block(&mut self) -> PResult<'a, P<Block>> {
ba9703b0
XL
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);
dfeec247 411 }
ba9703b0 412 Ok(block)
dfeec247
XL
413 }
414
ee023bcb
FG
415 fn error_block_no_opening_brace_msg(
416 &mut self,
417 msg: &str,
418 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
dfeec247 419 let sp = self.token.span;
3c0e092e 420 let mut e = self.struct_span_err(sp, msg);
dfeec247
XL
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.
5869c6ff 429 match self.parse_stmt_without_recovery(false, ForceCollect::No) {
ba9703b0
XL
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(_))
dfeec247 433 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
ba9703b0 434 || do_not_suggest_help => {}
ee023bcb
FG
435 // Do not suggest `if foo println!("") {;}` (as would be seen in test for #46836).
436 Ok(Some(Stmt { kind: StmtKind::Empty, .. })) => {}
ba9703b0
XL
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) {
dfeec247 440 // Expand the span to include the semicolon.
74b04a01 441 stmt.span.with_hi(self.prev_token.span.hi())
dfeec247
XL
442 } else {
443 stmt.span
444 };
ee023bcb
FG
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 );
416331ca 454 }
ee023bcb 455 Err(e) => {
dfeec247
XL
456 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
457 e.cancel();
458 }
459 _ => {}
416331ca 460 }
dfeec247 461 e.span_label(sp, "expected `{`");
3c0e092e
XL
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))
416331ca
XL
469 }
470
471 /// Parses a block. Inner attributes are allowed.
e74abb32 472 pub(super) fn parse_inner_attrs_and_block(
dfeec247 473 &mut self,
ba9703b0
XL
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,
e74abb32 483 ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
416331ca
XL
484 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
485
ee023bcb 486 self.maybe_recover_unexpected_block_label();
ba9703b0
XL
487 if !self.eat(&token::OpenDelim(token::Brace)) {
488 return self.error_block_no_opening_brace();
489 }
490
29967ef6 491 let attrs = self.parse_inner_attributes()?;
ee023bcb
FG
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)?,
29967ef6
XL
495 };
496 Ok((attrs, tail))
416331ca
XL
497 }
498
499 /// Parses the rest of a block expression or function body.
500 /// Precondition: already parsed the '{'.
29967ef6
XL
501 crate fn parse_block_tail(
502 &mut self,
503 lo: Span,
504 s: BlockCheckMode,
505 recover: AttemptLocalParseRecovery,
506 ) -> PResult<'a, P<Block>> {
416331ca
XL
507 let mut stmts = vec![];
508 while !self.eat(&token::CloseDelim(token::Brace)) {
509 if self.token == token::Eof {
510 break;
511 }
29967ef6
XL
512 let stmt = match self.parse_full_stmt(recover) {
513 Err(mut err) if recover.yes() => {
60c5eb7d 514 self.maybe_annotate_with_ascription(&mut err, false);
416331ca
XL
515 err.emit();
516 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
dfeec247 517 Some(self.mk_stmt_err(self.token.span))
416331ca
XL
518 }
519 Ok(stmt) => stmt,
29967ef6 520 Err(err) => return Err(err),
416331ca
XL
521 };
522 if let Some(stmt) = stmt {
523 stmts.push(stmt);
524 } else {
525 // Found only `;` or `}`.
526 continue;
527 };
528 }
74b04a01 529 Ok(self.mk_block(stmts, s, lo.to(self.prev_token.span)))
416331ca
XL
530 }
531
532 /// Parses a statement, including the trailing semicolon.
29967ef6
XL
533 pub fn parse_full_stmt(
534 &mut self,
535 recover: AttemptLocalParseRecovery,
536 ) -> PResult<'a, Option<Stmt>> {
e1599b0c 537 // Skip looking for a trailing semicolon when we have an interpolated statement.
416331ca
XL
538 maybe_whole!(self, NtStmt, |x| Some(x));
539
ee023bcb
FG
540 let Some(mut stmt) = self.parse_stmt_without_recovery(true, ForceCollect::No)? else {
541 return Ok(None);
416331ca
XL
542 };
543
e74abb32
XL
544 let mut eat_semi = true;
545 match stmt.kind {
74b04a01 546 // Expression without semicolon.
1b1a35ee 547 StmtKind::Expr(ref mut expr)
74b04a01
XL
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 }
416331ca 570 }
1b1a35ee
XL
571 if let Err(mut e) =
572 self.check_mistyped_turbofish_with_multiple_type_params(e, expr)
573 {
29967ef6
XL
574 if recover.no() {
575 return Err(e);
576 }
1b1a35ee
XL
577 e.emit();
578 self.recover_stmt();
579 }
74b04a01
XL
580 // Don't complain about type errors in body tail after parse error (#57383).
581 let sp = expr.span.to(self.prev_token.span);
1b1a35ee 582 *expr = self.mk_expr_err(sp);
416331ca
XL
583 }
584 }
fc512014 585 StmtKind::Expr(_) | StmtKind::MacCall(_) => {}
94222f64
XL
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, _) => {
ee023bcb
FG
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),
1b1a35ee 595 }
74b04a01 596 eat_semi = false;
416331ca 597 }
94222f64 598 StmtKind::Empty | StmtKind::Item(_) | StmtKind::Local(_) | StmtKind::Semi(_) => eat_semi = false,
416331ca
XL
599 }
600
e74abb32 601 if eat_semi && self.eat(&token::Semi) {
416331ca
XL
602 stmt = stmt.add_trailing_semicolon();
603 }
74b04a01 604 stmt.span = stmt.span.to(self.prev_token.span);
416331ca
XL
605 Ok(Some(stmt))
606 }
607
dfeec247 608 pub(super) fn mk_block(&self, stmts: Vec<Stmt>, rules: BlockCheckMode, span: Span) -> P<Block> {
94222f64
XL
609 P(Block {
610 stmts,
611 id: DUMMY_NODE_ID,
612 rules,
613 span,
614 tokens: None,
615 could_be_bare_literal: false,
616 })
dfeec247
XL
617 }
618
619 pub(super) fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt {
fc512014 620 Stmt { id: DUMMY_NODE_ID, kind, span }
dfeec247
XL
621 }
622
29967ef6 623 pub(super) fn mk_stmt_err(&self, span: Span) -> Stmt {
dfeec247
XL
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)
416331ca
XL
629 }
630}