1 use super::{Parser, Restrictions, PrevTokenKind, SemiColonMode, BlockMode};
2 use super::expr::LhsExpr;
3 use super::path::PathStyle;
4 use super::pat::GateOr;
5 use super::diagnostics::Error;
6 use crate::maybe_whole;
7 use crate::DirectoryOwnership;
9 use rustc_errors::{PResult, Applicability};
13 use syntax::ast::{DUMMY_NODE_ID, Stmt, StmtKind, Local, Block, BlockCheckMode, Expr, ExprKind};
14 use syntax::ast::{Attribute, AttrStyle, VisibilityKind, MacStmtStyle, Mac};
15 use syntax::util::classify;
17 use syntax_pos::source_map::{respan, Span};
18 use syntax_pos::symbol::{kw, sym};
23 /// Parses a statement. This stops just before trailing semicolons on everything but items.
24 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
25 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
26 Ok(self.parse_stmt_without_recovery(true).unwrap_or_else(|mut e| {
28 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
33 fn parse_stmt_without_recovery(
35 macro_legacy_warnings: bool,
36 ) -> PResult<'a, Option<Stmt>> {
37 maybe_whole!(self, NtStmt, |x| Some(x));
39 let attrs = self.parse_outer_attributes()?;
40 let lo = self.token.span;
42 Ok(Some(if self.eat_keyword(kw::Let) {
43 let local = self.parse_local(attrs.into())?;
44 self.mk_stmt(lo.to(self.prev_span), StmtKind::Local(local))
45 } else if let Some(macro_def) = self.eat_macro_def(
47 &respan(lo, VisibilityKind::Inherited),
50 self.mk_stmt(lo.to(self.prev_span), StmtKind::Item(macro_def))
51 // Starts like a simple path, being careful to avoid contextual keywords
52 // such as a union items, item with `crate` visibility or auto trait items.
53 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
54 // like a path (1 token), but it fact not a path.
55 } else if self.token.is_path_start()
56 && !self.token.is_qpath_start()
57 && !self.is_union_item() // `union::b::c` - path, `union U { ... }` - not a path.
58 && !self.is_crate_vis() // `crate::b::c` - path, `crate struct S;` - not a path.
59 && !self.is_auto_trait_item()
60 && !self.is_async_fn()
62 let path = self.parse_path(PathStyle::Expr)?;
64 if self.eat(&token::Not) {
65 return self.parse_stmt_mac(lo, attrs.into(), path, macro_legacy_warnings);
68 let expr = if self.check(&token::OpenDelim(token::Brace)) {
69 self.parse_struct_expr(lo, path, ThinVec::new())?
71 let hi = self.prev_span;
72 self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new())
75 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
76 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
77 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
79 return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Expr(expr))));
81 // FIXME: Bad copy of attrs
82 let old_directory_ownership =
83 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
84 let item = self.parse_item_(attrs.clone(), false, true)?;
85 self.directory.ownership = old_directory_ownership;
87 if let Some(item) = item {
88 return Ok(Some(self.mk_stmt(lo.to(item.span), StmtKind::Item(item))));
91 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
92 if !attrs.is_empty() {
93 if s.prev_token_kind == PrevTokenKind::DocComment {
94 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
95 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
97 s.token.span, "expected statement after outer attribute"
103 // Do not attempt to parse an expression if we're done here.
104 if self.token == token::Semi {
105 unused_attrs(&attrs, self);
107 let mut last_semi = lo;
108 while self.token == token::Semi {
109 last_semi = self.token.span;
112 // We are encoding a string of semicolons as an
113 // an empty tuple that spans the excess semicolons
114 // 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 unused_attrs(&attrs, self);
128 // Remainder are line-expr stmts.
129 let e = self.parse_expr_res( Restrictions::STMT_EXPR, Some(attrs.into()))?;
130 self.mk_stmt(lo.to(e.span), StmtKind::Expr(e))
134 /// Parses a statement macro `mac!(args)` provided a `path` representing `mac`.
135 /// At this point, the `!` token after the path has already been eaten.
139 attrs: ThinVec<Attribute>,
141 legacy_warnings: bool,
142 ) -> PResult<'a, Option<Stmt>> {
143 let args = self.parse_mac_args()?;
144 let delim = args.delim();
145 let hi = self.prev_span;
147 let style = if delim == token::Brace {
150 MacStmtStyle::NoBraces
156 prior_type_ascription: self.last_type_ascription,
159 let kind = if delim == token::Brace
160 || self.token == token::Semi
161 || self.token == token::Eof
163 StmtKind::Mac(P((mac, style, attrs.into())))
165 // We used to incorrectly stop parsing macro-expanded statements here.
166 // If the next token will be an error anyway but could have parsed with the
167 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
168 else if legacy_warnings
169 && self.token.can_begin_expr()
170 && match self.token.kind {
171 // These can continue an expression, so we can't stop parsing and warn.
172 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
173 token::BinOp(token::Minus) | token::BinOp(token::Star) |
174 token::BinOp(token::And) | token::BinOp(token::Or) |
175 token::AndAnd | token::OrOr |
176 token::DotDot | token::DotDotDot | token::DotDotEq => false,
180 self.warn_missing_semicolon();
181 StmtKind::Mac(P((mac, style, attrs)))
183 // Since none of the above applied, this is an expression statement macro.
184 let e = self.mk_expr(lo.to(hi), ExprKind::Mac(mac), ThinVec::new());
185 let e = self.maybe_recover_from_bad_qpath(e, true)?;
186 let e = self.parse_dot_or_call_expr_with(e, lo, attrs)?;
187 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
190 Ok(Some(self.mk_stmt(lo.to(hi), kind)))
193 /// Parses a local variable declaration.
194 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
195 let lo = self.prev_span;
196 let pat = self.parse_top_pat(GateOr::Yes)?;
198 let (err, ty) = if self.eat(&token::Colon) {
199 // Save the state of the parser before parsing type normally, in case there is a `:`
200 // instead of an `=` typo.
201 let parser_snapshot_before_type = self.clone();
202 let colon_sp = self.prev_span;
203 match self.parse_ty() {
204 Ok(ty) => (None, Some(ty)),
206 // Rewind to before attempting to parse the type and continue parsing.
207 let parser_snapshot_after_type = self.clone();
208 mem::replace(self, parser_snapshot_before_type);
210 let snippet = self.span_to_snippet(pat.span).unwrap();
211 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
212 (Some((parser_snapshot_after_type, colon_sp, err)), None)
218 let init = match (self.parse_initializer(err.is_some()), err) {
219 (Ok(init), None) => { // init parsed, ty parsed
222 (Ok(init), Some((_, colon_sp, mut err))) => { // 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))) => { // init error, ty error
239 // Couldn't parse the type nor the initializer, only raise the type error and
240 // return to the parser state before parsing the type as the initializer.
241 // let x: <parse_error>;
242 mem::replace(self, snapshot);
245 (Err(err), None) => { // init error, ty parsed
246 // Couldn't parse the initializer and we're not attempting to recover a failed
247 // parse of the type, return the error.
251 let hi = if self.token == token::Semi {
266 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
267 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
268 if self.eat(&token::Eq) {
269 Ok(Some(self.parse_expr()?))
271 Ok(Some(self.parse_expr()?))
277 fn is_auto_trait_item(&self) -> bool {
279 (self.token.is_keyword(kw::Auto) &&
280 self.is_keyword_ahead(1, &[kw::Trait]))
281 || // unsafe auto trait
282 (self.token.is_keyword(kw::Unsafe) &&
283 self.is_keyword_ahead(1, &[kw::Auto]) &&
284 self.is_keyword_ahead(2, &[kw::Trait]))
287 /// Parses a block. No inner attributes are allowed.
288 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
289 maybe_whole!(self, NtBlock, |x| x);
291 let lo = self.token.span;
293 if !self.eat(&token::OpenDelim(token::Brace)) {
294 let sp = self.token.span;
295 let tok = self.this_token_descr();
296 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
297 let do_not_suggest_help =
298 self.token.is_keyword(kw::In) || self.token == token::Colon;
300 if self.token.is_ident_named(sym::and) {
301 e.span_suggestion_short(
303 "use `&&` instead of `and` for the boolean operator",
305 Applicability::MaybeIncorrect,
308 if self.token.is_ident_named(sym::or) {
309 e.span_suggestion_short(
311 "use `||` instead of `or` for the boolean operator",
313 Applicability::MaybeIncorrect,
317 // Check to see if the user has written something like
322 // which is valid in other languages, but not Rust.
323 match self.parse_stmt_without_recovery(false) {
325 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
326 || do_not_suggest_help {
327 // If the next token is an open brace (e.g., `if a b {`), the place-
328 // inside-a-block suggestion would be more likely wrong than right.
329 e.span_label(sp, "expected `{`");
332 let mut stmt_span = stmt.span;
333 // Expand the span to include the semicolon, if it exists.
334 if self.eat(&token::Semi) {
335 stmt_span = stmt_span.with_hi(self.prev_span.hi());
337 if let Ok(snippet) = self.span_to_snippet(stmt_span) {
340 "try placing this code inside a block",
341 format!("{{ {} }}", snippet),
342 // Speculative; has been misleading in the past (#46836).
343 Applicability::MaybeIncorrect,
348 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
353 e.span_label(sp, "expected `{`");
357 self.parse_block_tail(lo, BlockCheckMode::Default)
360 /// Parses a block. Inner attributes are allowed.
361 pub(super) fn parse_inner_attrs_and_block(
363 ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
364 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
366 let lo = self.token.span;
367 self.expect(&token::OpenDelim(token::Brace))?;
368 Ok((self.parse_inner_attributes()?,
369 self.parse_block_tail(lo, BlockCheckMode::Default)?))
372 /// Parses the rest of a block expression or function body.
373 /// Precondition: already parsed the '{'.
374 pub(super) fn parse_block_tail(
378 ) -> PResult<'a, P<Block>> {
379 let mut stmts = vec![];
380 while !self.eat(&token::CloseDelim(token::Brace)) {
381 if self.token == token::Eof {
384 let stmt = match self.parse_full_stmt(false) {
386 self.maybe_annotate_with_ascription(&mut err, false);
388 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
391 StmtKind::Expr(self.mk_expr_err(self.token.span)),
396 if let Some(stmt) = stmt {
399 // Found only `;` or `}`.
407 span: lo.to(self.prev_span),
411 /// Parses a statement, including the trailing semicolon.
412 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
413 // Skip looking for a trailing semicolon when we have an interpolated statement.
414 maybe_whole!(self, NtStmt, |x| Some(x));
416 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
418 None => return Ok(None),
421 let mut eat_semi = true;
423 StmtKind::Expr(ref expr) if self.token != token::Eof => {
424 // expression without semicolon
425 if classify::expr_requires_semi_to_be_stmt(expr) {
426 // Just check for errors and recover; do not eat semicolon yet.
428 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
432 // Don't complain about type errors in body tail after parse error (#57383).
433 let sp = expr.span.to(self.prev_span);
434 stmt.kind = StmtKind::Expr(self.mk_expr_err(sp));
438 StmtKind::Local(..) => {
439 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
440 if macro_legacy_warnings && self.token != token::Semi {
441 self.warn_missing_semicolon();
450 if eat_semi && self.eat(&token::Semi) {
451 stmt = stmt.add_trailing_semicolon();
453 stmt.span = stmt.span.to(self.prev_span);
457 fn warn_missing_semicolon(&self) {
458 self.diagnostic().struct_span_warn(self.token.span, {
459 &format!("expected `;`, found {}", self.this_token_descr())
461 "this was erroneously allowed and will become a hard error in a future release"
465 fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt {
466 Stmt { id: DUMMY_NODE_ID, kind, span }