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