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