]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/stmt.rs
Rollup merge of #103397 - crlf0710:port_dead_code_lint, r=davidtwco
[rust.git] / compiler / rustc_parse / src / parser / stmt.rs
1 use super::attr::InnerAttrForbiddenReason;
2 use super::diagnostics::AttemptLocalParseRecovery;
3 use super::expr::LhsExpr;
4 use super::pat::RecoverComma;
5 use super::path::PathStyle;
6 use super::TrailingToken;
7 use super::{
8     AttrWrapper, BlockMode, FnParseMode, ForceCollect, Parser, Restrictions, SemiColonMode,
9 };
10 use crate::errors::{
11     AssignmentElseNotAllowed, CompoundAssignmentExpressionInLet, ConstLetMutuallyExclusive,
12     DocCommentDoesNotDocumentAnything, ExpectedStatementAfterOuterAttr, InvalidCurlyInLetElse,
13     InvalidExpressionInLetElse, InvalidVariableDeclaration, InvalidVariableDeclarationSub,
14     WrapExpressionInParentheses,
15 };
16 use crate::maybe_whole;
17
18 use rustc_ast as ast;
19 use rustc_ast::ptr::P;
20 use rustc_ast::token::{self, Delimiter, TokenKind};
21 use rustc_ast::util::classify;
22 use rustc_ast::{AttrStyle, AttrVec, Attribute, LocalKind, MacCall, MacCallStmt, MacStmtStyle};
23 use rustc_ast::{Block, BlockCheckMode, Expr, ExprKind, HasAttrs, Local, Stmt};
24 use rustc_ast::{StmtKind, DUMMY_NODE_ID};
25 use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed, PResult};
26 use rustc_span::source_map::{BytePos, Span};
27 use rustc_span::symbol::{kw, sym};
28
29 use std::mem;
30
31 impl<'a> Parser<'a> {
32     /// Parses a statement. This stops just before trailing semicolons on everything but items.
33     /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
34     // Public for rustfmt usage.
35     pub fn parse_stmt(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<Stmt>> {
36         Ok(self.parse_stmt_without_recovery(false, force_collect).unwrap_or_else(|mut e| {
37             e.emit();
38             self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
39             None
40         }))
41     }
42
43     /// If `force_collect` is [`ForceCollect::Yes`], forces collection of tokens regardless of whether
44     /// or not we have attributes
45     pub(crate) fn parse_stmt_without_recovery(
46         &mut self,
47         capture_semi: bool,
48         force_collect: ForceCollect,
49     ) -> PResult<'a, Option<Stmt>> {
50         let attrs = self.parse_outer_attributes()?;
51         let lo = self.token.span;
52
53         // Don't use `maybe_whole` so that we have precise control
54         // over when we bump the parser
55         if let token::Interpolated(nt) = &self.token.kind && let token::NtStmt(stmt) = &**nt {
56             let mut stmt = stmt.clone();
57             self.bump();
58             stmt.visit_attrs(|stmt_attrs| {
59                 attrs.prepend_to_nt_inner(stmt_attrs);
60             });
61             return Ok(Some(stmt.into_inner()));
62         }
63
64         if self.token.is_keyword(kw::Mut) && self.is_keyword_ahead(1, &[kw::Let]) {
65             self.bump();
66             let mut_let_span = lo.to(self.token.span);
67             self.sess.emit_err(InvalidVariableDeclaration {
68                 span: mut_let_span,
69                 sub: InvalidVariableDeclarationSub::SwitchMutLetOrder(mut_let_span),
70             });
71         }
72
73         Ok(Some(if self.token.is_keyword(kw::Let) {
74             self.parse_local_mk(lo, attrs, capture_semi, force_collect)?
75         } else if self.is_kw_followed_by_ident(kw::Mut) {
76             self.recover_stmt_local(lo, attrs, InvalidVariableDeclarationSub::MissingLet)?
77         } else if self.is_kw_followed_by_ident(kw::Auto) {
78             self.bump(); // `auto`
79             self.recover_stmt_local(lo, attrs, InvalidVariableDeclarationSub::UseLetNotAuto)?
80         } else if self.is_kw_followed_by_ident(sym::var) {
81             self.bump(); // `var`
82             self.recover_stmt_local(lo, attrs, InvalidVariableDeclarationSub::UseLetNotVar)?
83         } else if self.check_path() && !self.token.is_qpath_start() && !self.is_path_start_item() {
84             // We have avoided contextual keywords like `union`, items with `crate` visibility,
85             // or `auto trait` items. We aim to parse an arbitrary path `a::b` but not something
86             // that starts like a path (1 token), but it fact not a path.
87             // Also, we avoid stealing syntax from `parse_item_`.
88             if force_collect == ForceCollect::Yes {
89                 self.collect_tokens_no_attrs(|this| this.parse_stmt_path_start(lo, attrs))
90             } else {
91                 self.parse_stmt_path_start(lo, attrs)
92             }?
93         } else if let Some(item) = self.parse_item_common(
94             attrs.clone(),
95             false,
96             true,
97             FnParseMode { req_name: |_| true, req_body: true },
98             force_collect,
99         )? {
100             // FIXME: Bad copy of attrs
101             self.mk_stmt(lo.to(item.span), StmtKind::Item(P(item)))
102         } else if self.eat(&token::Semi) {
103             // Do not attempt to parse an expression if we're done here.
104             self.error_outer_attrs(&attrs.take_for_recovery());
105             self.mk_stmt(lo, StmtKind::Empty)
106         } else if self.token != token::CloseDelim(Delimiter::Brace) {
107             // Remainder are line-expr stmts.
108             let e = if force_collect == ForceCollect::Yes {
109                 self.collect_tokens_no_attrs(|this| {
110                     this.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs))
111                 })
112             } else {
113                 self.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs))
114             }?;
115             if matches!(e.kind, ExprKind::Assign(..)) && self.eat_keyword(kw::Else) {
116                 let bl = self.parse_block()?;
117                 // Destructuring assignment ... else.
118                 // This is not allowed, but point it out in a nice way.
119                 self.sess.emit_err(AssignmentElseNotAllowed { span: e.span.to(bl.span) });
120             }
121             self.mk_stmt(lo.to(e.span), StmtKind::Expr(e))
122         } else {
123             self.error_outer_attrs(&attrs.take_for_recovery());
124             return Ok(None);
125         }))
126     }
127
128     fn parse_stmt_path_start(&mut self, lo: Span, attrs: AttrWrapper) -> PResult<'a, Stmt> {
129         let stmt = self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
130             let path = this.parse_path(PathStyle::Expr)?;
131
132             if this.eat(&token::Not) {
133                 let stmt_mac = this.parse_stmt_mac(lo, attrs, path)?;
134                 if this.token == token::Semi {
135                     return Ok((stmt_mac, TrailingToken::Semi));
136                 } else {
137                     return Ok((stmt_mac, TrailingToken::None));
138                 }
139             }
140
141             let expr = if this.eat(&token::OpenDelim(Delimiter::Brace)) {
142                 this.parse_struct_expr(None, path, true)?
143             } else {
144                 let hi = this.prev_token.span;
145                 this.mk_expr(lo.to(hi), ExprKind::Path(None, path))
146             };
147
148             let expr = this.with_res(Restrictions::STMT_EXPR, |this| {
149                 this.parse_dot_or_call_expr_with(expr, lo, attrs)
150             })?;
151             // `DUMMY_SP` will get overwritten later in this function
152             Ok((this.mk_stmt(rustc_span::DUMMY_SP, StmtKind::Expr(expr)), TrailingToken::None))
153         })?;
154
155         if let StmtKind::Expr(expr) = stmt.kind {
156             // Perform this outside of the `collect_tokens_trailing_token` closure,
157             // since our outer attributes do not apply to this part of the expression
158             let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
159                 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
160             })?;
161             Ok(self.mk_stmt(lo.to(self.prev_token.span), StmtKind::Expr(expr)))
162         } else {
163             Ok(stmt)
164         }
165     }
166
167     /// Parses a statement macro `mac!(args)` provided a `path` representing `mac`.
168     /// At this point, the `!` token after the path has already been eaten.
169     fn parse_stmt_mac(&mut self, lo: Span, attrs: AttrVec, path: ast::Path) -> PResult<'a, Stmt> {
170         let args = self.parse_mac_args()?;
171         let delim = args.delim();
172         let hi = self.prev_token.span;
173
174         let style = match delim {
175             Some(Delimiter::Brace) => MacStmtStyle::Braces,
176             Some(_) => MacStmtStyle::NoBraces,
177             None => unreachable!(),
178         };
179
180         let mac = P(MacCall { path, args, prior_type_ascription: self.last_type_ascription });
181
182         let kind = if (style == MacStmtStyle::Braces
183             && self.token != token::Dot
184             && self.token != token::Question)
185             || self.token == token::Semi
186             || self.token == token::Eof
187         {
188             StmtKind::MacCall(P(MacCallStmt { mac, style, attrs, tokens: None }))
189         } else {
190             // Since none of the above applied, this is an expression statement macro.
191             let e = self.mk_expr(lo.to(hi), ExprKind::MacCall(mac));
192             let e = self.maybe_recover_from_bad_qpath(e)?;
193             let e = self.parse_dot_or_call_expr_with(e, lo, attrs)?;
194             let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
195             StmtKind::Expr(e)
196         };
197         Ok(self.mk_stmt(lo.to(hi), kind))
198     }
199
200     /// Error on outer attributes in this context.
201     /// Also error if the previous token was a doc comment.
202     fn error_outer_attrs(&self, attrs: &[Attribute]) {
203         if let [.., last] = attrs {
204             if last.is_doc_comment() {
205                 self.sess.emit_err(DocCommentDoesNotDocumentAnything {
206                     span: last.span,
207                     missing_comma: None,
208                 });
209             } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
210                 self.sess.emit_err(ExpectedStatementAfterOuterAttr { span: last.span });
211             }
212         }
213     }
214
215     fn recover_stmt_local(
216         &mut self,
217         lo: Span,
218         attrs: AttrWrapper,
219         subdiagnostic: fn(Span) -> InvalidVariableDeclarationSub,
220     ) -> PResult<'a, Stmt> {
221         let stmt = self.recover_local_after_let(lo, attrs)?;
222         self.sess.emit_err(InvalidVariableDeclaration { span: lo, sub: subdiagnostic(lo) });
223         Ok(stmt)
224     }
225
226     fn parse_local_mk(
227         &mut self,
228         lo: Span,
229         attrs: AttrWrapper,
230         capture_semi: bool,
231         force_collect: ForceCollect,
232     ) -> PResult<'a, Stmt> {
233         self.collect_tokens_trailing_token(attrs, force_collect, |this, attrs| {
234             this.expect_keyword(kw::Let)?;
235             let local = this.parse_local(attrs)?;
236             let trailing = if capture_semi && this.token.kind == token::Semi {
237                 TrailingToken::Semi
238             } else {
239                 TrailingToken::None
240             };
241             Ok((this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Local(local)), trailing))
242         })
243     }
244
245     fn recover_local_after_let(&mut self, lo: Span, attrs: AttrWrapper) -> PResult<'a, Stmt> {
246         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
247             let local = this.parse_local(attrs)?;
248             // FIXME - maybe capture semicolon in recovery?
249             Ok((
250                 this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Local(local)),
251                 TrailingToken::None,
252             ))
253         })
254     }
255
256     /// Parses a local variable declaration.
257     fn parse_local(&mut self, attrs: AttrVec) -> PResult<'a, P<Local>> {
258         let lo = self.prev_token.span;
259
260         if self.token.is_keyword(kw::Const) && self.look_ahead(1, |t| t.is_ident()) {
261             self.sess.emit_err(ConstLetMutuallyExclusive { span: lo.to(self.token.span) });
262             self.bump();
263         }
264
265         let (pat, colon) = self.parse_pat_before_ty(None, RecoverComma::Yes, "`let` bindings")?;
266
267         let (err, ty) = if colon {
268             // Save the state of the parser before parsing type normally, in case there is a `:`
269             // instead of an `=` typo.
270             let parser_snapshot_before_type = self.clone();
271             let colon_sp = self.prev_token.span;
272             match self.parse_ty() {
273                 Ok(ty) => (None, Some(ty)),
274                 Err(mut err) => {
275                     if let Ok(snip) = self.span_to_snippet(pat.span) {
276                         err.span_label(pat.span, format!("while parsing the type for `{}`", snip));
277                     }
278                     // we use noexpect here because we don't actually expect Eq to be here
279                     // but we are still checking for it in order to be able to handle it if
280                     // it is there
281                     let err = if self.check_noexpect(&token::Eq) {
282                         err.emit();
283                         None
284                     } else {
285                         // Rewind to before attempting to parse the type and continue parsing.
286                         let parser_snapshot_after_type =
287                             mem::replace(self, parser_snapshot_before_type);
288                         Some((parser_snapshot_after_type, colon_sp, err))
289                     };
290                     (err, None)
291                 }
292             }
293         } else {
294             (None, None)
295         };
296         let init = match (self.parse_initializer(err.is_some()), err) {
297             (Ok(init), None) => {
298                 // init parsed, ty parsed
299                 init
300             }
301             (Ok(init), Some((_, colon_sp, mut err))) => {
302                 // init parsed, ty error
303                 // Could parse the type as if it were the initializer, it is likely there was a
304                 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
305                 err.span_suggestion_short(
306                     colon_sp,
307                     "use `=` if you meant to assign",
308                     " =",
309                     Applicability::MachineApplicable,
310                 );
311                 err.emit();
312                 // As this was parsed successfully, continue as if the code has been fixed for the
313                 // rest of the file. It will still fail due to the emitted error, but we avoid
314                 // extra noise.
315                 init
316             }
317             (Err(init_err), Some((snapshot, _, ty_err))) => {
318                 // init error, ty error
319                 init_err.cancel();
320                 // Couldn't parse the type nor the initializer, only raise the type error and
321                 // return to the parser state before parsing the type as the initializer.
322                 // let x: <parse_error>;
323                 *self = snapshot;
324                 return Err(ty_err);
325             }
326             (Err(err), None) => {
327                 // init error, ty parsed
328                 // Couldn't parse the initializer and we're not attempting to recover a failed
329                 // parse of the type, return the error.
330                 return Err(err);
331             }
332         };
333         let kind = match init {
334             None => LocalKind::Decl,
335             Some(init) => {
336                 if self.eat_keyword(kw::Else) {
337                     if self.token.is_keyword(kw::If) {
338                         // `let...else if`. Emit the same error that `parse_block()` would,
339                         // but explicitly point out that this pattern is not allowed.
340                         let msg = "conditional `else if` is not supported for `let...else`";
341                         return Err(self.error_block_no_opening_brace_msg(msg));
342                     }
343                     let els = self.parse_block()?;
344                     self.check_let_else_init_bool_expr(&init);
345                     self.check_let_else_init_trailing_brace(&init);
346                     LocalKind::InitElse(init, els)
347                 } else {
348                     LocalKind::Init(init)
349                 }
350             }
351         };
352         let hi = if self.token == token::Semi { self.token.span } else { self.prev_token.span };
353         Ok(P(ast::Local { ty, pat, kind, id: DUMMY_NODE_ID, span: lo.to(hi), attrs, tokens: None }))
354     }
355
356     fn check_let_else_init_bool_expr(&self, init: &ast::Expr) {
357         if let ast::ExprKind::Binary(op, ..) = init.kind {
358             if op.node.lazy() {
359                 self.sess.emit_err(InvalidExpressionInLetElse {
360                     span: init.span,
361                     operator: op.node.to_string(),
362                     sugg: WrapExpressionInParentheses {
363                         left: init.span.shrink_to_lo(),
364                         right: init.span.shrink_to_hi(),
365                     },
366                 });
367             }
368         }
369     }
370
371     fn check_let_else_init_trailing_brace(&self, init: &ast::Expr) {
372         if let Some(trailing) = classify::expr_trailing_brace(init) {
373             self.sess.emit_err(InvalidCurlyInLetElse {
374                 span: trailing.span.with_lo(trailing.span.hi() - BytePos(1)),
375                 sugg: WrapExpressionInParentheses {
376                     left: trailing.span.shrink_to_lo(),
377                     right: trailing.span.shrink_to_hi(),
378                 },
379             });
380         }
381     }
382
383     /// Parses the RHS of a local variable declaration (e.g., `= 14;`).
384     fn parse_initializer(&mut self, eq_optional: bool) -> PResult<'a, Option<P<Expr>>> {
385         let eq_consumed = match self.token.kind {
386             token::BinOpEq(..) => {
387                 // Recover `let x <op>= 1` as `let x = 1`
388                 self.sess.emit_err(CompoundAssignmentExpressionInLet { span: self.token.span });
389                 self.bump();
390                 true
391             }
392             _ => self.eat(&token::Eq),
393         };
394
395         Ok(if eq_consumed || eq_optional { Some(self.parse_expr()?) } else { None })
396     }
397
398     /// Parses a block. No inner attributes are allowed.
399     pub(super) fn parse_block(&mut self) -> PResult<'a, P<Block>> {
400         let (attrs, block) = self.parse_inner_attrs_and_block()?;
401         if let [.., last] = &*attrs {
402             self.error_on_forbidden_inner_attr(
403                 last.span,
404                 super::attr::InnerAttrPolicy::Forbidden(Some(
405                     InnerAttrForbiddenReason::InCodeBlock,
406                 )),
407             );
408         }
409         Ok(block)
410     }
411
412     fn error_block_no_opening_brace_msg(
413         &mut self,
414         msg: &str,
415     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
416         let sp = self.token.span;
417         let mut e = self.struct_span_err(sp, msg);
418         let do_not_suggest_help = self.token.is_keyword(kw::In) || self.token == token::Colon;
419
420         // Check to see if the user has written something like
421         //
422         //    if (cond)
423         //      bar;
424         //
425         // which is valid in other languages, but not Rust.
426         match self.parse_stmt_without_recovery(false, ForceCollect::No) {
427             // If the next token is an open brace, e.g., we have:
428             //
429             //     if expr other_expr {
430             //        ^    ^          ^- lookahead(1) is a brace
431             //        |    |- current token is not "else"
432             //        |- (statement we just parsed)
433             //
434             // the place-inside-a-block suggestion would be more likely wrong than right.
435             //
436             // FIXME(compiler-errors): this should probably parse an arbitrary expr and not
437             // just lookahead one token, so we can see if there's a brace after _that_,
438             // since we want to protect against:
439             //     `if 1 1 + 1 {` being suggested as  `if { 1 } 1 + 1 {`
440             //                                            +   +
441             Ok(Some(_))
442                 if (!self.token.is_keyword(kw::Else)
443                     && self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Brace)))
444                     || do_not_suggest_help => {}
445             // Do not suggest `if foo println!("") {;}` (as would be seen in test for #46836).
446             Ok(Some(Stmt { kind: StmtKind::Empty, .. })) => {}
447             Ok(Some(stmt)) => {
448                 let stmt_own_line = self.sess.source_map().is_line_before_span_empty(sp);
449                 let stmt_span = if stmt_own_line && self.eat(&token::Semi) {
450                     // Expand the span to include the semicolon.
451                     stmt.span.with_hi(self.prev_token.span.hi())
452                 } else {
453                     stmt.span
454                 };
455                 e.multipart_suggestion(
456                     "try placing this code inside a block",
457                     vec![
458                         (stmt_span.shrink_to_lo(), "{ ".to_string()),
459                         (stmt_span.shrink_to_hi(), " }".to_string()),
460                     ],
461                     // Speculative; has been misleading in the past (#46836).
462                     Applicability::MaybeIncorrect,
463                 );
464             }
465             Err(e) => {
466                 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
467                 e.cancel();
468             }
469             _ => {}
470         }
471         e.span_label(sp, "expected `{`");
472         e
473     }
474
475     fn error_block_no_opening_brace<T>(&mut self) -> PResult<'a, T> {
476         let tok = super::token_descr(&self.token);
477         let msg = format!("expected `{{`, found {}", tok);
478         Err(self.error_block_no_opening_brace_msg(&msg))
479     }
480
481     /// Parses a block. Inner attributes are allowed.
482     pub(super) fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (AttrVec, P<Block>)> {
483         self.parse_block_common(self.token.span, BlockCheckMode::Default)
484     }
485
486     /// Parses a block. Inner attributes are allowed.
487     pub(super) fn parse_block_common(
488         &mut self,
489         lo: Span,
490         blk_mode: BlockCheckMode,
491     ) -> PResult<'a, (AttrVec, P<Block>)> {
492         maybe_whole!(self, NtBlock, |x| (AttrVec::new(), x));
493
494         self.maybe_recover_unexpected_block_label();
495         if !self.eat(&token::OpenDelim(Delimiter::Brace)) {
496             return self.error_block_no_opening_brace();
497         }
498
499         let attrs = self.parse_inner_attributes()?;
500         let tail = match self.maybe_suggest_struct_literal(lo, blk_mode) {
501             Some(tail) => tail?,
502             None => self.parse_block_tail(lo, blk_mode, AttemptLocalParseRecovery::Yes)?,
503         };
504         Ok((attrs, tail))
505     }
506
507     /// Parses the rest of a block expression or function body.
508     /// Precondition: already parsed the '{'.
509     pub(crate) fn parse_block_tail(
510         &mut self,
511         lo: Span,
512         s: BlockCheckMode,
513         recover: AttemptLocalParseRecovery,
514     ) -> PResult<'a, P<Block>> {
515         let mut stmts = vec![];
516         while !self.eat(&token::CloseDelim(Delimiter::Brace)) {
517             if self.token == token::Eof {
518                 break;
519             }
520             let stmt = match self.parse_full_stmt(recover) {
521                 Err(mut err) if recover.yes() => {
522                     self.maybe_annotate_with_ascription(&mut err, false);
523                     err.emit();
524                     self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
525                     Some(self.mk_stmt_err(self.token.span))
526                 }
527                 Ok(stmt) => stmt,
528                 Err(err) => return Err(err),
529             };
530             if let Some(stmt) = stmt {
531                 stmts.push(stmt);
532             } else {
533                 // Found only `;` or `}`.
534                 continue;
535             };
536         }
537         Ok(self.mk_block(stmts, s, lo.to(self.prev_token.span)))
538     }
539
540     /// Parses a statement, including the trailing semicolon.
541     pub fn parse_full_stmt(
542         &mut self,
543         recover: AttemptLocalParseRecovery,
544     ) -> PResult<'a, Option<Stmt>> {
545         // Skip looking for a trailing semicolon when we have an interpolated statement.
546         maybe_whole!(self, NtStmt, |x| Some(x.into_inner()));
547
548         let Some(mut stmt) = self.parse_stmt_without_recovery(true, ForceCollect::No)? else {
549             return Ok(None);
550         };
551
552         let mut eat_semi = true;
553         match stmt.kind {
554             // Expression without semicolon.
555             StmtKind::Expr(ref mut expr)
556                 if self.token != token::Eof && classify::expr_requires_semi_to_be_stmt(expr) => {
557                 // Just check for errors and recover; do not eat semicolon yet.
558                 // `expect_one_of` returns PResult<'a, bool /* recovered */>
559                 let replace_with_err =
560                     match self.expect_one_of(&[], &[token::Semi, token::CloseDelim(Delimiter::Brace)]) {
561                     // Recover from parser, skip type error to avoid extra errors.
562                     Ok(true) => true,
563                     Err(mut e) => {
564                         if let TokenKind::DocComment(..) = self.token.kind &&
565                             let Ok(snippet) = self.span_to_snippet(self.token.span) {
566                                 let sp = self.token.span;
567                                 let marker = &snippet[..3];
568                                 let (comment_marker, doc_comment_marker) = marker.split_at(2);
569
570                                 e.span_suggestion(
571                                     sp.with_hi(sp.lo() + BytePos(marker.len() as u32)),
572                                     &format!(
573                                         "add a space before `{}` to use a regular comment",
574                                         doc_comment_marker,
575                                     ),
576                                     format!("{} {}", comment_marker, doc_comment_marker),
577                                     Applicability::MaybeIncorrect,
578                                 );
579                         }
580
581                         if let Err(mut e) =
582                             self.check_mistyped_turbofish_with_multiple_type_params(e, expr)
583                         {
584                             if recover.no() {
585                                 return Err(e);
586                             }
587                             e.emit();
588                             self.recover_stmt();
589                         }
590                         true
591                     }
592                     _ => false
593                 };
594                 if replace_with_err {
595                     // We already emitted an error, so don't emit another type error
596                     let sp = expr.span.to(self.prev_token.span);
597                     *expr = self.mk_expr_err(sp);
598                 }
599             }
600             StmtKind::Expr(_) | StmtKind::MacCall(_) => {}
601             StmtKind::Local(ref mut local) if let Err(e) = self.expect_semi() => {
602                 // We might be at the `,` in `let x = foo<bar, baz>;`. Try to recover.
603                 match &mut local.kind {
604                     LocalKind::Init(expr) | LocalKind::InitElse(expr, _) => {
605                         self.check_mistyped_turbofish_with_multiple_type_params(e, expr)?;
606                         // We found `foo<bar, baz>`, have we fully recovered?
607                         self.expect_semi()?;
608                     }
609                     LocalKind::Decl => return Err(e),
610                 }
611                 eat_semi = false;
612             }
613             StmtKind::Empty | StmtKind::Item(_) | StmtKind::Local(_) | StmtKind::Semi(_) => eat_semi = false,
614         }
615
616         if eat_semi && self.eat(&token::Semi) {
617             stmt = stmt.add_trailing_semicolon();
618         }
619         stmt.span = stmt.span.to(self.prev_token.span);
620         Ok(Some(stmt))
621     }
622
623     pub(super) fn mk_block(&self, stmts: Vec<Stmt>, rules: BlockCheckMode, span: Span) -> P<Block> {
624         P(Block {
625             stmts,
626             id: DUMMY_NODE_ID,
627             rules,
628             span,
629             tokens: None,
630             could_be_bare_literal: false,
631         })
632     }
633
634     pub(super) fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt {
635         Stmt { id: DUMMY_NODE_ID, kind, span }
636     }
637
638     pub(super) fn mk_stmt_err(&self, span: Span) -> Stmt {
639         self.mk_stmt(span, StmtKind::Expr(self.mk_expr_err(span)))
640     }
641
642     pub(super) fn mk_block_err(&self, span: Span) -> P<Block> {
643         self.mk_block(vec![self.mk_stmt_err(span)], BlockCheckMode::Default, span)
644     }
645 }