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