1 use super::attr::DEFAULT_INNER_ATTR_FORBIDDEN;
2 use super::diagnostics::{AttemptLocalParseRecovery, Error};
3 use super::expr::LhsExpr;
4 use super::pat::GateOr;
5 use super::path::PathStyle;
6 use super::{BlockMode, Parser, Restrictions, SemiColonMode};
7 use crate::maybe_whole;
10 use rustc_ast::attr::HasAttrs;
11 use rustc_ast::ptr::P;
12 use rustc_ast::token::{self, TokenKind};
13 use rustc_ast::tokenstream::LazyTokenStream;
14 use rustc_ast::util::classify;
15 use rustc_ast::{AttrStyle, AttrVec, Attribute, MacCall, MacCallStmt, MacStmtStyle};
16 use rustc_ast::{Block, BlockCheckMode, Expr, ExprKind, Local, Stmt, StmtKind, DUMMY_NODE_ID};
17 use rustc_errors::{Applicability, PResult};
18 use rustc_span::source_map::{BytePos, Span};
19 use rustc_span::symbol::{kw, sym};
24 /// Parses a statement. This stops just before trailing semicolons on everything but items.
25 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
26 // Public for rustfmt usage.
27 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
28 Ok(self.parse_stmt_without_recovery().unwrap_or_else(|mut e| {
30 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
35 fn parse_stmt_without_recovery(&mut self) -> PResult<'a, Option<Stmt>> {
36 let mut attrs = self.parse_outer_attributes()?;
37 let has_attrs = !attrs.is_empty();
38 let lo = self.token.span;
40 maybe_whole!(self, NtStmt, |stmt| {
42 stmt.visit_attrs(|stmt_attrs| {
43 mem::swap(stmt_attrs, &mut attrs);
44 stmt_attrs.extend(attrs);
49 let parse_stmt_inner = |this: &mut Self| {
50 let stmt = if this.eat_keyword(kw::Let) {
51 this.parse_local_mk(lo, attrs.into())?
52 } else if this.is_kw_followed_by_ident(kw::Mut) {
53 this.recover_stmt_local(lo, attrs.into(), "missing keyword", "let mut")?
54 } else if this.is_kw_followed_by_ident(kw::Auto) {
55 this.bump(); // `auto`
56 let msg = "write `let` instead of `auto` to introduce a new variable";
57 this.recover_stmt_local(lo, attrs.into(), msg, "let")?
58 } else if this.is_kw_followed_by_ident(sym::var) {
60 let msg = "write `let` instead of `var` to introduce a new variable";
61 this.recover_stmt_local(lo, attrs.into(), msg, "let")?
62 } else if this.check_path()
63 && !this.token.is_qpath_start()
64 && !this.is_path_start_item()
66 // We have avoided contextual keywords like `union`, items with `crate` visibility,
67 // or `auto trait` items. We aim to parse an arbitrary path `a::b` but not something
68 // that starts like a path (1 token), but it fact not a path.
69 // Also, we avoid stealing syntax from `parse_item_`.
70 this.parse_stmt_path_start(lo, attrs)?
71 } else if let Some(item) =
72 this.parse_item_common(attrs.clone(), false, true, |_| true)?
74 // FIXME: Bad copy of attrs
75 this.mk_stmt(lo.to(item.span), StmtKind::Item(P(item)))
76 } else if this.eat(&token::Semi) {
77 // Do not attempt to parse an expression if we're done here.
78 this.error_outer_attrs(&attrs);
79 this.mk_stmt(lo, StmtKind::Empty)
80 } else if this.token != token::CloseDelim(token::Brace) {
81 // Remainder are line-expr stmts.
82 let e = this.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs.into()))?;
83 this.mk_stmt(lo.to(e.span), StmtKind::Expr(e))
85 this.error_outer_attrs(&attrs);
91 let stmt = if has_attrs {
92 let (mut stmt, tokens) = self.collect_tokens(parse_stmt_inner)?;
93 if let Some(stmt) = &mut stmt {
94 // If we already have tokens (e.g. due to encounting an `NtStmt`),
96 if stmt.tokens().is_none() {
97 stmt.set_tokens(tokens);
102 parse_stmt_inner(self)?
107 fn parse_stmt_path_start(&mut self, lo: Span, attrs: Vec<Attribute>) -> PResult<'a, Stmt> {
108 let path = self.parse_path(PathStyle::Expr)?;
110 if self.eat(&token::Not) {
111 return self.parse_stmt_mac(lo, attrs.into(), path);
114 let expr = if self.eat(&token::OpenDelim(token::Brace)) {
115 self.parse_struct_expr(path, AttrVec::new(), true)?
117 let hi = self.prev_token.span;
118 self.mk_expr(lo.to(hi), ExprKind::Path(None, path), AttrVec::new())
121 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
122 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
123 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
125 Ok(self.mk_stmt(lo.to(self.prev_token.span), StmtKind::Expr(expr)))
128 /// Parses a statement macro `mac!(args)` provided a `path` representing `mac`.
129 /// At this point, the `!` token after the path has already been eaten.
130 fn parse_stmt_mac(&mut self, lo: Span, attrs: AttrVec, path: ast::Path) -> PResult<'a, Stmt> {
131 let args = self.parse_mac_args()?;
132 let delim = args.delim();
133 let hi = self.prev_token.span;
136 if delim == token::Brace { MacStmtStyle::Braces } else { MacStmtStyle::NoBraces };
138 let mac = MacCall { path, args, prior_type_ascription: self.last_type_ascription };
140 let kind = if delim == token::Brace || self.token == token::Semi || self.token == token::Eof
142 StmtKind::MacCall(P(MacCallStmt { mac, style, attrs, tokens: None }))
144 // Since none of the above applied, this is an expression statement macro.
145 let e = self.mk_expr(lo.to(hi), ExprKind::MacCall(mac), AttrVec::new());
146 let e = self.maybe_recover_from_bad_qpath(e, true)?;
147 let e = self.parse_dot_or_call_expr_with(e, lo, attrs)?;
148 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
151 Ok(self.mk_stmt(lo.to(hi), kind))
154 /// Error on outer attributes in this context.
155 /// Also error if the previous token was a doc comment.
156 fn error_outer_attrs(&self, attrs: &[Attribute]) {
157 if let [.., last] = attrs {
158 if last.is_doc_comment() {
159 self.span_fatal_err(last.span, Error::UselessDocComment).emit();
160 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
161 self.struct_span_err(last.span, "expected statement after outer attribute").emit();
166 fn recover_stmt_local(
172 ) -> PResult<'a, Stmt> {
173 let stmt = self.parse_local_mk(lo, attrs)?;
174 self.struct_span_err(lo, "invalid variable declaration")
175 .span_suggestion(lo, msg, sugg.to_string(), Applicability::MachineApplicable)
180 fn parse_local_mk(&mut self, lo: Span, attrs: AttrVec) -> PResult<'a, Stmt> {
181 let local = self.parse_local(attrs)?;
182 Ok(self.mk_stmt(lo.to(self.prev_token.span), StmtKind::Local(local)))
185 /// Parses a local variable declaration.
186 fn parse_local(&mut self, attrs: AttrVec) -> PResult<'a, P<Local>> {
187 let lo = self.prev_token.span;
188 let pat = self.parse_top_pat(GateOr::Yes)?;
190 let (err, ty) = if self.eat(&token::Colon) {
191 // Save the state of the parser before parsing type normally, in case there is a `:`
192 // instead of an `=` typo.
193 let parser_snapshot_before_type = self.clone();
194 let colon_sp = self.prev_token.span;
195 match self.parse_ty() {
196 Ok(ty) => (None, Some(ty)),
198 if let Ok(snip) = self.span_to_snippet(pat.span) {
199 err.span_label(pat.span, format!("while parsing the type for `{}`", snip));
201 let err = if self.check(&token::Eq) {
205 // Rewind to before attempting to parse the type and continue parsing.
206 let parser_snapshot_after_type =
207 mem::replace(self, parser_snapshot_before_type);
208 Some((parser_snapshot_after_type, colon_sp, err))
216 let init = match (self.parse_initializer(err.is_some()), err) {
217 (Ok(init), None) => {
218 // init parsed, ty parsed
221 (Ok(init), Some((_, colon_sp, mut err))) => {
222 // init parsed, ty error
223 // Could parse the type as if it were the initializer, it is likely there was a
224 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
225 err.span_suggestion_short(
227 "use `=` if you meant to assign",
229 Applicability::MachineApplicable,
232 // As this was parsed successfully, continue as if the code has been fixed for the
233 // rest of the file. It will still fail due to the emitted error, but we avoid
237 (Err(mut init_err), Some((snapshot, _, ty_err))) => {
238 // init error, ty error
240 // Couldn't parse the type nor the initializer, only raise the type error and
241 // return to the parser state before parsing the type as the initializer.
242 // let x: <parse_error>;
246 (Err(err), None) => {
247 // init error, ty parsed
248 // Couldn't parse the initializer and we're not attempting to recover a failed
249 // parse of the type, return the error.
253 let hi = if self.token == token::Semi { self.token.span } else { self.prev_token.span };
254 Ok(P(ast::Local { ty, pat, init, id: DUMMY_NODE_ID, span: lo.to(hi), attrs, tokens: None }))
257 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
258 fn parse_initializer(&mut self, eq_optional: bool) -> PResult<'a, Option<P<Expr>>> {
259 let eq_consumed = match self.token.kind {
260 token::BinOpEq(..) => {
261 // Recover `let x <op>= 1` as `let x = 1`
262 self.struct_span_err(
264 "can't reassign to an uninitialized variable",
266 .span_suggestion_short(
268 "initialize the variable",
270 Applicability::MaybeIncorrect,
276 _ => self.eat(&token::Eq),
279 Ok(if eq_consumed || eq_optional { Some(self.parse_expr()?) } else { None })
282 /// Parses a block. No inner attributes are allowed.
283 pub(super) fn parse_block(&mut self) -> PResult<'a, P<Block>> {
284 let (attrs, block) = self.parse_inner_attrs_and_block()?;
285 if let [.., last] = &*attrs {
286 self.error_on_forbidden_inner_attr(last.span, DEFAULT_INNER_ATTR_FORBIDDEN);
291 fn error_block_no_opening_brace<T>(&mut self) -> PResult<'a, T> {
292 let sp = self.token.span;
293 let tok = super::token_descr(&self.token);
294 let mut e = self.struct_span_err(sp, &format!("expected `{{`, found {}", tok));
295 let do_not_suggest_help = self.token.is_keyword(kw::In) || self.token == token::Colon;
297 // Check to see if the user has written something like
302 // which is valid in other languages, but not Rust.
303 match self.parse_stmt_without_recovery() {
304 // If the next token is an open brace (e.g., `if a b {`), the place-
305 // inside-a-block suggestion would be more likely wrong than right.
307 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
308 || do_not_suggest_help => {}
310 let stmt_own_line = self.sess.source_map().is_line_before_span_empty(sp);
311 let stmt_span = if stmt_own_line && self.eat(&token::Semi) {
312 // Expand the span to include the semicolon.
313 stmt.span.with_hi(self.prev_token.span.hi())
317 if let Ok(snippet) = self.span_to_snippet(stmt_span) {
320 "try placing this code inside a block",
321 format!("{{ {} }}", snippet),
322 // Speculative; has been misleading in the past (#46836).
323 Applicability::MaybeIncorrect,
328 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
333 e.span_label(sp, "expected `{`");
337 /// Parses a block. Inner attributes are allowed.
338 pub(super) fn parse_inner_attrs_and_block(
340 ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
341 self.parse_block_common(self.token.span, BlockCheckMode::Default)
344 /// Parses a block. Inner attributes are allowed.
345 pub(super) fn parse_block_common(
348 blk_mode: BlockCheckMode,
349 ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
350 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
352 if !self.eat(&token::OpenDelim(token::Brace)) {
353 return self.error_block_no_opening_brace();
356 let attrs = self.parse_inner_attributes()?;
357 let tail = if let Some(tail) = self.maybe_suggest_struct_literal(lo, blk_mode) {
360 self.parse_block_tail(lo, blk_mode, AttemptLocalParseRecovery::Yes)?
365 /// Parses the rest of a block expression or function body.
366 /// Precondition: already parsed the '{'.
367 crate fn parse_block_tail(
371 recover: AttemptLocalParseRecovery,
372 ) -> PResult<'a, P<Block>> {
373 let mut stmts = vec![];
374 while !self.eat(&token::CloseDelim(token::Brace)) {
375 if self.token == token::Eof {
378 let stmt = match self.parse_full_stmt(recover) {
379 Err(mut err) if recover.yes() => {
380 self.maybe_annotate_with_ascription(&mut err, false);
382 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
383 Some(self.mk_stmt_err(self.token.span))
386 Err(err) => return Err(err),
388 if let Some(stmt) = stmt {
391 // Found only `;` or `}`.
395 Ok(self.mk_block(stmts, s, lo.to(self.prev_token.span)))
398 /// Parses a statement, including the trailing semicolon.
399 pub fn parse_full_stmt(
401 recover: AttemptLocalParseRecovery,
402 ) -> PResult<'a, Option<Stmt>> {
403 // Skip looking for a trailing semicolon when we have an interpolated statement.
404 maybe_whole!(self, NtStmt, |x| Some(x));
406 let mut stmt = match self.parse_stmt_without_recovery()? {
408 None => return Ok(None),
411 let add_semi_token = |tokens: Option<&mut LazyTokenStream>| {
412 if let Some(tokens) = tokens {
413 *tokens = tokens.add_trailing_semi();
417 let mut eat_semi = true;
419 // Expression without semicolon.
420 StmtKind::Expr(ref mut expr)
421 if self.token != token::Eof && classify::expr_requires_semi_to_be_stmt(expr) =>
423 // Just check for errors and recover; do not eat semicolon yet.
425 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
427 if let TokenKind::DocComment(..) = self.token.kind {
428 if let Ok(snippet) = self.span_to_snippet(self.token.span) {
429 let sp = self.token.span;
430 let marker = &snippet[..3];
431 let (comment_marker, doc_comment_marker) = marker.split_at(2);
434 sp.with_hi(sp.lo() + BytePos(marker.len() as u32)),
436 "add a space before `{}` to use a regular comment",
439 format!("{} {}", comment_marker, doc_comment_marker),
440 Applicability::MaybeIncorrect,
445 self.check_mistyped_turbofish_with_multiple_type_params(e, expr)
453 // Don't complain about type errors in body tail after parse error (#57383).
454 let sp = expr.span.to(self.prev_token.span);
455 *expr = self.mk_expr_err(sp);
458 StmtKind::Expr(_) | StmtKind::MacCall(_) => {}
459 StmtKind::Local(ref mut local) => {
460 if let Err(e) = self.expect_semi() {
461 // We might be at the `,` in `let x = foo<bar, baz>;`. Try to recover.
462 match &mut local.init {
463 Some(ref mut expr) => {
464 self.check_mistyped_turbofish_with_multiple_type_params(e, expr)?;
465 // We found `foo<bar, baz>`, have we fully recovered?
468 None => return Err(e),
472 // We just checked that there's a semicolon in the tokenstream,
474 add_semi_token(local.tokens.as_mut());
476 StmtKind::Empty | StmtKind::Item(_) | StmtKind::Semi(_) => eat_semi = false,
479 if eat_semi && self.eat(&token::Semi) {
480 stmt = stmt.add_trailing_semicolon();
481 // We just checked that we have a semicolon in the tokenstream,
483 add_semi_token(stmt.tokens_mut());
485 stmt.span = stmt.span.to(self.prev_token.span);
489 pub(super) fn mk_block(&self, stmts: Vec<Stmt>, rules: BlockCheckMode, span: Span) -> P<Block> {
490 P(Block { stmts, id: DUMMY_NODE_ID, rules, span, tokens: None })
493 pub(super) fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt {
494 Stmt { id: DUMMY_NODE_ID, kind, span }
497 pub(super) fn mk_stmt_err(&self, span: Span) -> Stmt {
498 self.mk_stmt(span, StmtKind::Expr(self.mk_expr_err(span)))
501 pub(super) fn mk_block_err(&self, span: Span) -> P<Block> {
502 self.mk_block(vec![self.mk_stmt_err(span)], BlockCheckMode::Default, span)