]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/stmt.rs
Auto merge of #68267 - estebank:lt-sugg, r=petrochenkov
[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, PrevTokenKind, 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, 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;
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         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))));
61         }
62
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()
73         {
74             let path = self.parse_path(PathStyle::Expr)?;
75
76             if self.eat(&token::Not) {
77                 return self.parse_stmt_mac(lo, attrs.into(), path, macro_legacy_warnings);
78             }
79
80             let expr = if self.check(&token::OpenDelim(token::Brace)) {
81                 self.parse_struct_expr(lo, path, AttrVec::new())?
82             } else {
83                 let hi = self.prev_span;
84                 self.mk_expr(lo.to(hi), ExprKind::Path(None, path), AttrVec::new())
85             };
86
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))
90             })?;
91             return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Expr(expr))));
92         }
93
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;
99
100         if let Some(item) = item {
101             return Ok(Some(self.mk_stmt(lo.to(item.span), StmtKind::Item(item))));
102         }
103
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);
107             self.bump();
108             let mut last_semi = lo;
109             while self.token == token::Semi {
110                 last_semi = self.token.span;
111                 self.bump();
112             }
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(
116                 lo.to(last_semi),
117                 ExprKind::Tup(Vec::new()),
118                 AttrVec::new(),
119             ));
120             return Ok(Some(self.mk_stmt(lo.to(last_semi), kind)));
121         }
122
123         if self.token == token::CloseDelim(token::Brace) {
124             self.error_outer_attrs(&attrs);
125             return Ok(None);
126         }
127
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))))
131     }
132
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.
135     fn parse_stmt_mac(
136         &mut self,
137         lo: Span,
138         attrs: AttrVec,
139         path: ast::Path,
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;
145
146         let style =
147             if delim == token::Brace { MacStmtStyle::Braces } else { MacStmtStyle::NoBraces };
148
149         let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription };
150
151         let kind = if delim == token::Brace || self.token == token::Semi || self.token == token::Eof
152         {
153             StmtKind::Mac(P((mac, style, attrs.into())))
154         }
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)
168                 | token::AndAnd
169                 | token::OrOr
170                 | token::DotDot
171                 | token::DotDotDot
172                 | token::DotDotEq => false,
173                 _ => true,
174             }
175         {
176             self.warn_missing_semicolon();
177             StmtKind::Mac(P((mac, style, attrs)))
178         } else {
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))?;
184             StmtKind::Expr(e)
185         };
186         Ok(Some(self.mk_stmt(lo.to(hi), kind)))
187     }
188
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")
197                     .emit();
198             }
199         }
200     }
201
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())
204     }
205
206     fn recover_stmt_local(
207         &mut self,
208         lo: Span,
209         attrs: AttrVec,
210         msg: &str,
211         sugg: &str,
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)
216             .emit();
217         Ok(Some(stmt))
218     }
219
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)))
223     }
224
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)?;
229
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)),
237                 Err(mut err) => {
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);
241
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)
245                 }
246             }
247         } else {
248             (None, None)
249         };
250         let init = match (self.parse_initializer(err.is_some()), err) {
251             (Ok(init), None) => {
252                 // init parsed, ty parsed
253                 init
254             }
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(
260                     colon_sp,
261                     "use `=` if you meant to assign",
262                     " =".to_string(),
263                     Applicability::MachineApplicable,
264                 );
265                 err.emit();
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
268                 // extra noise.
269                 init
270             }
271             (Err(mut init_err), Some((snapshot, _, ty_err))) => {
272                 // init error, ty error
273                 init_err.cancel();
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);
278                 return Err(ty_err);
279             }
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.
284                 return Err(err);
285             }
286         };
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 }))
289     }
290
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()?))
295         } else if skip_eq {
296             Ok(Some(self.parse_expr()?))
297         } else {
298             Ok(None)
299         }
300     }
301
302     fn is_auto_trait_item(&self) -> bool {
303         // auto trait
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]))
310     }
311
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);
315
316         let lo = self.token.span;
317
318         if !self.eat(&token::OpenDelim(token::Brace)) {
319             return self.error_block_no_opening_brace();
320         }
321
322         self.parse_block_tail(lo, BlockCheckMode::Default)
323     }
324
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;
330
331         // Check to see if the user has written something like
332         //
333         //    if (cond)
334         //      bar;
335         //
336         // which is valid in other languages, but not Rust.
337         match self.parse_stmt_without_recovery(false) {
338             Ok(Some(stmt)) => {
339                 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
340                     || do_not_suggest_help
341                 {
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 `{`");
345                     return Err(e);
346                 }
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())
350                 } else {
351                     stmt.span
352                 };
353                 if let Ok(snippet) = self.span_to_snippet(stmt_span) {
354                     e.span_suggestion(
355                         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,
360                     );
361                 }
362             }
363             Err(mut e) => {
364                 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
365                 e.cancel();
366             }
367             _ => {}
368         }
369         e.span_label(sp, "expected `{`");
370         return Err(e);
371     }
372
373     /// Parses a block. Inner attributes are allowed.
374     pub(super) fn parse_inner_attrs_and_block(
375         &mut self,
376     ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
377         maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
378
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)?))
382     }
383
384     /// Parses the rest of a block expression or function body.
385     /// Precondition: already parsed the '{'.
386     pub(super) fn parse_block_tail(
387         &mut self,
388         lo: Span,
389         s: BlockCheckMode,
390     ) -> PResult<'a, P<Block>> {
391         let mut stmts = vec![];
392         while !self.eat(&token::CloseDelim(token::Brace)) {
393             if self.token == token::Eof {
394                 break;
395             }
396             let stmt = match self.parse_full_stmt(false) {
397                 Err(mut err) => {
398                     self.maybe_annotate_with_ascription(&mut err, false);
399                     err.emit();
400                     self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
401                     Some(self.mk_stmt_err(self.token.span))
402                 }
403                 Ok(stmt) => stmt,
404             };
405             if let Some(stmt) = stmt {
406                 stmts.push(stmt);
407             } else {
408                 // Found only `;` or `}`.
409                 continue;
410             };
411         }
412         Ok(self.mk_block(stmts, s, lo.to(self.prev_span)))
413     }
414
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));
419
420         let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
421             Some(stmt) => stmt,
422             None => return Ok(None),
423         };
424
425         let mut eat_semi = true;
426         match stmt.kind {
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.
431                     if let Err(mut e) =
432                         self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
433                     {
434                         e.emit();
435                         self.recover_stmt();
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));
439                     }
440                 }
441             }
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();
446                 } else {
447                     self.expect_semi()?;
448                     eat_semi = false;
449                 }
450             }
451             _ => {}
452         }
453
454         if eat_semi && self.eat(&token::Semi) {
455             stmt = stmt.add_trailing_semicolon();
456         }
457         stmt.span = stmt.span.to(self.prev_span);
458         Ok(Some(stmt))
459     }
460
461     fn warn_missing_semicolon(&self) {
462         self.diagnostic()
463             .struct_span_warn(self.token.span, {
464                 &format!("expected `;`, found {}", super::token_descr(&self.token))
465             })
466             .note({
467                 "this was erroneously allowed and will become a hard error in a future release"
468             })
469             .emit();
470     }
471
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 })
474     }
475
476     pub(super) fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt {
477         Stmt { id: DUMMY_NODE_ID, kind, span }
478     }
479
480     fn mk_stmt_err(&self, span: Span) -> Stmt {
481         self.mk_stmt(span, StmtKind::Expr(self.mk_expr_err(span)))
482     }
483
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)
486     }
487 }