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