]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/stmt.rs
implement recovery in check_assoc_op
[rust.git] / src / librustc_parse / parser / stmt.rs
1 use super::{Parser, Restrictions, PrevTokenKind, SemiColonMode, BlockMode};
2 use super::expr::LhsExpr;
3 use super::path::PathStyle;
4 use super::pat::GateOr;
5 use super::diagnostics::Error;
6 use crate::maybe_whole;
7 use crate::DirectoryOwnership;
8
9 use rustc_errors::{PResult, Applicability};
10 use syntax::ThinVec;
11 use syntax::ptr::P;
12 use syntax::ast;
13 use syntax::ast::{DUMMY_NODE_ID, Stmt, StmtKind, Local, Block, BlockCheckMode, Expr, ExprKind};
14 use syntax::ast::{Attribute, AttrStyle, VisibilityKind, MacStmtStyle, Mac};
15 use syntax::util::classify;
16 use syntax::token;
17 use syntax_pos::source_map::{respan, Span};
18 use syntax_pos::symbol::kw;
19
20 use std::mem;
21
22 impl<'a> Parser<'a> {
23     /// Parses a statement. This stops just before trailing semicolons on everything but items.
24     /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
25     pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
26         Ok(self.parse_stmt_without_recovery(true).unwrap_or_else(|mut e| {
27             e.emit();
28             self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
29             None
30         }))
31     }
32
33     fn parse_stmt_without_recovery(
34         &mut self,
35         macro_legacy_warnings: bool,
36     ) -> PResult<'a, Option<Stmt>> {
37         maybe_whole!(self, NtStmt, |x| Some(x));
38
39         let attrs = self.parse_outer_attributes()?;
40         let lo = self.token.span;
41
42         if self.eat_keyword(kw::Let) {
43             let local = self.parse_local(attrs.into())?;
44             return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Local(local))));
45         }
46
47         let mac_vis = respan(lo, VisibilityKind::Inherited);
48         if let Some(macro_def) = self.eat_macro_def(&attrs, &mac_vis, lo)? {
49             return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Item(macro_def))));
50         }
51
52         // Starts like a simple path, being careful to avoid contextual keywords
53         // such as a union items, item with `crate` visibility or auto trait items.
54         // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
55         // like a path (1 token), but it fact not a path.
56         if self.token.is_path_start()
57             && !self.token.is_qpath_start()
58             && !self.is_union_item() // `union::b::c` - path, `union U { ... }` - not a path.
59             && !self.is_crate_vis() // `crate::b::c` - path, `crate struct S;` - not a path.
60             && !self.is_auto_trait_item()
61             && !self.is_async_fn()
62         {
63             let path = self.parse_path(PathStyle::Expr)?;
64
65             if self.eat(&token::Not) {
66                 return self.parse_stmt_mac(lo, attrs.into(), path, macro_legacy_warnings);
67             }
68
69             let expr = if self.check(&token::OpenDelim(token::Brace)) {
70                 self.parse_struct_expr(lo, path, ThinVec::new())?
71             } else {
72                 let hi = self.prev_span;
73                 self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new())
74             };
75
76             let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
77                 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
78                 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
79             })?;
80             return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Expr(expr))));
81         }
82
83         // FIXME: Bad copy of attrs
84         let old_directory_ownership =
85             mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
86         let item = self.parse_item_(attrs.clone(), false, true)?;
87         self.directory.ownership = old_directory_ownership;
88
89         if let Some(item) = item {
90             return Ok(Some(self.mk_stmt(lo.to(item.span), StmtKind::Item(item))));
91         }
92
93         // Do not attempt to parse an expression if we're done here.
94         if self.token == token::Semi {
95             self.error_outer_attrs(&attrs);
96             self.bump();
97             let mut last_semi = lo;
98             while self.token == token::Semi {
99                 last_semi = self.token.span;
100                 self.bump();
101             }
102             // We are encoding a string of semicolons as an an empty tuple that spans
103             // the excess semicolons to preserve this info until the lint stage.
104             let kind = StmtKind::Semi(self.mk_expr(
105                 lo.to(last_semi),
106                 ExprKind::Tup(Vec::new()),
107                 ThinVec::new()
108             ));
109             return Ok(Some(self.mk_stmt(lo.to(last_semi), kind)));
110         }
111
112         if self.token == token::CloseDelim(token::Brace) {
113             self.error_outer_attrs(&attrs);
114             return Ok(None);
115         }
116
117         // Remainder are line-expr stmts.
118         let e = self.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs.into()))?;
119         Ok(Some(self.mk_stmt(lo.to(e.span), StmtKind::Expr(e))))
120     }
121
122     /// Parses a statement macro `mac!(args)` provided a `path` representing `mac`.
123     /// At this point, the `!` token after the path has already been eaten.
124     fn parse_stmt_mac(
125         &mut self,
126         lo: Span,
127         attrs: ThinVec<Attribute>,
128         path: ast::Path,
129         legacy_warnings: bool,
130     ) -> PResult<'a, Option<Stmt>> {
131         let args = self.parse_mac_args()?;
132         let delim = args.delim();
133         let hi = self.prev_span;
134
135         let style = if delim == token::Brace {
136             MacStmtStyle::Braces
137         } else {
138             MacStmtStyle::NoBraces
139         };
140
141         let mac = Mac {
142             path,
143             args,
144             prior_type_ascription: self.last_type_ascription,
145         };
146
147         let kind = if delim == token::Brace
148             || self.token == token::Semi
149             || self.token == token::Eof
150         {
151             StmtKind::Mac(P((mac, style, attrs.into())))
152         }
153         // We used to incorrectly stop parsing macro-expanded statements here.
154         // If the next token will be an error anyway but could have parsed with the
155         // earlier behavior, stop parsing here and emit a warning to avoid breakage.
156         else if legacy_warnings
157             && self.token.can_begin_expr()
158             && match self.token.kind {
159                 // These can continue an expression, so we can't stop parsing and warn.
160                 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
161                 token::BinOp(token::Minus) | token::BinOp(token::Star) |
162                 token::BinOp(token::And) | token::BinOp(token::Or) |
163                 token::AndAnd | token::OrOr |
164                 token::DotDot | token::DotDotDot | token::DotDotEq => false,
165                 _ => true,
166             }
167         {
168             self.warn_missing_semicolon();
169             StmtKind::Mac(P((mac, style, attrs)))
170         } else {
171             // Since none of the above applied, this is an expression statement macro.
172             let e = self.mk_expr(lo.to(hi), ExprKind::Mac(mac), ThinVec::new());
173             let e = self.maybe_recover_from_bad_qpath(e, true)?;
174             let e = self.parse_dot_or_call_expr_with(e, lo, attrs)?;
175             let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
176             StmtKind::Expr(e)
177         };
178         Ok(Some(self.mk_stmt(lo.to(hi), kind)))
179     }
180
181     /// Error on outer attributes in this context.
182     /// Also error if the previous token was a doc comment.
183     fn error_outer_attrs(&self, attrs: &[Attribute]) {
184         if !attrs.is_empty() {
185             if self.prev_token_kind == PrevTokenKind::DocComment {
186                 self.span_fatal_err(self.prev_span, Error::UselessDocComment).emit();
187             } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
188                 self.span_err(self.token.span, "expected statement after outer attribute");
189             }
190         }
191     }
192
193     /// Parses a local variable declaration.
194     fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
195         let lo = self.prev_span;
196         let pat = self.parse_top_pat(GateOr::Yes)?;
197
198         let (err, ty) = if self.eat(&token::Colon) {
199             // Save the state of the parser before parsing type normally, in case there is a `:`
200             // instead of an `=` typo.
201             let parser_snapshot_before_type = self.clone();
202             let colon_sp = self.prev_span;
203             match self.parse_ty() {
204                 Ok(ty) => (None, Some(ty)),
205                 Err(mut err) => {
206                     // Rewind to before attempting to parse the type and continue parsing.
207                     let parser_snapshot_after_type = self.clone();
208                     mem::replace(self, parser_snapshot_before_type);
209
210                     let snippet = self.span_to_snippet(pat.span).unwrap();
211                     err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
212                     (Some((parser_snapshot_after_type, colon_sp, err)), None)
213                 }
214             }
215         } else {
216             (None, None)
217         };
218         let init = match (self.parse_initializer(err.is_some()), err) {
219             (Ok(init), None) => {  // init parsed, ty parsed
220                 init
221             }
222             (Ok(init), Some((_, colon_sp, mut err))) => {  // 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))) => {  // init error, ty error
238                 init_err.cancel();
239                 // Couldn't parse the type nor the initializer, only raise the type error and
240                 // return to the parser state before parsing the type as the initializer.
241                 // let x: <parse_error>;
242                 mem::replace(self, snapshot);
243                 return Err(ty_err);
244             }
245             (Err(err), None) => {  // init error, ty parsed
246                 // Couldn't parse the initializer and we're not attempting to recover a failed
247                 // parse of the type, return the error.
248                 return Err(err);
249             }
250         };
251         let hi = if self.token == token::Semi {
252             self.token.span
253         } else {
254             self.prev_span
255         };
256         Ok(P(ast::Local {
257             ty,
258             pat,
259             init,
260             id: DUMMY_NODE_ID,
261             span: lo.to(hi),
262             attrs,
263         }))
264     }
265
266     /// Parses the RHS of a local variable declaration (e.g., '= 14;').
267     fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
268         if self.eat(&token::Eq) {
269             Ok(Some(self.parse_expr()?))
270         } else if skip_eq {
271             Ok(Some(self.parse_expr()?))
272         } else {
273             Ok(None)
274         }
275     }
276
277     fn is_auto_trait_item(&self) -> bool {
278         // auto trait
279         (self.token.is_keyword(kw::Auto) &&
280             self.is_keyword_ahead(1, &[kw::Trait]))
281         || // unsafe auto trait
282         (self.token.is_keyword(kw::Unsafe) &&
283          self.is_keyword_ahead(1, &[kw::Auto]) &&
284          self.is_keyword_ahead(2, &[kw::Trait]))
285     }
286
287     /// Parses a block. No inner attributes are allowed.
288     pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
289         maybe_whole!(self, NtBlock, |x| x);
290
291         let lo = self.token.span;
292
293         if !self.eat(&token::OpenDelim(token::Brace)) {
294             return self.error_block_no_opening_brace();
295         }
296
297         self.parse_block_tail(lo, BlockCheckMode::Default)
298     }
299
300     fn error_block_no_opening_brace<T>(&mut self) -> PResult<'a, T> {
301         let sp = self.token.span;
302         let tok = self.this_token_descr();
303         let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
304         let do_not_suggest_help = self.token.is_keyword(kw::In) || self.token == token::Colon;
305
306         // Check to see if the user has written something like
307         //
308         //    if (cond)
309         //      bar;
310         //
311         // which is valid in other languages, but not Rust.
312         match self.parse_stmt_without_recovery(false) {
313             Ok(Some(stmt)) => {
314                 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
315                     || do_not_suggest_help
316                 {
317                     // If the next token is an open brace (e.g., `if a b {`), the place-
318                     // inside-a-block suggestion would be more likely wrong than right.
319                     e.span_label(sp, "expected `{`");
320                     return Err(e);
321                 }
322                 let stmt_span = if self.eat(&token::Semi) {
323                     // Expand the span to include the semicolon.
324                     stmt.span.with_hi(self.prev_span.hi())
325                 } else {
326                     stmt.span
327                 };
328                 if let Ok(snippet) = self.span_to_snippet(stmt_span) {
329                     e.span_suggestion(
330                         stmt_span,
331                         "try placing this code inside a block",
332                         format!("{{ {} }}", snippet),
333                         // Speculative; has been misleading in the past (#46836).
334                         Applicability::MaybeIncorrect,
335                     );
336                 }
337             }
338             Err(mut e) => {
339                 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
340                 e.cancel();
341             }
342             _ => {}
343         }
344         e.span_label(sp, "expected `{`");
345         return Err(e);
346     }
347
348     /// Parses a block. Inner attributes are allowed.
349     pub(super) fn parse_inner_attrs_and_block(
350         &mut self
351     ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
352         maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
353
354         let lo = self.token.span;
355         self.expect(&token::OpenDelim(token::Brace))?;
356         Ok((self.parse_inner_attributes()?,
357             self.parse_block_tail(lo, BlockCheckMode::Default)?))
358     }
359
360     /// Parses the rest of a block expression or function body.
361     /// Precondition: already parsed the '{'.
362     pub(super) fn parse_block_tail(
363         &mut self,
364         lo: Span,
365         s: BlockCheckMode
366     ) -> PResult<'a, P<Block>> {
367         let mut stmts = vec![];
368         while !self.eat(&token::CloseDelim(token::Brace)) {
369             if self.token == token::Eof {
370                 break;
371             }
372             let stmt = match self.parse_full_stmt(false) {
373                 Err(mut err) => {
374                     self.maybe_annotate_with_ascription(&mut err, false);
375                     err.emit();
376                     self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
377                     Some(self.mk_stmt(
378                         self.token.span,
379                         StmtKind::Expr(self.mk_expr_err(self.token.span)),
380                     ))
381                 }
382                 Ok(stmt) => stmt,
383             };
384             if let Some(stmt) = stmt {
385                 stmts.push(stmt);
386             } else {
387                 // Found only `;` or `}`.
388                 continue;
389             };
390         }
391         Ok(P(ast::Block {
392             stmts,
393             id: DUMMY_NODE_ID,
394             rules: s,
395             span: lo.to(self.prev_span),
396         }))
397     }
398
399     /// Parses a statement, including the trailing semicolon.
400     pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
401         // Skip looking for a trailing semicolon when we have an interpolated statement.
402         maybe_whole!(self, NtStmt, |x| Some(x));
403
404         let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
405             Some(stmt) => stmt,
406             None => return Ok(None),
407         };
408
409         let mut eat_semi = true;
410         match stmt.kind {
411             StmtKind::Expr(ref expr) if self.token != token::Eof => {
412                 // expression without semicolon
413                 if classify::expr_requires_semi_to_be_stmt(expr) {
414                     // Just check for errors and recover; do not eat semicolon yet.
415                     if let Err(mut e) =
416                         self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
417                     {
418                         e.emit();
419                         self.recover_stmt();
420                         // Don't complain about type errors in body tail after parse error (#57383).
421                         let sp = expr.span.to(self.prev_span);
422                         stmt.kind = StmtKind::Expr(self.mk_expr_err(sp));
423                     }
424                 }
425             }
426             StmtKind::Local(..) => {
427                 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
428                 if macro_legacy_warnings && self.token != token::Semi {
429                     self.warn_missing_semicolon();
430                 } else {
431                     self.expect_semi()?;
432                     eat_semi = false;
433                 }
434             }
435             _ => {}
436         }
437
438         if eat_semi && self.eat(&token::Semi) {
439             stmt = stmt.add_trailing_semicolon();
440         }
441         stmt.span = stmt.span.to(self.prev_span);
442         Ok(Some(stmt))
443     }
444
445     fn warn_missing_semicolon(&self) {
446         self.diagnostic().struct_span_warn(self.token.span, {
447             &format!("expected `;`, found {}", self.this_token_descr())
448         }).note({
449             "this was erroneously allowed and will become a hard error in a future release"
450         }).emit();
451     }
452
453     fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt {
454         Stmt { id: DUMMY_NODE_ID, kind, span }
455     }
456 }