1 use super::diagnostics::Error;
2 use super::expr::LhsExpr;
3 use super::pat::GateOr;
4 use super::path::PathStyle;
5 use super::{BlockMode, Parser, PrevTokenKind, Restrictions, SemiColonMode};
6 use crate::maybe_whole;
7 use crate::DirectoryOwnership;
9 use rustc_errors::{Applicability, PResult};
10 use rustc_span::source_map::{respan, Span};
11 use rustc_span::symbol::{kw, sym, Symbol};
13 use syntax::ast::{AttrStyle, AttrVec, Attribute, Mac, MacStmtStyle, VisibilityKind};
14 use syntax::ast::{Block, BlockCheckMode, Expr, ExprKind, Local, Stmt, StmtKind, DUMMY_NODE_ID};
17 use syntax::util::classify;
22 /// Parses a statement. This stops just before trailing semicolons on everything but items.
23 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
24 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
25 Ok(self.parse_stmt_without_recovery(true).unwrap_or_else(|mut e| {
27 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
32 fn parse_stmt_without_recovery(
34 macro_legacy_warnings: bool,
35 ) -> PResult<'a, Option<Stmt>> {
36 maybe_whole!(self, NtStmt, |x| Some(x));
38 let attrs = self.parse_outer_attributes()?;
39 let lo = self.token.span;
41 if self.eat_keyword(kw::Let) {
42 return self.parse_local_mk(lo, attrs.into()).map(Some);
44 if self.is_kw_followed_by_ident(kw::Mut) {
45 return self.recover_stmt_local(lo, attrs.into(), "missing keyword", "let mut");
47 if self.is_kw_followed_by_ident(kw::Auto) {
48 self.bump(); // `auto`
49 let msg = "write `let` instead of `auto` to introduce a new variable";
50 return self.recover_stmt_local(lo, attrs.into(), msg, "let");
52 if self.is_kw_followed_by_ident(sym::var) {
54 let msg = "write `let` instead of `var` to introduce a new variable";
55 return self.recover_stmt_local(lo, attrs.into(), msg, "let");
58 let mac_vis = respan(lo, VisibilityKind::Inherited);
59 if let Some(macro_def) = self.eat_macro_def(&attrs, &mac_vis, lo)? {
60 return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Item(macro_def))));
63 // Starts like a simple path, being careful to avoid contextual keywords
64 // such as a union items, item with `crate` visibility or auto trait items.
65 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
66 // like a path (1 token), but it fact not a path.
67 if self.token.is_path_start()
68 && !self.token.is_qpath_start()
69 && !self.is_union_item() // `union::b::c` - path, `union U { ... }` - not a path.
70 && !self.is_crate_vis() // `crate::b::c` - path, `crate struct S;` - not a path.
71 && !self.is_auto_trait_item()
72 && !self.is_async_fn()
74 let path = self.parse_path(PathStyle::Expr)?;
76 if self.eat(&token::Not) {
77 return self.parse_stmt_mac(lo, attrs.into(), path, macro_legacy_warnings);
80 let expr = if self.check(&token::OpenDelim(token::Brace)) {
81 self.parse_struct_expr(lo, path, AttrVec::new())?
83 let hi = self.prev_span;
84 self.mk_expr(lo.to(hi), ExprKind::Path(None, path), AttrVec::new())
87 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
88 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
89 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
91 return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Expr(expr))));
94 // FIXME: Bad copy of attrs
95 let old_directory_ownership =
96 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
97 let item = self.parse_item_(attrs.clone(), false, true)?;
98 self.directory.ownership = old_directory_ownership;
100 if let Some(item) = item {
101 return Ok(Some(self.mk_stmt(lo.to(item.span), StmtKind::Item(item))));
104 // Do not attempt to parse an expression if we're done here.
105 if self.token == token::Semi {
106 self.error_outer_attrs(&attrs);
108 let mut last_semi = lo;
109 while self.token == token::Semi {
110 last_semi = self.token.span;
113 // We are encoding a string of semicolons as an an empty tuple that spans
114 // the excess semicolons to preserve this info until the lint stage.
115 let kind = StmtKind::Semi(self.mk_expr(
117 ExprKind::Tup(Vec::new()),
120 return Ok(Some(self.mk_stmt(lo.to(last_semi), kind)));
123 if self.token == token::CloseDelim(token::Brace) {
124 self.error_outer_attrs(&attrs);
128 // Remainder are line-expr stmts.
129 let e = self.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs.into()))?;
130 Ok(Some(self.mk_stmt(lo.to(e.span), StmtKind::Expr(e))))
133 /// Parses a statement macro `mac!(args)` provided a `path` representing `mac`.
134 /// At this point, the `!` token after the path has already been eaten.
140 legacy_warnings: bool,
141 ) -> PResult<'a, Option<Stmt>> {
142 let args = self.parse_mac_args()?;
143 let delim = args.delim();
144 let hi = self.prev_span;
147 if delim == token::Brace { MacStmtStyle::Braces } else { MacStmtStyle::NoBraces };
149 let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription };
151 let kind = if delim == token::Brace || self.token == token::Semi || self.token == token::Eof
153 StmtKind::Mac(P((mac, style, attrs.into())))
155 // We used to incorrectly stop parsing macro-expanded statements here.
156 // If the next token will be an error anyway but could have parsed with the
157 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
158 else if legacy_warnings
159 && self.token.can_begin_expr()
160 && match self.token.kind {
161 // These can continue an expression, so we can't stop parsing and warn.
162 token::OpenDelim(token::Paren)
163 | token::OpenDelim(token::Bracket)
164 | token::BinOp(token::Minus)
165 | token::BinOp(token::Star)
166 | token::BinOp(token::And)
167 | token::BinOp(token::Or)
172 | token::DotDotEq => false,
176 self.warn_missing_semicolon();
177 StmtKind::Mac(P((mac, style, attrs)))
179 // Since none of the above applied, this is an expression statement macro.
180 let e = self.mk_expr(lo.to(hi), ExprKind::Mac(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)?;
183 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
186 Ok(Some(self.mk_stmt(lo.to(hi), kind)))
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]) {
192 if !attrs.is_empty() {
193 if self.prev_token_kind == PrevTokenKind::DocComment {
194 self.span_fatal_err(self.prev_span, Error::UselessDocComment).emit();
195 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
196 self.struct_span_err(self.token.span, "expected statement after outer attribute")
202 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
203 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
206 fn recover_stmt_local(
212 ) -> PResult<'a, Option<Stmt>> {
213 let stmt = self.parse_local_mk(lo, attrs)?;
214 self.struct_span_err(lo, "invalid variable declaration")
215 .span_suggestion(lo, msg, sugg.to_string(), Applicability::MachineApplicable)
220 fn parse_local_mk(&mut self, lo: Span, attrs: AttrVec) -> PResult<'a, Stmt> {
221 let local = self.parse_local(attrs.into())?;
222 Ok(self.mk_stmt(lo.to(self.prev_span), StmtKind::Local(local)))
225 /// Parses a local variable declaration.
226 fn parse_local(&mut self, attrs: AttrVec) -> PResult<'a, P<Local>> {
227 let lo = self.prev_span;
228 let pat = self.parse_top_pat(GateOr::Yes)?;
230 let (err, ty) = if self.eat(&token::Colon) {
231 // Save the state of the parser before parsing type normally, in case there is a `:`
232 // instead of an `=` typo.
233 let parser_snapshot_before_type = self.clone();
234 let colon_sp = self.prev_span;
235 match self.parse_ty() {
236 Ok(ty) => (None, Some(ty)),
238 // Rewind to before attempting to parse the type and continue parsing.
239 let parser_snapshot_after_type = self.clone();
240 mem::replace(self, parser_snapshot_before_type);
242 let snippet = self.span_to_snippet(pat.span).unwrap();
243 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
244 (Some((parser_snapshot_after_type, colon_sp, err)), None)
250 let init = match (self.parse_initializer(err.is_some()), err) {
251 (Ok(init), None) => {
252 // init parsed, ty parsed
255 (Ok(init), Some((_, colon_sp, mut err))) => {
256 // init parsed, ty error
257 // Could parse the type as if it were the initializer, it is likely there was a
258 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
259 err.span_suggestion_short(
261 "use `=` if you meant to assign",
263 Applicability::MachineApplicable,
266 // As this was parsed successfully, continue as if the code has been fixed for the
267 // rest of the file. It will still fail due to the emitted error, but we avoid
271 (Err(mut init_err), Some((snapshot, _, ty_err))) => {
272 // init error, ty error
274 // Couldn't parse the type nor the initializer, only raise the type error and
275 // return to the parser state before parsing the type as the initializer.
276 // let x: <parse_error>;
277 mem::replace(self, snapshot);
280 (Err(err), None) => {
281 // init error, ty parsed
282 // Couldn't parse the initializer and we're not attempting to recover a failed
283 // parse of the type, return the error.
287 let hi = if self.token == token::Semi { self.token.span } else { self.prev_span };
288 Ok(P(ast::Local { ty, pat, init, id: DUMMY_NODE_ID, span: lo.to(hi), attrs }))
291 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
292 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
293 if self.eat(&token::Eq) {
294 Ok(Some(self.parse_expr()?))
296 Ok(Some(self.parse_expr()?))
302 fn is_auto_trait_item(&self) -> bool {
304 (self.token.is_keyword(kw::Auto) &&
305 self.is_keyword_ahead(1, &[kw::Trait]))
306 || // unsafe auto trait
307 (self.token.is_keyword(kw::Unsafe) &&
308 self.is_keyword_ahead(1, &[kw::Auto]) &&
309 self.is_keyword_ahead(2, &[kw::Trait]))
312 /// Parses a block. No inner attributes are allowed.
313 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
314 maybe_whole!(self, NtBlock, |x| x);
316 let lo = self.token.span;
318 if !self.eat(&token::OpenDelim(token::Brace)) {
319 return self.error_block_no_opening_brace();
322 self.parse_block_tail(lo, BlockCheckMode::Default)
325 fn error_block_no_opening_brace<T>(&mut self) -> PResult<'a, T> {
326 let sp = self.token.span;
327 let tok = super::token_descr(&self.token);
328 let mut e = self.struct_span_err(sp, &format!("expected `{{`, found {}", tok));
329 let do_not_suggest_help = self.token.is_keyword(kw::In) || self.token == token::Colon;
331 // Check to see if the user has written something like
336 // which is valid in other languages, but not Rust.
337 match self.parse_stmt_without_recovery(false) {
339 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
340 || do_not_suggest_help
342 // If the next token is an open brace (e.g., `if a b {`), the place-
343 // inside-a-block suggestion would be more likely wrong than right.
344 e.span_label(sp, "expected `{`");
347 let stmt_span = if self.eat(&token::Semi) {
348 // Expand the span to include the semicolon.
349 stmt.span.with_hi(self.prev_span.hi())
353 if let Ok(snippet) = self.span_to_snippet(stmt_span) {
356 "try placing this code inside a block",
357 format!("{{ {} }}", snippet),
358 // Speculative; has been misleading in the past (#46836).
359 Applicability::MaybeIncorrect,
364 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
369 e.span_label(sp, "expected `{`");
373 /// Parses a block. Inner attributes are allowed.
374 pub(super) fn parse_inner_attrs_and_block(
376 ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
377 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
379 let lo = self.token.span;
380 self.expect(&token::OpenDelim(token::Brace))?;
381 Ok((self.parse_inner_attributes()?, self.parse_block_tail(lo, BlockCheckMode::Default)?))
384 /// Parses the rest of a block expression or function body.
385 /// Precondition: already parsed the '{'.
386 pub(super) fn parse_block_tail(
390 ) -> PResult<'a, P<Block>> {
391 let mut stmts = vec![];
392 while !self.eat(&token::CloseDelim(token::Brace)) {
393 if self.token == token::Eof {
396 let stmt = match self.parse_full_stmt(false) {
398 self.maybe_annotate_with_ascription(&mut err, false);
400 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
401 Some(self.mk_stmt_err(self.token.span))
405 if let Some(stmt) = stmt {
408 // Found only `;` or `}`.
412 Ok(self.mk_block(stmts, s, lo.to(self.prev_span)))
415 /// Parses a statement, including the trailing semicolon.
416 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
417 // Skip looking for a trailing semicolon when we have an interpolated statement.
418 maybe_whole!(self, NtStmt, |x| Some(x));
420 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
422 None => return Ok(None),
425 let mut eat_semi = true;
427 StmtKind::Expr(ref expr) if self.token != token::Eof => {
428 // expression without semicolon
429 if classify::expr_requires_semi_to_be_stmt(expr) {
430 // Just check for errors and recover; do not eat semicolon yet.
432 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
436 // Don't complain about type errors in body tail after parse error (#57383).
437 let sp = expr.span.to(self.prev_span);
438 stmt.kind = StmtKind::Expr(self.mk_expr_err(sp));
442 StmtKind::Local(..) => {
443 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
444 if macro_legacy_warnings && self.token != token::Semi {
445 self.warn_missing_semicolon();
454 if eat_semi && self.eat(&token::Semi) {
455 stmt = stmt.add_trailing_semicolon();
457 stmt.span = stmt.span.to(self.prev_span);
461 fn warn_missing_semicolon(&self) {
463 .struct_span_warn(self.token.span, {
464 &format!("expected `;`, found {}", super::token_descr(&self.token))
467 "this was erroneously allowed and will become a hard error in a future release"
472 pub(super) fn mk_block(&self, stmts: Vec<Stmt>, rules: BlockCheckMode, span: Span) -> P<Block> {
473 P(Block { stmts, id: DUMMY_NODE_ID, rules, span })
476 pub(super) fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt {
477 Stmt { id: DUMMY_NODE_ID, kind, span }
480 fn mk_stmt_err(&self, span: Span) -> Stmt {
481 self.mk_stmt(span, StmtKind::Expr(self.mk_expr_err(span)))
484 pub(super) fn mk_block_err(&self, span: Span) -> P<Block> {
485 self.mk_block(vec![self.mk_stmt_err(span)], BlockCheckMode::Default, span)