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 if self.eat_keyword(kw::Let) {
43 let local = self.parse_local(attrs.into())?;
44 return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Local(local))));
47 let mac_vis = respan(lo, VisibilityKind::Inherited);
48 if let Some(macro_def) = self.eat_macro_def(&attrs, &mac_vis, lo)? {
49 return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Item(macro_def))));
52 // Starts like a simple path, being careful to avoid contextual keywords
53 // such as a union items, item with `crate` visibility or auto trait items.
54 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
55 // like a path (1 token), but it fact not a path.
56 if self.token.is_path_start()
57 && !self.token.is_qpath_start()
58 && !self.is_union_item() // `union::b::c` - path, `union U { ... }` - not a path.
59 && !self.is_crate_vis() // `crate::b::c` - path, `crate struct S;` - not a path.
60 && !self.is_auto_trait_item()
61 && !self.is_async_fn()
63 let path = self.parse_path(PathStyle::Expr)?;
65 if self.eat(&token::Not) {
66 return self.parse_stmt_mac(lo, attrs.into(), path, macro_legacy_warnings);
69 let expr = if self.check(&token::OpenDelim(token::Brace)) {
70 self.parse_struct_expr(lo, path, ThinVec::new())?
72 let hi = self.prev_span;
73 self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new())
76 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
77 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
78 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
80 return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Expr(expr))));
83 // FIXME: Bad copy of attrs
84 let old_directory_ownership =
85 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
86 let item = self.parse_item_(attrs.clone(), false, true)?;
87 self.directory.ownership = old_directory_ownership;
89 if let Some(item) = item {
90 return Ok(Some(self.mk_stmt(lo.to(item.span), StmtKind::Item(item))));
93 // Do not attempt to parse an expression if we're done here.
94 if self.token == token::Semi {
95 self.error_outer_attrs(&attrs);
97 let mut last_semi = lo;
98 while self.token == token::Semi {
99 last_semi = self.token.span;
102 // We are encoding a string of semicolons as an an empty tuple that spans
103 // the excess semicolons to preserve this info until the lint stage.
104 let kind = StmtKind::Semi(self.mk_expr(
106 ExprKind::Tup(Vec::new()),
109 return Ok(Some(self.mk_stmt(lo.to(last_semi), kind)));
112 if self.token == token::CloseDelim(token::Brace) {
113 self.error_outer_attrs(&attrs);
117 // Remainder are line-expr stmts.
118 let e = self.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs.into()))?;
119 Ok(Some(self.mk_stmt(lo.to(e.span), StmtKind::Expr(e))))
122 /// Parses a statement macro `mac!(args)` provided a `path` representing `mac`.
123 /// At this point, the `!` token after the path has already been eaten.
127 attrs: ThinVec<Attribute>,
129 legacy_warnings: bool,
130 ) -> PResult<'a, Option<Stmt>> {
131 let args = self.parse_mac_args()?;
132 let delim = args.delim();
133 let hi = self.prev_span;
135 let style = if delim == token::Brace {
138 MacStmtStyle::NoBraces
144 prior_type_ascription: self.last_type_ascription,
147 let kind = if delim == token::Brace
148 || self.token == token::Semi
149 || self.token == token::Eof
151 StmtKind::Mac(P((mac, style, attrs.into())))
153 // We used to incorrectly stop parsing macro-expanded statements here.
154 // If the next token will be an error anyway but could have parsed with the
155 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
156 else if legacy_warnings
157 && self.token.can_begin_expr()
158 && match self.token.kind {
159 // These can continue an expression, so we can't stop parsing and warn.
160 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
161 token::BinOp(token::Minus) | token::BinOp(token::Star) |
162 token::BinOp(token::And) | token::BinOp(token::Or) |
163 token::AndAnd | token::OrOr |
164 token::DotDot | token::DotDotDot | token::DotDotEq => false,
168 self.warn_missing_semicolon();
169 StmtKind::Mac(P((mac, style, attrs)))
171 // Since none of the above applied, this is an expression statement macro.
172 let e = self.mk_expr(lo.to(hi), ExprKind::Mac(mac), ThinVec::new());
173 let e = self.maybe_recover_from_bad_qpath(e, true)?;
174 let e = self.parse_dot_or_call_expr_with(e, lo, attrs)?;
175 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
178 Ok(Some(self.mk_stmt(lo.to(hi), kind)))
181 /// Error on outer attributes in this context.
182 /// Also error if the previous token was a doc comment.
183 fn error_outer_attrs(&self, attrs: &[Attribute]) {
184 if !attrs.is_empty() {
185 if self.prev_token_kind == PrevTokenKind::DocComment {
186 self.span_fatal_err(self.prev_span, Error::UselessDocComment).emit();
187 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
188 self.span_err(self.token.span, "expected statement after outer attribute");
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 return self.error_block_no_opening_brace();
297 self.parse_block_tail(lo, BlockCheckMode::Default)
300 fn error_block_no_opening_brace<T>(&mut self) -> PResult<'a, T> {
301 let sp = self.token.span;
302 let tok = self.this_token_descr();
303 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
304 let do_not_suggest_help =
305 self.token.is_keyword(kw::In) || self.token == token::Colon;
307 if self.token.is_ident_named(sym::and) {
308 e.span_suggestion_short(
310 "use `&&` instead of `and` for the boolean operator",
312 Applicability::MaybeIncorrect,
315 if self.token.is_ident_named(sym::or) {
316 e.span_suggestion_short(
318 "use `||` instead of `or` for the boolean operator",
320 Applicability::MaybeIncorrect,
324 // Check to see if the user has written something like
329 // which is valid in other languages, but not Rust.
330 match self.parse_stmt_without_recovery(false) {
332 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
333 || do_not_suggest_help
335 // If the next token is an open brace (e.g., `if a b {`), the place-
336 // inside-a-block suggestion would be more likely wrong than right.
337 e.span_label(sp, "expected `{`");
340 let stmt_span = if self.eat(&token::Semi) {
341 // Expand the span to include the semicolon.
342 stmt.span.with_hi(self.prev_span.hi())
346 if let Ok(snippet) = self.span_to_snippet(stmt_span) {
349 "try placing this code inside a block",
350 format!("{{ {} }}", snippet),
351 // Speculative; has been misleading in the past (#46836).
352 Applicability::MaybeIncorrect,
357 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
362 e.span_label(sp, "expected `{`");
366 /// Parses a block. Inner attributes are allowed.
367 pub(super) fn parse_inner_attrs_and_block(
369 ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
370 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
372 let lo = self.token.span;
373 self.expect(&token::OpenDelim(token::Brace))?;
374 Ok((self.parse_inner_attributes()?,
375 self.parse_block_tail(lo, BlockCheckMode::Default)?))
378 /// Parses the rest of a block expression or function body.
379 /// Precondition: already parsed the '{'.
380 pub(super) fn parse_block_tail(
384 ) -> PResult<'a, P<Block>> {
385 let mut stmts = vec![];
386 while !self.eat(&token::CloseDelim(token::Brace)) {
387 if self.token == token::Eof {
390 let stmt = match self.parse_full_stmt(false) {
392 self.maybe_annotate_with_ascription(&mut err, false);
394 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
397 StmtKind::Expr(self.mk_expr_err(self.token.span)),
402 if let Some(stmt) = stmt {
405 // Found only `;` or `}`.
413 span: lo.to(self.prev_span),
417 /// Parses a statement, including the trailing semicolon.
418 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
419 // Skip looking for a trailing semicolon when we have an interpolated statement.
420 maybe_whole!(self, NtStmt, |x| Some(x));
422 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
424 None => return Ok(None),
427 let mut eat_semi = true;
429 StmtKind::Expr(ref expr) if self.token != token::Eof => {
430 // expression without semicolon
431 if classify::expr_requires_semi_to_be_stmt(expr) {
432 // Just check for errors and recover; do not eat semicolon yet.
434 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
438 // Don't complain about type errors in body tail after parse error (#57383).
439 let sp = expr.span.to(self.prev_span);
440 stmt.kind = StmtKind::Expr(self.mk_expr_err(sp));
444 StmtKind::Local(..) => {
445 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
446 if macro_legacy_warnings && self.token != token::Semi {
447 self.warn_missing_semicolon();
456 if eat_semi && self.eat(&token::Semi) {
457 stmt = stmt.add_trailing_semicolon();
459 stmt.span = stmt.span.to(self.prev_span);
463 fn warn_missing_semicolon(&self) {
464 self.diagnostic().struct_span_warn(self.token.span, {
465 &format!("expected `;`, found {}", self.this_token_descr())
467 "this was erroneously allowed and will become a hard error in a future release"
471 fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt {
472 Stmt { id: DUMMY_NODE_ID, kind, span }