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