]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/stmt.rs
Rollup merge of #69158 - ecstatic-morse:graphviz-diff, r=matthewjasper
[rust.git] / src / librustc_parse / parser / stmt.rs
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, Restrictions, SemiColonMode};
6 use crate::maybe_whole;
7 use crate::DirectoryOwnership;
8
9 use rustc_errors::{Applicability, PResult};
10 use rustc_span::source_map::{BytePos, Span};
11 use rustc_span::symbol::{kw, sym};
12 use syntax::ast;
13 use syntax::ast::{AttrStyle, AttrVec, Attribute, Mac, MacStmtStyle};
14 use syntax::ast::{Block, BlockCheckMode, Expr, ExprKind, Local, Stmt, StmtKind, DUMMY_NODE_ID};
15 use syntax::ptr::P;
16 use syntax::token::{self, TokenKind};
17 use syntax::util::classify;
18
19 use std::mem;
20
21 impl<'a> Parser<'a> {
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| {
26             e.emit();
27             self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
28             None
29         }))
30     }
31
32     fn parse_stmt_without_recovery(
33         &mut self,
34         macro_legacy_warnings: bool,
35     ) -> PResult<'a, Option<Stmt>> {
36         maybe_whole!(self, NtStmt, |x| Some(x));
37
38         let attrs = self.parse_outer_attributes()?;
39         let lo = self.token.span;
40
41         if self.eat_keyword(kw::Let) {
42             return self.parse_local_mk(lo, attrs.into()).map(Some);
43         }
44         if self.is_kw_followed_by_ident(kw::Mut) {
45             return self.recover_stmt_local(lo, attrs.into(), "missing keyword", "let mut");
46         }
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");
51         }
52         if self.is_kw_followed_by_ident(sym::var) {
53             self.bump(); // `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");
56         }
57
58         // Starts like a simple path, being careful to avoid contextual keywords,
59         // e.g., `union`, items with `crate` visibility, or `auto trait` items.
60         // We aim to parse an arbitrary path `a::b` but not something that starts like a path
61         // (1 token), but it fact not a path. Also, we avoid stealing syntax from `parse_item_`.
62         if self.token.is_path_start() && !self.token.is_qpath_start() && !self.is_path_start_item()
63         {
64             let path = self.parse_path(PathStyle::Expr)?;
65
66             if self.eat(&token::Not) {
67                 return self.parse_stmt_mac(lo, attrs.into(), path, macro_legacy_warnings);
68             }
69
70             let expr = if self.check(&token::OpenDelim(token::Brace)) {
71                 self.parse_struct_expr(lo, path, AttrVec::new())?
72             } else {
73                 let hi = self.prev_span;
74                 self.mk_expr(lo.to(hi), ExprKind::Path(None, path), AttrVec::new())
75             };
76
77             let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
78                 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
79                 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
80             })?;
81             return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Expr(expr))));
82         }
83
84         // FIXME: Bad copy of attrs
85         let old_directory_ownership =
86             mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
87         let item = self.parse_item_(attrs.clone(), false, true)?;
88         self.directory.ownership = old_directory_ownership;
89
90         if let Some(item) = item {
91             return Ok(Some(self.mk_stmt(lo.to(item.span), StmtKind::Item(item))));
92         }
93
94         // Do not attempt to parse an expression if we're done here.
95         if self.token == token::Semi {
96             self.error_outer_attrs(&attrs);
97             self.bump();
98             let mut last_semi = lo;
99             while self.token == token::Semi {
100                 last_semi = self.token.span;
101                 self.bump();
102             }
103             // We are encoding a string of semicolons as an an empty tuple that spans
104             // the excess semicolons to preserve this info until the lint stage.
105             let kind = StmtKind::Semi(self.mk_expr(
106                 lo.to(last_semi),
107                 ExprKind::Tup(Vec::new()),
108                 AttrVec::new(),
109             ));
110             return Ok(Some(self.mk_stmt(lo.to(last_semi), kind)));
111         }
112
113         if self.token == token::CloseDelim(token::Brace) {
114             self.error_outer_attrs(&attrs);
115             return Ok(None);
116         }
117
118         // Remainder are line-expr stmts.
119         let e = self.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs.into()))?;
120         Ok(Some(self.mk_stmt(lo.to(e.span), StmtKind::Expr(e))))
121     }
122
123     /// Parses a statement macro `mac!(args)` provided a `path` representing `mac`.
124     /// At this point, the `!` token after the path has already been eaten.
125     fn parse_stmt_mac(
126         &mut self,
127         lo: Span,
128         attrs: AttrVec,
129         path: ast::Path,
130         legacy_warnings: bool,
131     ) -> PResult<'a, Option<Stmt>> {
132         let args = self.parse_mac_args()?;
133         let delim = args.delim();
134         let hi = self.prev_span;
135
136         let style =
137             if delim == token::Brace { MacStmtStyle::Braces } else { MacStmtStyle::NoBraces };
138
139         let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription };
140
141         let kind = if delim == token::Brace || self.token == token::Semi || self.token == token::Eof
142         {
143             StmtKind::Mac(P((mac, style, attrs.into())))
144         }
145         // We used to incorrectly stop parsing macro-expanded statements here.
146         // If the next token will be an error anyway but could have parsed with the
147         // earlier behavior, stop parsing here and emit a warning to avoid breakage.
148         else if legacy_warnings
149             && self.token.can_begin_expr()
150             && match self.token.kind {
151                 // These can continue an expression, so we can't stop parsing and warn.
152                 token::OpenDelim(token::Paren)
153                 | token::OpenDelim(token::Bracket)
154                 | token::BinOp(token::Minus)
155                 | token::BinOp(token::Star)
156                 | token::BinOp(token::And)
157                 | token::BinOp(token::Or)
158                 | token::AndAnd
159                 | token::OrOr
160                 | token::DotDot
161                 | token::DotDotDot
162                 | token::DotDotEq => false,
163                 _ => true,
164             }
165         {
166             self.warn_missing_semicolon();
167             StmtKind::Mac(P((mac, style, attrs)))
168         } else {
169             // Since none of the above applied, this is an expression statement macro.
170             let e = self.mk_expr(lo.to(hi), ExprKind::Mac(mac), AttrVec::new());
171             let e = self.maybe_recover_from_bad_qpath(e, true)?;
172             let e = self.parse_dot_or_call_expr_with(e, lo, attrs)?;
173             let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
174             StmtKind::Expr(e)
175         };
176         Ok(Some(self.mk_stmt(lo.to(hi), kind)))
177     }
178
179     /// Error on outer attributes in this context.
180     /// Also error if the previous token was a doc comment.
181     fn error_outer_attrs(&self, attrs: &[Attribute]) {
182         if !attrs.is_empty() {
183             if matches!(self.prev_token.kind, TokenKind::DocComment(..)) {
184                 self.span_fatal_err(self.prev_span, Error::UselessDocComment).emit();
185             } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
186                 self.struct_span_err(self.token.span, "expected statement after outer attribute")
187                     .emit();
188             }
189         }
190     }
191
192     fn recover_stmt_local(
193         &mut self,
194         lo: Span,
195         attrs: AttrVec,
196         msg: &str,
197         sugg: &str,
198     ) -> PResult<'a, Option<Stmt>> {
199         let stmt = self.parse_local_mk(lo, attrs)?;
200         self.struct_span_err(lo, "invalid variable declaration")
201             .span_suggestion(lo, msg, sugg.to_string(), Applicability::MachineApplicable)
202             .emit();
203         Ok(Some(stmt))
204     }
205
206     fn parse_local_mk(&mut self, lo: Span, attrs: AttrVec) -> PResult<'a, Stmt> {
207         let local = self.parse_local(attrs.into())?;
208         Ok(self.mk_stmt(lo.to(self.prev_span), StmtKind::Local(local)))
209     }
210
211     /// Parses a local variable declaration.
212     fn parse_local(&mut self, attrs: AttrVec) -> PResult<'a, P<Local>> {
213         let lo = self.prev_span;
214         let pat = self.parse_top_pat(GateOr::Yes)?;
215
216         let (err, ty) = if self.eat(&token::Colon) {
217             // Save the state of the parser before parsing type normally, in case there is a `:`
218             // instead of an `=` typo.
219             let parser_snapshot_before_type = self.clone();
220             let colon_sp = self.prev_span;
221             match self.parse_ty() {
222                 Ok(ty) => (None, Some(ty)),
223                 Err(mut err) => {
224                     // Rewind to before attempting to parse the type and continue parsing.
225                     let parser_snapshot_after_type = self.clone();
226                     mem::replace(self, parser_snapshot_before_type);
227
228                     let snippet = self.span_to_snippet(pat.span).unwrap();
229                     err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
230                     (Some((parser_snapshot_after_type, colon_sp, err)), None)
231                 }
232             }
233         } else {
234             (None, None)
235         };
236         let init = match (self.parse_initializer(err.is_some()), err) {
237             (Ok(init), None) => {
238                 // init parsed, ty parsed
239                 init
240             }
241             (Ok(init), Some((_, colon_sp, mut err))) => {
242                 // init parsed, ty error
243                 // Could parse the type as if it were the initializer, it is likely there was a
244                 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
245                 err.span_suggestion_short(
246                     colon_sp,
247                     "use `=` if you meant to assign",
248                     " =".to_string(),
249                     Applicability::MachineApplicable,
250                 );
251                 err.emit();
252                 // As this was parsed successfully, continue as if the code has been fixed for the
253                 // rest of the file. It will still fail due to the emitted error, but we avoid
254                 // extra noise.
255                 init
256             }
257             (Err(mut init_err), Some((snapshot, _, ty_err))) => {
258                 // init error, ty error
259                 init_err.cancel();
260                 // Couldn't parse the type nor the initializer, only raise the type error and
261                 // return to the parser state before parsing the type as the initializer.
262                 // let x: <parse_error>;
263                 mem::replace(self, snapshot);
264                 return Err(ty_err);
265             }
266             (Err(err), None) => {
267                 // init error, ty parsed
268                 // Couldn't parse the initializer and we're not attempting to recover a failed
269                 // parse of the type, return the error.
270                 return Err(err);
271             }
272         };
273         let hi = if self.token == token::Semi { self.token.span } else { self.prev_span };
274         Ok(P(ast::Local { ty, pat, init, id: DUMMY_NODE_ID, span: lo.to(hi), attrs }))
275     }
276
277     /// Parses the RHS of a local variable declaration (e.g., '= 14;').
278     fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
279         if self.eat(&token::Eq) {
280             Ok(Some(self.parse_expr()?))
281         } else if skip_eq {
282             Ok(Some(self.parse_expr()?))
283         } else {
284             Ok(None)
285         }
286     }
287
288     /// Parses a block. No inner attributes are allowed.
289     pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
290         maybe_whole!(self, NtBlock, |x| x);
291
292         let lo = self.token.span;
293
294         if !self.eat(&token::OpenDelim(token::Brace)) {
295             return self.error_block_no_opening_brace();
296         }
297
298         self.parse_block_tail(lo, BlockCheckMode::Default)
299     }
300
301     fn error_block_no_opening_brace<T>(&mut self) -> PResult<'a, T> {
302         let sp = self.token.span;
303         let tok = super::token_descr(&self.token);
304         let mut e = self.struct_span_err(sp, &format!("expected `{{`, found {}", tok));
305         let do_not_suggest_help = self.token.is_keyword(kw::In) || self.token == token::Colon;
306
307         // Check to see if the user has written something like
308         //
309         //    if (cond)
310         //      bar;
311         //
312         // which is valid in other languages, but not Rust.
313         match self.parse_stmt_without_recovery(false) {
314             Ok(Some(stmt)) => {
315                 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
316                     || do_not_suggest_help
317                 {
318                     // If the next token is an open brace (e.g., `if a b {`), the place-
319                     // inside-a-block suggestion would be more likely wrong than right.
320                     e.span_label(sp, "expected `{`");
321                     return Err(e);
322                 }
323                 let stmt_span = if self.eat(&token::Semi) {
324                     // Expand the span to include the semicolon.
325                     stmt.span.with_hi(self.prev_span.hi())
326                 } else {
327                     stmt.span
328                 };
329                 if let Ok(snippet) = self.span_to_snippet(stmt_span) {
330                     e.span_suggestion(
331                         stmt_span,
332                         "try placing this code inside a block",
333                         format!("{{ {} }}", snippet),
334                         // Speculative; has been misleading in the past (#46836).
335                         Applicability::MaybeIncorrect,
336                     );
337                 }
338             }
339             Err(mut e) => {
340                 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
341                 e.cancel();
342             }
343             _ => {}
344         }
345         e.span_label(sp, "expected `{`");
346         return Err(e);
347     }
348
349     /// Parses a block. Inner attributes are allowed.
350     pub(super) fn parse_inner_attrs_and_block(
351         &mut self,
352     ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
353         maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
354
355         let lo = self.token.span;
356         self.expect(&token::OpenDelim(token::Brace))?;
357         Ok((self.parse_inner_attributes()?, self.parse_block_tail(lo, BlockCheckMode::Default)?))
358     }
359
360     /// Parses the rest of a block expression or function body.
361     /// Precondition: already parsed the '{'.
362     pub(super) fn parse_block_tail(
363         &mut self,
364         lo: Span,
365         s: BlockCheckMode,
366     ) -> PResult<'a, P<Block>> {
367         let mut stmts = vec![];
368         while !self.eat(&token::CloseDelim(token::Brace)) {
369             if self.token == token::Eof {
370                 break;
371             }
372             let stmt = match self.parse_full_stmt(false) {
373                 Err(mut err) => {
374                     self.maybe_annotate_with_ascription(&mut err, false);
375                     err.emit();
376                     self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
377                     Some(self.mk_stmt_err(self.token.span))
378                 }
379                 Ok(stmt) => stmt,
380             };
381             if let Some(stmt) = stmt {
382                 stmts.push(stmt);
383             } else {
384                 // Found only `;` or `}`.
385                 continue;
386             };
387         }
388         Ok(self.mk_block(stmts, s, lo.to(self.prev_span)))
389     }
390
391     /// Parses a statement, including the trailing semicolon.
392     pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
393         // Skip looking for a trailing semicolon when we have an interpolated statement.
394         maybe_whole!(self, NtStmt, |x| Some(x));
395
396         let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
397             Some(stmt) => stmt,
398             None => return Ok(None),
399         };
400
401         let mut eat_semi = true;
402         match stmt.kind {
403             StmtKind::Expr(ref expr) if self.token != token::Eof => {
404                 // expression without semicolon
405                 if classify::expr_requires_semi_to_be_stmt(expr) {
406                     // Just check for errors and recover; do not eat semicolon yet.
407                     if let Err(mut e) =
408                         self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
409                     {
410                         if let TokenKind::DocComment(..) = self.token.kind {
411                             if let Ok(snippet) = self.span_to_snippet(self.token.span) {
412                                 let sp = self.token.span;
413                                 let marker = &snippet[..3];
414                                 let (comment_marker, doc_comment_marker) = marker.split_at(2);
415
416                                 e.span_suggestion(
417                                     sp.with_hi(sp.lo() + BytePos(marker.len() as u32)),
418                                     &format!(
419                                         "add a space before `{}` to use a regular comment",
420                                         doc_comment_marker,
421                                     ),
422                                     format!("{} {}", comment_marker, doc_comment_marker),
423                                     Applicability::MaybeIncorrect,
424                                 );
425                             }
426                         }
427                         e.emit();
428                         self.recover_stmt();
429                         // Don't complain about type errors in body tail after parse error (#57383).
430                         let sp = expr.span.to(self.prev_span);
431                         stmt.kind = StmtKind::Expr(self.mk_expr_err(sp));
432                     }
433                 }
434             }
435             StmtKind::Local(..) => {
436                 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
437                 if macro_legacy_warnings && self.token != token::Semi {
438                     self.warn_missing_semicolon();
439                 } else {
440                     self.expect_semi()?;
441                     eat_semi = false;
442                 }
443             }
444             _ => {}
445         }
446
447         if eat_semi && self.eat(&token::Semi) {
448             stmt = stmt.add_trailing_semicolon();
449         }
450         stmt.span = stmt.span.to(self.prev_span);
451         Ok(Some(stmt))
452     }
453
454     fn warn_missing_semicolon(&self) {
455         self.diagnostic()
456             .struct_span_warn(self.token.span, {
457                 &format!("expected `;`, found {}", super::token_descr(&self.token))
458             })
459             .note({
460                 "this was erroneously allowed and will become a hard error in a future release"
461             })
462             .emit();
463     }
464
465     pub(super) fn mk_block(&self, stmts: Vec<Stmt>, rules: BlockCheckMode, span: Span) -> P<Block> {
466         P(Block { stmts, id: DUMMY_NODE_ID, rules, span })
467     }
468
469     pub(super) fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt {
470         Stmt { id: DUMMY_NODE_ID, kind, span }
471     }
472
473     fn mk_stmt_err(&self, span: Span) -> Stmt {
474         self.mk_stmt(span, StmtKind::Expr(self.mk_expr_err(span)))
475     }
476
477     pub(super) fn mk_block_err(&self, span: Span) -> P<Block> {
478         self.mk_block(vec![self.mk_stmt_err(span)], BlockCheckMode::Default, span)
479     }
480 }