]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/stmt.rs
3d2773cdc307936c4ac0c415e342c888eccab94b
[rust.git] / src / librustc_parse / parser / stmt.rs
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;
8
9 use rustc_errors::{PResult, Applicability};
10 use syntax::ThinVec;
11 use syntax::ptr::P;
12 use syntax::ast;
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;
16 use syntax::token;
17 use syntax_pos::source_map::{respan, Span};
18 use syntax_pos::symbol::{kw, sym};
19
20 use std::mem;
21
22 impl<'a> Parser<'a> {
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| {
27             e.emit();
28             self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
29             None
30         }))
31     }
32
33     fn parse_stmt_without_recovery(
34         &mut self,
35         macro_legacy_warnings: bool,
36     ) -> PResult<'a, Option<Stmt>> {
37         maybe_whole!(self, NtStmt, |x| Some(x));
38
39         let attrs = self.parse_outer_attributes()?;
40         let lo = self.token.span;
41
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(
46             &attrs,
47             &respan(lo, VisibilityKind::Inherited),
48             lo,
49         )? {
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()
61         {
62             let path = self.parse_path(PathStyle::Expr)?;
63
64             if self.eat(&token::Not) {
65                 return self.parse_stmt_mac(lo, attrs.into(), path, macro_legacy_warnings);
66             }
67
68             let expr = if self.check(&token::OpenDelim(token::Brace)) {
69                 self.parse_struct_expr(lo, path, ThinVec::new())?
70             } else {
71                 let hi = self.prev_span;
72                 self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new())
73             };
74
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))
78             })?;
79             return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Expr(expr))));
80         } else {
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;
86
87             if let Some(item) = item {
88                 return Ok(Some(self.mk_stmt(lo.to(item.span), StmtKind::Item(item))));
89             }
90
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) {
96                         s.span_err(
97                             s.token.span, "expected statement after outer attribute"
98                         );
99                     }
100                 }
101             };
102
103             // Do not attempt to parse an expression if we're done here.
104             if self.token == token::Semi {
105                 unused_attrs(&attrs, self);
106                 self.bump();
107                 let mut last_semi = lo;
108                 while self.token == token::Semi {
109                     last_semi = self.token.span;
110                     self.bump();
111                 }
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(
116                     lo.to(last_semi),
117                     ExprKind::Tup(Vec::new()),
118                     ThinVec::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                 unused_attrs(&attrs, self);
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             self.mk_stmt(lo.to(e.span), StmtKind::Expr(e))
131         }))
132     }
133
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.
136     fn parse_stmt_mac(
137         &mut self,
138         lo: Span,
139         attrs: ThinVec<Attribute>,
140         path: ast::Path,
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;
146
147         let style = if delim == token::Brace {
148             MacStmtStyle::Braces
149         } else {
150             MacStmtStyle::NoBraces
151         };
152
153         let mac = Mac {
154             path,
155             args,
156             prior_type_ascription: self.last_type_ascription,
157         };
158
159         let kind = if delim == token::Brace
160             || self.token == token::Semi
161             || self.token == token::Eof
162         {
163             StmtKind::Mac(P((mac, style, attrs.into())))
164         }
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,
177                 _ => true,
178             }
179         {
180             self.warn_missing_semicolon();
181             StmtKind::Mac(P((mac, style, attrs)))
182         } else {
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))?;
188             StmtKind::Expr(e)
189         };
190         Ok(Some(self.mk_stmt(lo.to(hi), kind)))
191     }
192
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)?;
197
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)),
205                 Err(mut err) => {
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);
209
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)
213                 }
214             }
215         } else {
216             (None, None)
217         };
218         let init = match (self.parse_initializer(err.is_some()), err) {
219             (Ok(init), None) => {  // init parsed, ty parsed
220                 init
221             }
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(
226                     colon_sp,
227                     "use `=` if you meant to assign",
228                     " =".to_string(),
229                     Applicability::MachineApplicable
230                 );
231                 err.emit();
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
234                 // extra noise.
235                 init
236             }
237             (Err(mut init_err), Some((snapshot, _, ty_err))) => {  // init error, ty error
238                 init_err.cancel();
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);
243                 return Err(ty_err);
244             }
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.
248                 return Err(err);
249             }
250         };
251         let hi = if self.token == token::Semi {
252             self.token.span
253         } else {
254             self.prev_span
255         };
256         Ok(P(ast::Local {
257             ty,
258             pat,
259             init,
260             id: DUMMY_NODE_ID,
261             span: lo.to(hi),
262             attrs,
263         }))
264     }
265
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()?))
270         } else if skip_eq {
271             Ok(Some(self.parse_expr()?))
272         } else {
273             Ok(None)
274         }
275     }
276
277     fn is_auto_trait_item(&self) -> bool {
278         // auto trait
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]))
285     }
286
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);
290
291         let lo = self.token.span;
292
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;
299
300             if self.token.is_ident_named(sym::and) {
301                 e.span_suggestion_short(
302                     self.token.span,
303                     "use `&&` instead of `and` for the boolean operator",
304                     "&&".to_string(),
305                     Applicability::MaybeIncorrect,
306                 );
307             }
308             if self.token.is_ident_named(sym::or) {
309                 e.span_suggestion_short(
310                     self.token.span,
311                     "use `||` instead of `or` for the boolean operator",
312                     "||".to_string(),
313                     Applicability::MaybeIncorrect,
314                 );
315             }
316
317             // Check to see if the user has written something like
318             //
319             //    if (cond)
320             //      bar;
321             //
322             // which is valid in other languages, but not Rust.
323             match self.parse_stmt_without_recovery(false) {
324                 Ok(Some(stmt)) => {
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 `{`");
330                         return Err(e);
331                     }
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());
336                     }
337                     if let Ok(snippet) = self.span_to_snippet(stmt_span) {
338                         e.span_suggestion(
339                             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,
344                         );
345                     }
346                 }
347                 Err(mut e) => {
348                     self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
349                     e.cancel();
350                 }
351                 _ => ()
352             }
353             e.span_label(sp, "expected `{`");
354             return Err(e);
355         }
356
357         self.parse_block_tail(lo, BlockCheckMode::Default)
358     }
359
360     /// Parses a block. Inner attributes are allowed.
361     pub(super) fn parse_inner_attrs_and_block(
362         &mut self
363     ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
364         maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
365
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)?))
370     }
371
372     /// Parses the rest of a block expression or function body.
373     /// Precondition: already parsed the '{'.
374     pub(super) fn parse_block_tail(
375         &mut self,
376         lo: Span,
377         s: BlockCheckMode
378     ) -> PResult<'a, P<Block>> {
379         let mut stmts = vec![];
380         while !self.eat(&token::CloseDelim(token::Brace)) {
381             if self.token == token::Eof {
382                 break;
383             }
384             let stmt = match self.parse_full_stmt(false) {
385                 Err(mut err) => {
386                     self.maybe_annotate_with_ascription(&mut err, false);
387                     err.emit();
388                     self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
389                     Some(self.mk_stmt(
390                         self.token.span,
391                         StmtKind::Expr(self.mk_expr_err(self.token.span)),
392                     ))
393                 }
394                 Ok(stmt) => stmt,
395             };
396             if let Some(stmt) = stmt {
397                 stmts.push(stmt);
398             } else {
399                 // Found only `;` or `}`.
400                 continue;
401             };
402         }
403         Ok(P(ast::Block {
404             stmts,
405             id: DUMMY_NODE_ID,
406             rules: s,
407             span: lo.to(self.prev_span),
408         }))
409     }
410
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));
415
416         let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
417             Some(stmt) => stmt,
418             None => return Ok(None),
419         };
420
421         let mut eat_semi = true;
422         match stmt.kind {
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.
427                     if let Err(mut e) =
428                         self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
429                     {
430                         e.emit();
431                         self.recover_stmt();
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));
435                     }
436                 }
437             }
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();
442                 } else {
443                     self.expect_semi()?;
444                     eat_semi = false;
445                 }
446             }
447             _ => {}
448         }
449
450         if eat_semi && self.eat(&token::Semi) {
451             stmt = stmt.add_trailing_semicolon();
452         }
453         stmt.span = stmt.span.to(self.prev_span);
454         Ok(Some(stmt))
455     }
456
457     fn warn_missing_semicolon(&self) {
458         self.diagnostic().struct_span_warn(self.token.span, {
459             &format!("expected `;`, found {}", self.this_token_descr())
460         }).note({
461             "this was erroneously allowed and will become a hard error in a future release"
462         }).emit();
463     }
464
465     fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt {
466         Stmt { id: DUMMY_NODE_ID, kind, span }
467     }
468 }