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;
8 AttrWrapper, BlockMode, FnParseMode, ForceCollect, Parser, Restrictions, SemiColonMode,
11 AssignmentElseNotAllowed, CompoundAssignmentExpressionInLet, ConstLetMutuallyExclusive,
12 DocCommentDoesNotDocumentAnything, ExpectedStatementAfterOuterAttr, InvalidCurlyInLetElse,
13 InvalidExpressionInLetElse, InvalidVariableDeclaration, InvalidVariableDeclarationSub,
14 WrapExpressionInParentheses,
16 use crate::maybe_whole;
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};
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| {
38 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
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(
48 force_collect: ForceCollect,
49 ) -> PResult<'a, Option<Stmt>> {
50 let attrs = self.parse_outer_attributes()?;
51 let lo = self.token.span;
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();
58 stmt.visit_attrs(|stmt_attrs| {
59 attrs.prepend_to_nt_inner(stmt_attrs);
61 return Ok(Some(stmt.into_inner()));
64 if self.token.is_keyword(kw::Mut) && self.is_keyword_ahead(1, &[kw::Let]) {
66 let mut_let_span = lo.to(self.token.span);
67 self.sess.emit_err(InvalidVariableDeclaration {
69 sub: InvalidVariableDeclarationSub::SwitchMutLetOrder(mut_let_span),
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) {
76 self.recover_stmt_local(lo, attrs, InvalidVariableDeclarationSub::MissingLet)?
77 } else if self.is_kw_followed_by_ident(kw::Auto) {
78 self.bump(); // `auto`
79 self.recover_stmt_local(lo, attrs, InvalidVariableDeclarationSub::UseLetNotAuto)?
80 } else if self.is_kw_followed_by_ident(sym::var) {
82 self.recover_stmt_local(lo, attrs, InvalidVariableDeclarationSub::UseLetNotVar)?
83 } else if self.check_path() && !self.token.is_qpath_start() && !self.is_path_start_item() {
84 // We have avoided contextual keywords like `union`, items with `crate` visibility,
85 // or `auto trait` items. We aim to parse an arbitrary path `a::b` but not something
86 // that starts like a path (1 token), but it fact not a path.
87 // Also, we avoid stealing syntax from `parse_item_`.
88 if force_collect == ForceCollect::Yes {
89 self.collect_tokens_no_attrs(|this| this.parse_stmt_path_start(lo, attrs))
91 self.parse_stmt_path_start(lo, attrs)
93 } else if let Some(item) = self.parse_item_common(
97 FnParseMode { req_name: |_| true, req_body: true },
100 // FIXME: Bad copy of attrs
101 self.mk_stmt(lo.to(item.span), StmtKind::Item(P(item)))
102 } else if self.eat(&token::Semi) {
103 // Do not attempt to parse an expression if we're done here.
104 self.error_outer_attrs(attrs);
105 self.mk_stmt(lo, StmtKind::Empty)
106 } else if self.token != token::CloseDelim(Delimiter::Brace) {
107 // Remainder are line-expr stmts.
108 let e = if force_collect == ForceCollect::Yes {
109 self.collect_tokens_no_attrs(|this| {
110 this.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs))
113 self.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs))
115 if matches!(e.kind, ExprKind::Assign(..)) && self.eat_keyword(kw::Else) {
116 let bl = self.parse_block()?;
117 // Destructuring assignment ... else.
118 // This is not allowed, but point it out in a nice way.
119 self.sess.emit_err(AssignmentElseNotAllowed { span: e.span.to(bl.span) });
121 self.mk_stmt(lo.to(e.span), StmtKind::Expr(e))
123 self.error_outer_attrs(attrs);
128 fn parse_stmt_path_start(&mut self, lo: Span, attrs: AttrWrapper) -> PResult<'a, Stmt> {
129 let stmt = self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
130 let path = this.parse_path(PathStyle::Expr)?;
132 if this.eat(&token::Not) {
133 let stmt_mac = this.parse_stmt_mac(lo, attrs, path)?;
134 if this.token == token::Semi {
135 return Ok((stmt_mac, TrailingToken::Semi));
137 return Ok((stmt_mac, TrailingToken::None));
141 let expr = if this.eat(&token::OpenDelim(Delimiter::Brace)) {
142 this.parse_struct_expr(None, path, true)?
144 let hi = this.prev_token.span;
145 this.mk_expr(lo.to(hi), ExprKind::Path(None, path))
148 let expr = this.with_res(Restrictions::STMT_EXPR, |this| {
149 this.parse_dot_or_call_expr_with(expr, lo, attrs)
151 // `DUMMY_SP` will get overwritten later in this function
152 Ok((this.mk_stmt(rustc_span::DUMMY_SP, StmtKind::Expr(expr)), TrailingToken::None))
155 if let StmtKind::Expr(expr) = stmt.kind {
156 // Perform this outside of the `collect_tokens_trailing_token` closure,
157 // since our outer attributes do not apply to this part of the expression
158 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
159 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
161 Ok(self.mk_stmt(lo.to(self.prev_token.span), StmtKind::Expr(expr)))
167 /// Parses a statement macro `mac!(args)` provided a `path` representing `mac`.
168 /// At this point, the `!` token after the path has already been eaten.
169 fn parse_stmt_mac(&mut self, lo: Span, attrs: AttrVec, path: ast::Path) -> PResult<'a, Stmt> {
170 let args = self.parse_mac_args()?;
171 let delim = args.delim();
172 let hi = self.prev_token.span;
174 let style = match delim {
175 Some(Delimiter::Brace) => MacStmtStyle::Braces,
176 Some(_) => MacStmtStyle::NoBraces,
177 None => unreachable!(),
180 let mac = P(MacCall { path, args, prior_type_ascription: self.last_type_ascription });
182 let kind = if (style == MacStmtStyle::Braces
183 && self.token != token::Dot
184 && self.token != token::Question)
185 || self.token == token::Semi
186 || self.token == token::Eof
188 StmtKind::MacCall(P(MacCallStmt { mac, style, attrs, tokens: None }))
190 // Since none of the above applied, this is an expression statement macro.
191 let e = self.mk_expr(lo.to(hi), ExprKind::MacCall(mac));
192 let e = self.maybe_recover_from_bad_qpath(e)?;
193 let e = self.parse_dot_or_call_expr_with(e, lo, attrs)?;
194 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
197 Ok(self.mk_stmt(lo.to(hi), kind))
200 /// Error on outer attributes in this context.
201 /// Also error if the previous token was a doc comment.
202 fn error_outer_attrs(&self, attrs: AttrWrapper) {
204 && let attrs = attrs.take_for_recovery(self.sess)
205 && let attrs @ [.., last] = &*attrs {
206 if last.is_doc_comment() {
207 self.sess.emit_err(DocCommentDoesNotDocumentAnything {
211 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
212 self.sess.emit_err(ExpectedStatementAfterOuterAttr { span: last.span });
217 fn recover_stmt_local(
221 subdiagnostic: fn(Span) -> InvalidVariableDeclarationSub,
222 ) -> PResult<'a, Stmt> {
223 let stmt = self.recover_local_after_let(lo, attrs)?;
224 self.sess.emit_err(InvalidVariableDeclaration { span: lo, sub: subdiagnostic(lo) });
233 force_collect: ForceCollect,
234 ) -> PResult<'a, Stmt> {
235 self.collect_tokens_trailing_token(attrs, force_collect, |this, attrs| {
236 this.expect_keyword(kw::Let)?;
237 let local = this.parse_local(attrs)?;
238 let trailing = if capture_semi && this.token.kind == token::Semi {
243 Ok((this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Local(local)), trailing))
247 fn recover_local_after_let(&mut self, lo: Span, attrs: AttrWrapper) -> PResult<'a, Stmt> {
248 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
249 let local = this.parse_local(attrs)?;
250 // FIXME - maybe capture semicolon in recovery?
252 this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Local(local)),
258 /// Parses a local variable declaration.
259 fn parse_local(&mut self, attrs: AttrVec) -> PResult<'a, P<Local>> {
260 let lo = self.prev_token.span;
262 if self.token.is_keyword(kw::Const) && self.look_ahead(1, |t| t.is_ident()) {
263 self.sess.emit_err(ConstLetMutuallyExclusive { span: lo.to(self.token.span) });
267 let (pat, colon) = self.parse_pat_before_ty(None, RecoverComma::Yes, "`let` bindings")?;
269 let (err, ty) = if colon {
270 // Save the state of the parser before parsing type normally, in case there is a `:`
271 // instead of an `=` typo.
272 let parser_snapshot_before_type = self.clone();
273 let colon_sp = self.prev_token.span;
274 match self.parse_ty() {
275 Ok(ty) => (None, Some(ty)),
277 if let Ok(snip) = self.span_to_snippet(pat.span) {
278 err.span_label(pat.span, format!("while parsing the type for `{}`", snip));
280 // we use noexpect here because we don't actually expect Eq to be here
281 // but we are still checking for it in order to be able to handle it if
283 let err = if self.check_noexpect(&token::Eq) {
287 // Rewind to before attempting to parse the type and continue parsing.
288 let parser_snapshot_after_type =
289 mem::replace(self, parser_snapshot_before_type);
290 Some((parser_snapshot_after_type, colon_sp, err))
298 let init = match (self.parse_initializer(err.is_some()), err) {
299 (Ok(init), None) => {
300 // init parsed, ty parsed
303 (Ok(init), Some((_, colon_sp, mut err))) => {
304 // init parsed, ty error
305 // Could parse the type as if it were the initializer, it is likely there was a
306 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
307 err.span_suggestion_short(
309 "use `=` if you meant to assign",
311 Applicability::MachineApplicable,
314 // As this was parsed successfully, continue as if the code has been fixed for the
315 // rest of the file. It will still fail due to the emitted error, but we avoid
319 (Err(init_err), Some((snapshot, _, ty_err))) => {
320 // init error, ty error
322 // Couldn't parse the type nor the initializer, only raise the type error and
323 // return to the parser state before parsing the type as the initializer.
324 // let x: <parse_error>;
328 (Err(err), None) => {
329 // init error, ty parsed
330 // Couldn't parse the initializer and we're not attempting to recover a failed
331 // parse of the type, return the error.
335 let kind = match init {
336 None => LocalKind::Decl,
338 if self.eat_keyword(kw::Else) {
339 if self.token.is_keyword(kw::If) {
340 // `let...else if`. Emit the same error that `parse_block()` would,
341 // but explicitly point out that this pattern is not allowed.
342 let msg = "conditional `else if` is not supported for `let...else`";
343 return Err(self.error_block_no_opening_brace_msg(msg));
345 let els = self.parse_block()?;
346 self.check_let_else_init_bool_expr(&init);
347 self.check_let_else_init_trailing_brace(&init);
348 LocalKind::InitElse(init, els)
350 LocalKind::Init(init)
354 let hi = if self.token == token::Semi { self.token.span } else { self.prev_token.span };
355 Ok(P(ast::Local { ty, pat, kind, id: DUMMY_NODE_ID, span: lo.to(hi), attrs, tokens: None }))
358 fn check_let_else_init_bool_expr(&self, init: &ast::Expr) {
359 if let ast::ExprKind::Binary(op, ..) = init.kind {
361 self.sess.emit_err(InvalidExpressionInLetElse {
363 operator: op.node.to_string(),
364 sugg: WrapExpressionInParentheses {
365 left: init.span.shrink_to_lo(),
366 right: init.span.shrink_to_hi(),
373 fn check_let_else_init_trailing_brace(&self, init: &ast::Expr) {
374 if let Some(trailing) = classify::expr_trailing_brace(init) {
375 self.sess.emit_err(InvalidCurlyInLetElse {
376 span: trailing.span.with_lo(trailing.span.hi() - BytePos(1)),
377 sugg: WrapExpressionInParentheses {
378 left: trailing.span.shrink_to_lo(),
379 right: trailing.span.shrink_to_hi(),
385 /// Parses the RHS of a local variable declaration (e.g., `= 14;`).
386 fn parse_initializer(&mut self, eq_optional: bool) -> PResult<'a, Option<P<Expr>>> {
387 let eq_consumed = match self.token.kind {
388 token::BinOpEq(..) => {
389 // Recover `let x <op>= 1` as `let x = 1`
390 self.sess.emit_err(CompoundAssignmentExpressionInLet { span: self.token.span });
394 _ => self.eat(&token::Eq),
397 Ok(if eq_consumed || eq_optional { Some(self.parse_expr()?) } else { None })
400 /// Parses a block. No inner attributes are allowed.
401 pub(super) fn parse_block(&mut self) -> PResult<'a, P<Block>> {
402 let (attrs, block) = self.parse_inner_attrs_and_block()?;
403 if let [.., last] = &*attrs {
404 self.error_on_forbidden_inner_attr(
406 super::attr::InnerAttrPolicy::Forbidden(Some(
407 InnerAttrForbiddenReason::InCodeBlock,
414 fn error_block_no_opening_brace_msg(
417 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
418 let sp = self.token.span;
419 let mut e = self.struct_span_err(sp, msg);
420 let do_not_suggest_help = self.token.is_keyword(kw::In) || self.token == token::Colon;
422 // Check to see if the user has written something like
427 // which is valid in other languages, but not Rust.
428 match self.parse_stmt_without_recovery(false, ForceCollect::No) {
429 // If the next token is an open brace, e.g., we have:
431 // if expr other_expr {
432 // ^ ^ ^- lookahead(1) is a brace
433 // | |- current token is not "else"
434 // |- (statement we just parsed)
436 // the place-inside-a-block suggestion would be more likely wrong than right.
438 // FIXME(compiler-errors): this should probably parse an arbitrary expr and not
439 // just lookahead one token, so we can see if there's a brace after _that_,
440 // since we want to protect against:
441 // `if 1 1 + 1 {` being suggested as `if { 1 } 1 + 1 {`
444 if (!self.token.is_keyword(kw::Else)
445 && self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Brace)))
446 || do_not_suggest_help => {}
447 // Do not suggest `if foo println!("") {;}` (as would be seen in test for #46836).
448 Ok(Some(Stmt { kind: StmtKind::Empty, .. })) => {}
450 let stmt_own_line = self.sess.source_map().is_line_before_span_empty(sp);
451 let stmt_span = if stmt_own_line && self.eat(&token::Semi) {
452 // Expand the span to include the semicolon.
453 stmt.span.with_hi(self.prev_token.span.hi())
457 e.multipart_suggestion(
458 "try placing this code inside a block",
460 (stmt_span.shrink_to_lo(), "{ ".to_string()),
461 (stmt_span.shrink_to_hi(), " }".to_string()),
463 // Speculative; has been misleading in the past (#46836).
464 Applicability::MaybeIncorrect,
468 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
473 e.span_label(sp, "expected `{`");
477 fn error_block_no_opening_brace<T>(&mut self) -> PResult<'a, T> {
478 let tok = super::token_descr(&self.token);
479 let msg = format!("expected `{{`, found {}", tok);
480 Err(self.error_block_no_opening_brace_msg(&msg))
483 /// Parses a block. Inner attributes are allowed.
484 pub(super) fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (AttrVec, P<Block>)> {
485 self.parse_block_common(self.token.span, BlockCheckMode::Default)
488 /// Parses a block. Inner attributes are allowed.
489 pub(super) fn parse_block_common(
492 blk_mode: BlockCheckMode,
493 ) -> PResult<'a, (AttrVec, P<Block>)> {
494 maybe_whole!(self, NtBlock, |x| (AttrVec::new(), x));
496 self.maybe_recover_unexpected_block_label();
497 if !self.eat(&token::OpenDelim(Delimiter::Brace)) {
498 return self.error_block_no_opening_brace();
501 let attrs = self.parse_inner_attributes()?;
502 let tail = match self.maybe_suggest_struct_literal(lo, blk_mode) {
504 None => self.parse_block_tail(lo, blk_mode, AttemptLocalParseRecovery::Yes)?,
509 /// Parses the rest of a block expression or function body.
510 /// Precondition: already parsed the '{'.
511 pub(crate) fn parse_block_tail(
515 recover: AttemptLocalParseRecovery,
516 ) -> PResult<'a, P<Block>> {
517 let mut stmts = vec![];
518 while !self.eat(&token::CloseDelim(Delimiter::Brace)) {
519 if self.token == token::Eof {
522 let stmt = match self.parse_full_stmt(recover) {
523 Err(mut err) if recover.yes() => {
524 self.maybe_annotate_with_ascription(&mut err, false);
526 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
527 Some(self.mk_stmt_err(self.token.span))
530 Err(err) => return Err(err),
532 if let Some(stmt) = stmt {
535 // Found only `;` or `}`.
539 Ok(self.mk_block(stmts, s, lo.to(self.prev_token.span)))
542 /// Parses a statement, including the trailing semicolon.
543 pub fn parse_full_stmt(
545 recover: AttemptLocalParseRecovery,
546 ) -> PResult<'a, Option<Stmt>> {
547 // Skip looking for a trailing semicolon when we have an interpolated statement.
548 maybe_whole!(self, NtStmt, |x| Some(x.into_inner()));
550 let Some(mut stmt) = self.parse_stmt_without_recovery(true, ForceCollect::No)? else {
554 let mut eat_semi = true;
556 // Expression without semicolon.
557 StmtKind::Expr(ref mut expr)
558 if self.token != token::Eof && classify::expr_requires_semi_to_be_stmt(expr) => {
559 // Just check for errors and recover; do not eat semicolon yet.
560 // `expect_one_of` returns PResult<'a, bool /* recovered */>
561 let replace_with_err =
562 match self.expect_one_of(&[], &[token::Semi, token::CloseDelim(Delimiter::Brace)]) {
563 // Recover from parser, skip type error to avoid extra errors.
566 if let TokenKind::DocComment(..) = self.token.kind &&
567 let Ok(snippet) = self.span_to_snippet(self.token.span) {
568 let sp = self.token.span;
569 let marker = &snippet[..3];
570 let (comment_marker, doc_comment_marker) = marker.split_at(2);
573 sp.with_hi(sp.lo() + BytePos(marker.len() as u32)),
575 "add a space before `{}` to use a regular comment",
578 format!("{} {}", comment_marker, doc_comment_marker),
579 Applicability::MaybeIncorrect,
584 self.check_mistyped_turbofish_with_multiple_type_params(e, expr)
596 if replace_with_err {
597 // We already emitted an error, so don't emit another type error
598 let sp = expr.span.to(self.prev_token.span);
599 *expr = self.mk_expr_err(sp);
602 StmtKind::Expr(_) | StmtKind::MacCall(_) => {}
603 StmtKind::Local(ref mut local) if let Err(e) = self.expect_semi() => {
604 // We might be at the `,` in `let x = foo<bar, baz>;`. Try to recover.
605 match &mut local.kind {
606 LocalKind::Init(expr) | LocalKind::InitElse(expr, _) => {
607 self.check_mistyped_turbofish_with_multiple_type_params(e, expr)?;
608 // We found `foo<bar, baz>`, have we fully recovered?
611 LocalKind::Decl => return Err(e),
615 StmtKind::Empty | StmtKind::Item(_) | StmtKind::Local(_) | StmtKind::Semi(_) => eat_semi = false,
618 if eat_semi && self.eat(&token::Semi) {
619 stmt = stmt.add_trailing_semicolon();
621 stmt.span = stmt.span.to(self.prev_token.span);
625 pub(super) fn mk_block(&self, stmts: Vec<Stmt>, rules: BlockCheckMode, span: Span) -> P<Block> {
632 could_be_bare_literal: false,
636 pub(super) fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt {
637 Stmt { id: DUMMY_NODE_ID, kind, span }
640 pub(super) fn mk_stmt_err(&self, span: Span) -> Stmt {
641 self.mk_stmt(span, StmtKind::Expr(self.mk_expr_err(span)))
644 pub(super) fn mk_block_err(&self, span: Span) -> P<Block> {
645 self.mk_block(vec![self.mk_stmt_err(span)], BlockCheckMode::Default, span)