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