]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/stmt.rs
Recover from a misplaced inner doc comment
[rust.git] / compiler / rustc_parse / src / parser / stmt.rs
1 use super::attr::DEFAULT_INNER_ATTR_FORBIDDEN;
2 use super::diagnostics::{AttemptLocalParseRecovery, Error};
3 use super::expr::LhsExpr;
4 use super::pat::RecoverComma;
5 use super::path::PathStyle;
6 use super::TrailingToken;
7 use super::{AttrWrapper, BlockMode, ForceCollect, Parser, Restrictions, SemiColonMode};
8 use crate::maybe_whole;
9
10 use rustc_ast as ast;
11 use rustc_ast::ptr::P;
12 use rustc_ast::token::{self, TokenKind};
13 use rustc_ast::util::classify;
14 use rustc_ast::AstLike;
15 use rustc_ast::{AttrStyle, AttrVec, Attribute, MacCall, MacCallStmt, MacStmtStyle};
16 use rustc_ast::{Block, BlockCheckMode, Expr, ExprKind, Local, Stmt};
17 use rustc_ast::{StmtKind, DUMMY_NODE_ID};
18 use rustc_errors::{Applicability, PResult};
19 use rustc_span::source_map::{BytePos, Span};
20 use rustc_span::symbol::{kw, sym};
21
22 use std::mem;
23
24 impl<'a> Parser<'a> {
25     /// Parses a statement. This stops just before trailing semicolons on everything but items.
26     /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
27     // Public for rustfmt usage.
28     pub fn parse_stmt(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<Stmt>> {
29         Ok(self.parse_stmt_without_recovery(false, force_collect).unwrap_or_else(|mut e| {
30             e.emit();
31             self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
32             None
33         }))
34     }
35
36     /// If `force_capture` is true, forces collection of tokens regardless of whether
37     /// or not we have attributes
38     crate fn parse_stmt_without_recovery(
39         &mut self,
40         capture_semi: bool,
41         force_collect: ForceCollect,
42     ) -> PResult<'a, Option<Stmt>> {
43         let attrs = self.parse_outer_attributes()?;
44         let lo = self.token.span;
45
46         // Don't use `maybe_whole` so that we have precise control
47         // over when we bump the parser
48         if let token::Interpolated(nt) = &self.token.kind {
49             if let token::NtStmt(stmt) = &**nt {
50                 let mut stmt = stmt.clone();
51                 self.bump();
52                 stmt.visit_attrs(|stmt_attrs| {
53                     attrs.prepend_to_nt_inner(stmt_attrs);
54                 });
55                 return Ok(Some(stmt));
56             }
57         }
58
59         Ok(Some(if self.token.is_keyword(kw::Let) {
60             self.parse_local_mk(lo, attrs, capture_semi, force_collect)?
61         } else if self.is_kw_followed_by_ident(kw::Mut) {
62             self.recover_stmt_local(lo, attrs, "missing keyword", "let mut")?
63         } else if self.is_kw_followed_by_ident(kw::Auto) {
64             self.bump(); // `auto`
65             let msg = "write `let` instead of `auto` to introduce a new variable";
66             self.recover_stmt_local(lo, attrs, msg, "let")?
67         } else if self.is_kw_followed_by_ident(sym::var) {
68             self.bump(); // `var`
69             let msg = "write `let` instead of `var` to introduce a new variable";
70             self.recover_stmt_local(lo, attrs, msg, "let")?
71         } else if self.check_path() && !self.token.is_qpath_start() && !self.is_path_start_item() {
72             // We have avoided contextual keywords like `union`, items with `crate` visibility,
73             // or `auto trait` items. We aim to parse an arbitrary path `a::b` but not something
74             // that starts like a path (1 token), but it fact not a path.
75             // Also, we avoid stealing syntax from `parse_item_`.
76             if force_collect == ForceCollect::Yes {
77                 self.collect_tokens_no_attrs(|this| this.parse_stmt_path_start(lo, attrs))
78             } else {
79                 self.parse_stmt_path_start(lo, attrs)
80             }?
81         } else if let Some(item) =
82             self.parse_item_common(attrs.clone(), false, true, |_| true, force_collect)?
83         {
84             // FIXME: Bad copy of attrs
85             self.mk_stmt(lo.to(item.span), StmtKind::Item(P(item)))
86         } else if self.eat(&token::Semi) {
87             // Do not attempt to parse an expression if we're done here.
88             self.error_outer_attrs(&attrs.take_for_recovery());
89             self.mk_stmt(lo, StmtKind::Empty)
90         } else if self.token != token::CloseDelim(token::Brace) {
91             // Remainder are line-expr stmts.
92             let e = if force_collect == ForceCollect::Yes {
93                 self.collect_tokens_no_attrs(|this| {
94                     this.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs))
95                 })
96             } else {
97                 self.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs))
98             }?;
99             self.mk_stmt(lo.to(e.span), StmtKind::Expr(e))
100         } else {
101             self.error_outer_attrs(&attrs.take_for_recovery());
102             return Ok(None);
103         }))
104     }
105
106     fn parse_stmt_path_start(&mut self, lo: Span, attrs: AttrWrapper) -> PResult<'a, Stmt> {
107         let stmt = self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
108             let path = this.parse_path(PathStyle::Expr)?;
109
110             if this.eat(&token::Not) {
111                 let stmt_mac = this.parse_stmt_mac(lo, attrs.into(), path)?;
112                 if this.token == token::Semi {
113                     return Ok((stmt_mac, TrailingToken::Semi));
114                 } else {
115                     return Ok((stmt_mac, TrailingToken::None));
116                 }
117             }
118
119             let expr = if this.eat(&token::OpenDelim(token::Brace)) {
120                 this.parse_struct_expr(None, path, AttrVec::new(), true)?
121             } else {
122                 let hi = this.prev_token.span;
123                 this.mk_expr(lo.to(hi), ExprKind::Path(None, path), AttrVec::new())
124             };
125
126             let expr = this.with_res(Restrictions::STMT_EXPR, |this| {
127                 this.parse_dot_or_call_expr_with(expr, lo, attrs)
128             })?;
129             // `DUMMY_SP` will get overwritten later in this function
130             Ok((this.mk_stmt(rustc_span::DUMMY_SP, StmtKind::Expr(expr)), TrailingToken::None))
131         })?;
132
133         if let StmtKind::Expr(expr) = stmt.kind {
134             // Perform this outside of the `collect_tokens_trailing_token` closure,
135             // since our outer attributes do not apply to this part of the expression
136             let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
137                 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
138             })?;
139             Ok(self.mk_stmt(lo.to(self.prev_token.span), StmtKind::Expr(expr)))
140         } else {
141             Ok(stmt)
142         }
143     }
144
145     /// Parses a statement macro `mac!(args)` provided a `path` representing `mac`.
146     /// At this point, the `!` token after the path has already been eaten.
147     fn parse_stmt_mac(&mut self, lo: Span, attrs: AttrVec, path: ast::Path) -> PResult<'a, Stmt> {
148         let args = self.parse_mac_args()?;
149         let delim = args.delim();
150         let hi = self.prev_token.span;
151
152         let style =
153             if delim == token::Brace { MacStmtStyle::Braces } else { MacStmtStyle::NoBraces };
154
155         let mac = MacCall { path, args, prior_type_ascription: self.last_type_ascription };
156
157         let kind = if delim == token::Brace || self.token == token::Semi || self.token == token::Eof
158         {
159             StmtKind::MacCall(P(MacCallStmt { mac, style, attrs, tokens: None }))
160         } else {
161             // Since none of the above applied, this is an expression statement macro.
162             let e = self.mk_expr(lo.to(hi), ExprKind::MacCall(mac), AttrVec::new());
163             let e = self.maybe_recover_from_bad_qpath(e, true)?;
164             let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
165             let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
166             StmtKind::Expr(e)
167         };
168         Ok(self.mk_stmt(lo.to(hi), kind))
169     }
170
171     /// Error on outer attributes in this context.
172     /// Also error if the previous token was a doc comment.
173     fn error_outer_attrs(&self, attrs: &[Attribute]) {
174         if let [.., last] = attrs {
175             if last.is_doc_comment() {
176                 self.span_err(last.span, Error::UselessDocComment).emit();
177             } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
178                 self.struct_span_err(last.span, "expected statement after outer attribute").emit();
179             }
180         }
181     }
182
183     fn recover_stmt_local(
184         &mut self,
185         lo: Span,
186         attrs: AttrWrapper,
187         msg: &str,
188         sugg: &str,
189     ) -> PResult<'a, Stmt> {
190         let stmt = self.recover_local_after_let(lo, attrs)?;
191         self.struct_span_err(lo, "invalid variable declaration")
192             .span_suggestion(lo, msg, sugg.to_string(), Applicability::MachineApplicable)
193             .emit();
194         Ok(stmt)
195     }
196
197     fn parse_local_mk(
198         &mut self,
199         lo: Span,
200         attrs: AttrWrapper,
201         capture_semi: bool,
202         force_collect: ForceCollect,
203     ) -> PResult<'a, Stmt> {
204         self.collect_tokens_trailing_token(attrs, force_collect, |this, attrs| {
205             this.expect_keyword(kw::Let)?;
206             let local = this.parse_local(attrs.into())?;
207             let trailing = if capture_semi && this.token.kind == token::Semi {
208                 TrailingToken::Semi
209             } else {
210                 TrailingToken::None
211             };
212             Ok((this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Local(local)), trailing))
213         })
214     }
215
216     fn recover_local_after_let(&mut self, lo: Span, attrs: AttrWrapper) -> PResult<'a, Stmt> {
217         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
218             let local = this.parse_local(attrs.into())?;
219             // FIXME - maybe capture semicolon in recovery?
220             Ok((
221                 this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Local(local)),
222                 TrailingToken::None,
223             ))
224         })
225     }
226
227     /// Parses a local variable declaration.
228     fn parse_local(&mut self, attrs: AttrVec) -> PResult<'a, P<Local>> {
229         let lo = self.prev_token.span;
230         let (pat, colon) = self.parse_pat_before_ty(None, RecoverComma::Yes, "`let` bindings")?;
231
232         let (err, ty) = if colon {
233             // Save the state of the parser before parsing type normally, in case there is a `:`
234             // instead of an `=` typo.
235             let parser_snapshot_before_type = self.clone();
236             let colon_sp = self.prev_token.span;
237             match self.parse_ty() {
238                 Ok(ty) => (None, Some(ty)),
239                 Err(mut err) => {
240                     if let Ok(snip) = self.span_to_snippet(pat.span) {
241                         err.span_label(pat.span, format!("while parsing the type for `{}`", snip));
242                     }
243                     let err = if self.check(&token::Eq) {
244                         err.emit();
245                         None
246                     } else {
247                         // Rewind to before attempting to parse the type and continue parsing.
248                         let parser_snapshot_after_type =
249                             mem::replace(self, parser_snapshot_before_type);
250                         Some((parser_snapshot_after_type, colon_sp, err))
251                     };
252                     (err, None)
253                 }
254             }
255         } else {
256             (None, None)
257         };
258         let init = match (self.parse_initializer(err.is_some()), err) {
259             (Ok(init), None) => {
260                 // init parsed, ty parsed
261                 init
262             }
263             (Ok(init), Some((_, colon_sp, mut err))) => {
264                 // init parsed, ty error
265                 // Could parse the type as if it were the initializer, it is likely there was a
266                 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
267                 err.span_suggestion_short(
268                     colon_sp,
269                     "use `=` if you meant to assign",
270                     " =".to_string(),
271                     Applicability::MachineApplicable,
272                 );
273                 err.emit();
274                 // As this was parsed successfully, continue as if the code has been fixed for the
275                 // rest of the file. It will still fail due to the emitted error, but we avoid
276                 // extra noise.
277                 init
278             }
279             (Err(mut init_err), Some((snapshot, _, ty_err))) => {
280                 // init error, ty error
281                 init_err.cancel();
282                 // Couldn't parse the type nor the initializer, only raise the type error and
283                 // return to the parser state before parsing the type as the initializer.
284                 // let x: <parse_error>;
285                 *self = snapshot;
286                 return Err(ty_err);
287             }
288             (Err(err), None) => {
289                 // init error, ty parsed
290                 // Couldn't parse the initializer and we're not attempting to recover a failed
291                 // parse of the type, return the error.
292                 return Err(err);
293             }
294         };
295         let hi = if self.token == token::Semi { self.token.span } else { self.prev_token.span };
296         Ok(P(ast::Local { ty, pat, init, id: DUMMY_NODE_ID, span: lo.to(hi), attrs, tokens: None }))
297     }
298
299     /// Parses the RHS of a local variable declaration (e.g., `= 14;`).
300     fn parse_initializer(&mut self, eq_optional: bool) -> PResult<'a, Option<P<Expr>>> {
301         let eq_consumed = match self.token.kind {
302             token::BinOpEq(..) => {
303                 // Recover `let x <op>= 1` as `let x = 1`
304                 self.struct_span_err(
305                     self.token.span,
306                     "can't reassign to an uninitialized variable",
307                 )
308                 .span_suggestion_short(
309                     self.token.span,
310                     "initialize the variable",
311                     "=".to_string(),
312                     Applicability::MaybeIncorrect,
313                 )
314                 .help("if you meant to overwrite, remove the `let` binding")
315                 .emit();
316                 self.bump();
317                 true
318             }
319             _ => self.eat(&token::Eq),
320         };
321
322         Ok(if eq_consumed || eq_optional { Some(self.parse_expr()?) } else { None })
323     }
324
325     /// Parses a block. No inner attributes are allowed.
326     pub(super) fn parse_block(&mut self) -> PResult<'a, P<Block>> {
327         let (attrs, block) = self.parse_inner_attrs_and_block()?;
328         if let [.., last] = &*attrs {
329             self.error_on_forbidden_inner_attr(last.span, DEFAULT_INNER_ATTR_FORBIDDEN);
330         }
331         Ok(block)
332     }
333
334     fn error_block_no_opening_brace<T>(&mut self) -> PResult<'a, T> {
335         let sp = self.token.span;
336         let tok = super::token_descr(&self.token);
337         let mut e = self.struct_span_err(sp, &format!("expected `{{`, found {}", tok));
338         let do_not_suggest_help = self.token.is_keyword(kw::In) || self.token == token::Colon;
339
340         // Check to see if the user has written something like
341         //
342         //    if (cond)
343         //      bar;
344         //
345         // which is valid in other languages, but not Rust.
346         match self.parse_stmt_without_recovery(false, ForceCollect::No) {
347             // If the next token is an open brace (e.g., `if a b {`), the place-
348             // inside-a-block suggestion would be more likely wrong than right.
349             Ok(Some(_))
350                 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
351                     || do_not_suggest_help => {}
352             Ok(Some(stmt)) => {
353                 let stmt_own_line = self.sess.source_map().is_line_before_span_empty(sp);
354                 let stmt_span = if stmt_own_line && self.eat(&token::Semi) {
355                     // Expand the span to include the semicolon.
356                     stmt.span.with_hi(self.prev_token.span.hi())
357                 } else {
358                     stmt.span
359                 };
360                 if let Ok(snippet) = self.span_to_snippet(stmt_span) {
361                     e.span_suggestion(
362                         stmt_span,
363                         "try placing this code inside a block",
364                         format!("{{ {} }}", snippet),
365                         // Speculative; has been misleading in the past (#46836).
366                         Applicability::MaybeIncorrect,
367                     );
368                 }
369             }
370             Err(mut e) => {
371                 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
372                 e.cancel();
373             }
374             _ => {}
375         }
376         e.span_label(sp, "expected `{`");
377         Err(e)
378     }
379
380     /// Parses a block. Inner attributes are allowed.
381     pub(super) fn parse_inner_attrs_and_block(
382         &mut self,
383     ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
384         self.parse_block_common(self.token.span, BlockCheckMode::Default)
385     }
386
387     /// Parses a block. Inner attributes are allowed.
388     pub(super) fn parse_block_common(
389         &mut self,
390         lo: Span,
391         blk_mode: BlockCheckMode,
392     ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
393         maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
394
395         if !self.eat(&token::OpenDelim(token::Brace)) {
396             return self.error_block_no_opening_brace();
397         }
398
399         let attrs = self.parse_inner_attributes()?;
400         let tail = if let Some(tail) = self.maybe_suggest_struct_literal(lo, blk_mode) {
401             tail?
402         } else {
403             self.parse_block_tail(lo, blk_mode, AttemptLocalParseRecovery::Yes)?
404         };
405         Ok((attrs, tail))
406     }
407
408     /// Parses the rest of a block expression or function body.
409     /// Precondition: already parsed the '{'.
410     crate fn parse_block_tail(
411         &mut self,
412         lo: Span,
413         s: BlockCheckMode,
414         recover: AttemptLocalParseRecovery,
415     ) -> PResult<'a, P<Block>> {
416         let mut stmts = vec![];
417         while !self.eat(&token::CloseDelim(token::Brace)) {
418             if self.token == token::Eof {
419                 break;
420             }
421             let stmt = match self.parse_full_stmt(recover) {
422                 Err(mut err) if recover.yes() => {
423                     self.maybe_annotate_with_ascription(&mut err, false);
424                     err.emit();
425                     self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
426                     Some(self.mk_stmt_err(self.token.span))
427                 }
428                 Ok(stmt) => stmt,
429                 Err(err) => return Err(err),
430             };
431             if let Some(stmt) = stmt {
432                 stmts.push(stmt);
433             } else {
434                 // Found only `;` or `}`.
435                 continue;
436             };
437         }
438         Ok(self.mk_block(stmts, s, lo.to(self.prev_token.span)))
439     }
440
441     /// Parses a statement, including the trailing semicolon.
442     pub fn parse_full_stmt(
443         &mut self,
444         recover: AttemptLocalParseRecovery,
445     ) -> PResult<'a, Option<Stmt>> {
446         // Skip looking for a trailing semicolon when we have an interpolated statement.
447         maybe_whole!(self, NtStmt, |x| Some(x));
448
449         let mut stmt = match self.parse_stmt_without_recovery(true, ForceCollect::No)? {
450             Some(stmt) => stmt,
451             None => return Ok(None),
452         };
453
454         let mut eat_semi = true;
455         match stmt.kind {
456             // Expression without semicolon.
457             StmtKind::Expr(ref mut expr)
458                 if self.token != token::Eof && classify::expr_requires_semi_to_be_stmt(expr) =>
459             {
460                 // Just check for errors and recover; do not eat semicolon yet.
461                 if let Err(mut e) =
462                     self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
463                 {
464                     if let TokenKind::DocComment(..) = self.token.kind {
465                         if let Ok(snippet) = self.span_to_snippet(self.token.span) {
466                             let sp = self.token.span;
467                             let marker = &snippet[..3];
468                             let (comment_marker, doc_comment_marker) = marker.split_at(2);
469
470                             e.span_suggestion(
471                                 sp.with_hi(sp.lo() + BytePos(marker.len() as u32)),
472                                 &format!(
473                                     "add a space before `{}` to use a regular comment",
474                                     doc_comment_marker,
475                                 ),
476                                 format!("{} {}", comment_marker, doc_comment_marker),
477                                 Applicability::MaybeIncorrect,
478                             );
479                         }
480                     }
481                     if let Err(mut e) =
482                         self.check_mistyped_turbofish_with_multiple_type_params(e, expr)
483                     {
484                         if recover.no() {
485                             return Err(e);
486                         }
487                         e.emit();
488                         self.recover_stmt();
489                     }
490                     // Don't complain about type errors in body tail after parse error (#57383).
491                     let sp = expr.span.to(self.prev_token.span);
492                     *expr = self.mk_expr_err(sp);
493                 }
494             }
495             StmtKind::Expr(_) | StmtKind::MacCall(_) => {}
496             StmtKind::Local(ref mut local) => {
497                 if let Err(e) = self.expect_semi() {
498                     // We might be at the `,` in `let x = foo<bar, baz>;`. Try to recover.
499                     match &mut local.init {
500                         Some(ref mut expr) => {
501                             self.check_mistyped_turbofish_with_multiple_type_params(e, expr)?;
502                             // We found `foo<bar, baz>`, have we fully recovered?
503                             self.expect_semi()?;
504                         }
505                         None => return Err(e),
506                     }
507                 }
508                 eat_semi = false;
509             }
510             StmtKind::Empty | StmtKind::Item(_) | StmtKind::Semi(_) => eat_semi = false,
511         }
512
513         if eat_semi && self.eat(&token::Semi) {
514             stmt = stmt.add_trailing_semicolon();
515         }
516         stmt.span = stmt.span.to(self.prev_token.span);
517         Ok(Some(stmt))
518     }
519
520     pub(super) fn mk_block(&self, stmts: Vec<Stmt>, rules: BlockCheckMode, span: Span) -> P<Block> {
521         P(Block { stmts, id: DUMMY_NODE_ID, rules, span, tokens: None })
522     }
523
524     pub(super) fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt {
525         Stmt { id: DUMMY_NODE_ID, kind, span }
526     }
527
528     pub(super) fn mk_stmt_err(&self, span: Span) -> Stmt {
529         self.mk_stmt(span, StmtKind::Expr(self.mk_expr_err(span)))
530     }
531
532     pub(super) fn mk_block_err(&self, span: Span) -> P<Block> {
533         self.mk_block(vec![self.mk_stmt_err(span)], BlockCheckMode::Default, span)
534     }
535 }