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::{AttrWrapper, BlockMode, ForceCollect, Parser, Restrictions, SemiColonMode};
8 use crate::maybe_whole;
11 use rustc_ast::ptr::P;
12 use rustc_ast::token::{self, TokenKind};
13 use rustc_ast::util::classify;
14 use rustc_ast::AstLike;
15 use rustc_ast::{AttrStyle, AttrVec, Attribute, MacCall, MacCallStmt, MacStmtStyle};
16 use rustc_ast::{Block, BlockCheckMode, Expr, ExprKind, Local, Stmt};
17 use rustc_ast::{StmtKind, DUMMY_NODE_ID};
18 use rustc_errors::{Applicability, PResult};
19 use rustc_span::source_map::{BytePos, Span};
20 use rustc_span::symbol::{kw, sym};
25 /// Parses a statement. This stops just before trailing semicolons on everything but items.
26 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
27 // Public for rustfmt usage.
28 pub fn parse_stmt(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<Stmt>> {
29 Ok(self.parse_stmt_without_recovery(false, force_collect).unwrap_or_else(|mut e| {
31 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
36 /// If `force_capture` is true, forces collection of tokens regardless of whether
37 /// or not we have attributes
38 crate fn parse_stmt_without_recovery(
41 force_collect: ForceCollect,
42 ) -> PResult<'a, Option<Stmt>> {
43 let attrs = self.parse_outer_attributes()?;
44 let lo = self.token.span;
46 // Don't use `maybe_whole` so that we have precise control
47 // over when we bump the parser
48 if let token::Interpolated(nt) = &self.token.kind {
49 if let token::NtStmt(stmt) = &**nt {
50 let mut stmt = stmt.clone();
52 stmt.visit_attrs(|stmt_attrs| {
53 attrs.prepend_to_nt_inner(stmt_attrs);
55 return Ok(Some(stmt));
59 Ok(Some(if self.token.is_keyword(kw::Let) {
60 self.parse_local_mk(lo, attrs, capture_semi, force_collect)?
61 } else if self.is_kw_followed_by_ident(kw::Mut) {
62 self.recover_stmt_local(lo, attrs, "missing keyword", "let mut")?
63 } else if self.is_kw_followed_by_ident(kw::Auto) {
64 self.bump(); // `auto`
65 let msg = "write `let` instead of `auto` to introduce a new variable";
66 self.recover_stmt_local(lo, attrs, msg, "let")?
67 } else if self.is_kw_followed_by_ident(sym::var) {
69 let msg = "write `let` instead of `var` to introduce a new variable";
70 self.recover_stmt_local(lo, attrs, msg, "let")?
71 } else if self.check_path() && !self.token.is_qpath_start() && !self.is_path_start_item() {
72 // We have avoided contextual keywords like `union`, items with `crate` visibility,
73 // or `auto trait` items. We aim to parse an arbitrary path `a::b` but not something
74 // that starts like a path (1 token), but it fact not a path.
75 // Also, we avoid stealing syntax from `parse_item_`.
76 if force_collect == ForceCollect::Yes {
77 self.collect_tokens_no_attrs(|this| this.parse_stmt_path_start(lo, attrs))
79 self.parse_stmt_path_start(lo, attrs)
81 } else if let Some(item) =
82 self.parse_item_common(attrs.clone(), false, true, |_| true, force_collect)?
84 // FIXME: Bad copy of attrs
85 self.mk_stmt(lo.to(item.span), StmtKind::Item(P(item)))
86 } else if self.eat(&token::Semi) {
87 // Do not attempt to parse an expression if we're done here.
88 self.error_outer_attrs(&attrs.take_for_recovery());
89 self.mk_stmt(lo, StmtKind::Empty)
90 } else if self.token != token::CloseDelim(token::Brace) {
91 // Remainder are line-expr stmts.
92 let e = if force_collect == ForceCollect::Yes {
93 self.collect_tokens_no_attrs(|this| {
94 this.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs))
97 self.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs))
99 self.mk_stmt(lo.to(e.span), StmtKind::Expr(e))
101 self.error_outer_attrs(&attrs.take_for_recovery());
106 fn parse_stmt_path_start(&mut self, lo: Span, attrs: AttrWrapper) -> PResult<'a, Stmt> {
107 let stmt = self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
108 let path = this.parse_path(PathStyle::Expr)?;
110 if this.eat(&token::Not) {
111 let stmt_mac = this.parse_stmt_mac(lo, attrs.into(), path)?;
112 if this.token == token::Semi {
113 return Ok((stmt_mac, TrailingToken::Semi));
115 return Ok((stmt_mac, TrailingToken::None));
119 let expr = if this.eat(&token::OpenDelim(token::Brace)) {
120 this.parse_struct_expr(None, path, AttrVec::new(), true)?
122 let hi = this.prev_token.span;
123 this.mk_expr(lo.to(hi), ExprKind::Path(None, path), AttrVec::new())
126 let expr = this.with_res(Restrictions::STMT_EXPR, |this| {
127 this.parse_dot_or_call_expr_with(expr, lo, attrs)
129 // `DUMMY_SP` will get overwritten later in this function
130 Ok((this.mk_stmt(rustc_span::DUMMY_SP, StmtKind::Expr(expr)), TrailingToken::None))
133 if let StmtKind::Expr(expr) = stmt.kind {
134 // Perform this outside of the `collect_tokens_trailing_token` closure,
135 // since our outer attributes do not apply to this part of the expression
136 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
137 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
139 Ok(self.mk_stmt(lo.to(self.prev_token.span), StmtKind::Expr(expr)))
145 /// Parses a statement macro `mac!(args)` provided a `path` representing `mac`.
146 /// At this point, the `!` token after the path has already been eaten.
147 fn parse_stmt_mac(&mut self, lo: Span, attrs: AttrVec, path: ast::Path) -> PResult<'a, Stmt> {
148 let args = self.parse_mac_args()?;
149 let delim = args.delim();
150 let hi = self.prev_token.span;
153 if delim == token::Brace { MacStmtStyle::Braces } else { MacStmtStyle::NoBraces };
155 let mac = MacCall { path, args, prior_type_ascription: self.last_type_ascription };
157 let kind = if delim == token::Brace || self.token == token::Semi || self.token == token::Eof
159 StmtKind::MacCall(P(MacCallStmt { mac, style, attrs, tokens: None }))
161 // Since none of the above applied, this is an expression statement macro.
162 let e = self.mk_expr(lo.to(hi), ExprKind::MacCall(mac), AttrVec::new());
163 let e = self.maybe_recover_from_bad_qpath(e, true)?;
164 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
165 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
168 Ok(self.mk_stmt(lo.to(hi), kind))
171 /// Error on outer attributes in this context.
172 /// Also error if the previous token was a doc comment.
173 fn error_outer_attrs(&self, attrs: &[Attribute]) {
174 if let [.., last] = attrs {
175 if last.is_doc_comment() {
176 self.span_err(last.span, Error::UselessDocComment).emit();
177 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
178 self.struct_span_err(last.span, "expected statement after outer attribute").emit();
183 fn recover_stmt_local(
189 ) -> PResult<'a, Stmt> {
190 let stmt = self.recover_local_after_let(lo, attrs)?;
191 self.struct_span_err(lo, "invalid variable declaration")
192 .span_suggestion(lo, msg, sugg.to_string(), Applicability::MachineApplicable)
202 force_collect: ForceCollect,
203 ) -> PResult<'a, Stmt> {
204 self.collect_tokens_trailing_token(attrs, force_collect, |this, attrs| {
205 this.expect_keyword(kw::Let)?;
206 let local = this.parse_local(attrs.into())?;
207 let trailing = if capture_semi && this.token.kind == token::Semi {
212 Ok((this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Local(local)), trailing))
216 fn recover_local_after_let(&mut self, lo: Span, attrs: AttrWrapper) -> PResult<'a, Stmt> {
217 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
218 let local = this.parse_local(attrs.into())?;
219 // FIXME - maybe capture semicolon in recovery?
221 this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Local(local)),
227 /// Parses a local variable declaration.
228 fn parse_local(&mut self, attrs: AttrVec) -> PResult<'a, P<Local>> {
229 let lo = self.prev_token.span;
230 let (pat, colon) = self.parse_pat_before_ty(None, RecoverComma::Yes, "`let` bindings")?;
232 let (err, ty) = if colon {
233 // Save the state of the parser before parsing type normally, in case there is a `:`
234 // instead of an `=` typo.
235 let parser_snapshot_before_type = self.clone();
236 let colon_sp = self.prev_token.span;
237 match self.parse_ty() {
238 Ok(ty) => (None, Some(ty)),
240 if let Ok(snip) = self.span_to_snippet(pat.span) {
241 err.span_label(pat.span, format!("while parsing the type for `{}`", snip));
243 let err = if self.check(&token::Eq) {
247 // Rewind to before attempting to parse the type and continue parsing.
248 let parser_snapshot_after_type =
249 mem::replace(self, parser_snapshot_before_type);
250 Some((parser_snapshot_after_type, colon_sp, err))
258 let init = match (self.parse_initializer(err.is_some()), err) {
259 (Ok(init), None) => {
260 // init parsed, ty parsed
263 (Ok(init), Some((_, colon_sp, mut err))) => {
264 // init parsed, ty error
265 // Could parse the type as if it were the initializer, it is likely there was a
266 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
267 err.span_suggestion_short(
269 "use `=` if you meant to assign",
271 Applicability::MachineApplicable,
274 // As this was parsed successfully, continue as if the code has been fixed for the
275 // rest of the file. It will still fail due to the emitted error, but we avoid
279 (Err(mut init_err), Some((snapshot, _, ty_err))) => {
280 // init error, ty error
282 // Couldn't parse the type nor the initializer, only raise the type error and
283 // return to the parser state before parsing the type as the initializer.
284 // let x: <parse_error>;
288 (Err(err), None) => {
289 // init error, ty parsed
290 // Couldn't parse the initializer and we're not attempting to recover a failed
291 // parse of the type, return the error.
295 let hi = if self.token == token::Semi { self.token.span } else { self.prev_token.span };
296 Ok(P(ast::Local { ty, pat, init, id: DUMMY_NODE_ID, span: lo.to(hi), attrs, tokens: None }))
299 /// Parses the RHS of a local variable declaration (e.g., `= 14;`).
300 fn parse_initializer(&mut self, eq_optional: bool) -> PResult<'a, Option<P<Expr>>> {
301 let eq_consumed = match self.token.kind {
302 token::BinOpEq(..) => {
303 // Recover `let x <op>= 1` as `let x = 1`
304 self.struct_span_err(
306 "can't reassign to an uninitialized variable",
308 .span_suggestion_short(
310 "initialize the variable",
312 Applicability::MaybeIncorrect,
314 .help("if you meant to overwrite, remove the `let` binding")
319 _ => self.eat(&token::Eq),
322 Ok(if eq_consumed || eq_optional { Some(self.parse_expr()?) } else { None })
325 /// Parses a block. No inner attributes are allowed.
326 pub(super) fn parse_block(&mut self) -> PResult<'a, P<Block>> {
327 let (attrs, block) = self.parse_inner_attrs_and_block()?;
328 if let [.., last] = &*attrs {
329 self.error_on_forbidden_inner_attr(last.span, DEFAULT_INNER_ATTR_FORBIDDEN);
334 fn error_block_no_opening_brace<T>(&mut self) -> PResult<'a, T> {
335 let sp = self.token.span;
336 let tok = super::token_descr(&self.token);
337 let mut e = self.struct_span_err(sp, &format!("expected `{{`, found {}", tok));
338 let do_not_suggest_help = self.token.is_keyword(kw::In) || self.token == token::Colon;
340 // Check to see if the user has written something like
345 // which is valid in other languages, but not Rust.
346 match self.parse_stmt_without_recovery(false, ForceCollect::No) {
347 // If the next token is an open brace (e.g., `if a b {`), the place-
348 // inside-a-block suggestion would be more likely wrong than right.
350 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
351 || do_not_suggest_help => {}
353 let stmt_own_line = self.sess.source_map().is_line_before_span_empty(sp);
354 let stmt_span = if stmt_own_line && self.eat(&token::Semi) {
355 // Expand the span to include the semicolon.
356 stmt.span.with_hi(self.prev_token.span.hi())
360 if let Ok(snippet) = self.span_to_snippet(stmt_span) {
363 "try placing this code inside a block",
364 format!("{{ {} }}", snippet),
365 // Speculative; has been misleading in the past (#46836).
366 Applicability::MaybeIncorrect,
371 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
376 e.span_label(sp, "expected `{`");
380 /// Parses a block. Inner attributes are allowed.
381 pub(super) fn parse_inner_attrs_and_block(
383 ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
384 self.parse_block_common(self.token.span, BlockCheckMode::Default)
387 /// Parses a block. Inner attributes are allowed.
388 pub(super) fn parse_block_common(
391 blk_mode: BlockCheckMode,
392 ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
393 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
395 if !self.eat(&token::OpenDelim(token::Brace)) {
396 return self.error_block_no_opening_brace();
399 let attrs = self.parse_inner_attributes()?;
400 let tail = if let Some(tail) = self.maybe_suggest_struct_literal(lo, blk_mode) {
403 self.parse_block_tail(lo, blk_mode, AttemptLocalParseRecovery::Yes)?
408 /// Parses the rest of a block expression or function body.
409 /// Precondition: already parsed the '{'.
410 crate fn parse_block_tail(
414 recover: AttemptLocalParseRecovery,
415 ) -> PResult<'a, P<Block>> {
416 let mut stmts = vec![];
417 while !self.eat(&token::CloseDelim(token::Brace)) {
418 if self.token == token::Eof {
421 let stmt = match self.parse_full_stmt(recover) {
422 Err(mut err) if recover.yes() => {
423 self.maybe_annotate_with_ascription(&mut err, false);
425 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
426 Some(self.mk_stmt_err(self.token.span))
429 Err(err) => return Err(err),
431 if let Some(stmt) = stmt {
434 // Found only `;` or `}`.
438 Ok(self.mk_block(stmts, s, lo.to(self.prev_token.span)))
441 /// Parses a statement, including the trailing semicolon.
442 pub fn parse_full_stmt(
444 recover: AttemptLocalParseRecovery,
445 ) -> PResult<'a, Option<Stmt>> {
446 // Skip looking for a trailing semicolon when we have an interpolated statement.
447 maybe_whole!(self, NtStmt, |x| Some(x));
449 let mut stmt = match self.parse_stmt_without_recovery(true, ForceCollect::No)? {
451 None => return Ok(None),
454 let mut eat_semi = true;
456 // Expression without semicolon.
457 StmtKind::Expr(ref mut expr)
458 if self.token != token::Eof && classify::expr_requires_semi_to_be_stmt(expr) =>
460 // Just check for errors and recover; do not eat semicolon yet.
462 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
464 if let TokenKind::DocComment(..) = self.token.kind {
465 if let Ok(snippet) = self.span_to_snippet(self.token.span) {
466 let sp = self.token.span;
467 let marker = &snippet[..3];
468 let (comment_marker, doc_comment_marker) = marker.split_at(2);
471 sp.with_hi(sp.lo() + BytePos(marker.len() as u32)),
473 "add a space before `{}` to use a regular comment",
476 format!("{} {}", comment_marker, doc_comment_marker),
477 Applicability::MaybeIncorrect,
482 self.check_mistyped_turbofish_with_multiple_type_params(e, expr)
490 // Don't complain about type errors in body tail after parse error (#57383).
491 let sp = expr.span.to(self.prev_token.span);
492 *expr = self.mk_expr_err(sp);
495 StmtKind::Expr(_) | StmtKind::MacCall(_) => {}
496 StmtKind::Local(ref mut local) => {
497 if let Err(e) = self.expect_semi() {
498 // We might be at the `,` in `let x = foo<bar, baz>;`. Try to recover.
499 match &mut local.init {
500 Some(ref mut expr) => {
501 self.check_mistyped_turbofish_with_multiple_type_params(e, expr)?;
502 // We found `foo<bar, baz>`, have we fully recovered?
505 None => return Err(e),
510 StmtKind::Empty | StmtKind::Item(_) | StmtKind::Semi(_) => eat_semi = false,
513 if eat_semi && self.eat(&token::Semi) {
514 stmt = stmt.add_trailing_semicolon();
516 stmt.span = stmt.span.to(self.prev_token.span);
520 pub(super) fn mk_block(&self, stmts: Vec<Stmt>, rules: BlockCheckMode, span: Span) -> P<Block> {
521 P(Block { stmts, id: DUMMY_NODE_ID, rules, span, tokens: None })
524 pub(super) fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt {
525 Stmt { id: DUMMY_NODE_ID, kind, span }
528 pub(super) fn mk_stmt_err(&self, span: Span) -> Stmt {
529 self.mk_stmt(span, StmtKind::Expr(self.mk_expr_err(span)))
532 pub(super) fn mk_block_err(&self, span: Span) -> P<Block> {
533 self.mk_block(vec![self.mk_stmt_err(span)], BlockCheckMode::Default, span)