]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/diagnostics.rs
Auto merge of #67758 - ssomers:testing_range, r=Mark-Simulacrum
[rust.git] / src / librustc_parse / parser / diagnostics.rs
1 use super::{BlockMode, Parser, PathStyle, SemiColonMode, SeqSep, TokenExpectType, TokenType};
2
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_error_codes::*;
5 use rustc_errors::{pluralize, struct_span_err};
6 use rustc_errors::{Applicability, DiagnosticBuilder, Handler, PResult};
7 use rustc_span::source_map::Spanned;
8 use rustc_span::symbol::kw;
9 use rustc_span::{MultiSpan, Span, SpanSnippetError, DUMMY_SP};
10 use syntax::ast::{
11     self, BinOpKind, BindingMode, BlockCheckMode, Expr, ExprKind, Ident, Item, Param,
12 };
13 use syntax::ast::{AttrVec, ItemKind, Mutability, Pat, PatKind, PathSegment, QSelf, Ty, TyKind};
14 use syntax::print::pprust;
15 use syntax::ptr::P;
16 use syntax::token::{self, token_can_begin_expr, TokenKind};
17 use syntax::util::parser::AssocOp;
18
19 use log::{debug, trace};
20 use std::mem;
21
22 const TURBOFISH: &'static str = "use `::<...>` instead of `<...>` to specify type arguments";
23
24 /// Creates a placeholder argument.
25 pub(super) fn dummy_arg(ident: Ident) -> Param {
26     let pat = P(Pat {
27         id: ast::DUMMY_NODE_ID,
28         kind: PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None),
29         span: ident.span,
30     });
31     let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID };
32     Param {
33         attrs: AttrVec::default(),
34         id: ast::DUMMY_NODE_ID,
35         pat,
36         span: ident.span,
37         ty: P(ty),
38         is_placeholder: false,
39     }
40 }
41
42 pub enum Error {
43     FileNotFoundForModule {
44         mod_name: String,
45         default_path: String,
46         secondary_path: String,
47         dir_path: String,
48     },
49     DuplicatePaths {
50         mod_name: String,
51         default_path: String,
52         secondary_path: String,
53     },
54     UselessDocComment,
55 }
56
57 impl Error {
58     fn span_err(self, sp: impl Into<MultiSpan>, handler: &Handler) -> DiagnosticBuilder<'_> {
59         match self {
60             Error::FileNotFoundForModule {
61                 ref mod_name,
62                 ref default_path,
63                 ref secondary_path,
64                 ref dir_path,
65             } => {
66                 let mut err = struct_span_err!(
67                     handler,
68                     sp,
69                     E0583,
70                     "file not found for module `{}`",
71                     mod_name,
72                 );
73                 err.help(&format!(
74                     "name the file either {} or {} inside the directory \"{}\"",
75                     default_path, secondary_path, dir_path,
76                 ));
77                 err
78             }
79             Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
80                 let mut err = struct_span_err!(
81                     handler,
82                     sp,
83                     E0584,
84                     "file for module `{}` found at both {} and {}",
85                     mod_name,
86                     default_path,
87                     secondary_path,
88                 );
89                 err.help("delete or rename one of them to remove the ambiguity");
90                 err
91             }
92             Error::UselessDocComment => {
93                 let mut err = struct_span_err!(
94                     handler,
95                     sp,
96                     E0585,
97                     "found a documentation comment that doesn't document anything",
98                 );
99                 err.help(
100                     "doc comments must come before what they document, maybe a comment was \
101                           intended with `//`?",
102                 );
103                 err
104             }
105         }
106     }
107 }
108
109 pub(super) trait RecoverQPath: Sized + 'static {
110     const PATH_STYLE: PathStyle = PathStyle::Expr;
111     fn to_ty(&self) -> Option<P<Ty>>;
112     fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
113 }
114
115 impl RecoverQPath for Ty {
116     const PATH_STYLE: PathStyle = PathStyle::Type;
117     fn to_ty(&self) -> Option<P<Ty>> {
118         Some(P(self.clone()))
119     }
120     fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
121         Self { span: path.span, kind: TyKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
122     }
123 }
124
125 impl RecoverQPath for Pat {
126     fn to_ty(&self) -> Option<P<Ty>> {
127         self.to_ty()
128     }
129     fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
130         Self { span: path.span, kind: PatKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
131     }
132 }
133
134 impl RecoverQPath for Expr {
135     fn to_ty(&self) -> Option<P<Ty>> {
136         self.to_ty()
137     }
138     fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
139         Self {
140             span: path.span,
141             kind: ExprKind::Path(qself, path),
142             attrs: AttrVec::new(),
143             id: ast::DUMMY_NODE_ID,
144         }
145     }
146 }
147
148 /// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
149 crate enum ConsumeClosingDelim {
150     Yes,
151     No,
152 }
153
154 impl<'a> Parser<'a> {
155     pub(super) fn span_fatal_err<S: Into<MultiSpan>>(
156         &self,
157         sp: S,
158         err: Error,
159     ) -> DiagnosticBuilder<'a> {
160         err.span_err(sp, self.diagnostic())
161     }
162
163     pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
164         self.sess.span_diagnostic.struct_span_err(sp, m)
165     }
166
167     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
168         self.sess.span_diagnostic.span_bug(sp, m)
169     }
170
171     pub(super) fn diagnostic(&self) -> &'a Handler {
172         &self.sess.span_diagnostic
173     }
174
175     pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
176         self.sess.source_map().span_to_snippet(span)
177     }
178
179     pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
180         let mut err = self.struct_span_err(
181             self.token.span,
182             &format!("expected identifier, found {}", super::token_descr(&self.token)),
183         );
184         let valid_follow = &[
185             TokenKind::Eq,
186             TokenKind::Colon,
187             TokenKind::Comma,
188             TokenKind::Semi,
189             TokenKind::ModSep,
190             TokenKind::OpenDelim(token::DelimToken::Brace),
191             TokenKind::OpenDelim(token::DelimToken::Paren),
192             TokenKind::CloseDelim(token::DelimToken::Brace),
193             TokenKind::CloseDelim(token::DelimToken::Paren),
194         ];
195         if let token::Ident(name, false) = self.token.kind {
196             if Ident::new(name, self.token.span).is_raw_guess()
197                 && self.look_ahead(1, |t| valid_follow.contains(&t.kind))
198             {
199                 err.span_suggestion(
200                     self.token.span,
201                     "you can escape reserved keywords to use them as identifiers",
202                     format!("r#{}", name),
203                     Applicability::MaybeIncorrect,
204                 );
205             }
206         }
207         if let Some(token_descr) = super::token_descr_opt(&self.token) {
208             err.span_label(self.token.span, format!("expected identifier, found {}", token_descr));
209         } else {
210             err.span_label(self.token.span, "expected identifier");
211             if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
212                 err.span_suggestion(
213                     self.token.span,
214                     "remove this comma",
215                     String::new(),
216                     Applicability::MachineApplicable,
217                 );
218             }
219         }
220         err
221     }
222
223     pub(super) fn expected_one_of_not_found(
224         &mut self,
225         edible: &[TokenKind],
226         inedible: &[TokenKind],
227     ) -> PResult<'a, bool /* recovered */> {
228         fn tokens_to_string(tokens: &[TokenType]) -> String {
229             let mut i = tokens.iter();
230             // This might be a sign we need a connect method on `Iterator`.
231             let b = i.next().map_or(String::new(), |t| t.to_string());
232             i.enumerate().fold(b, |mut b, (i, a)| {
233                 if tokens.len() > 2 && i == tokens.len() - 2 {
234                     b.push_str(", or ");
235                 } else if tokens.len() == 2 && i == tokens.len() - 2 {
236                     b.push_str(" or ");
237                 } else {
238                     b.push_str(", ");
239                 }
240                 b.push_str(&a.to_string());
241                 b
242             })
243         }
244
245         let mut expected = edible
246             .iter()
247             .map(|x| TokenType::Token(x.clone()))
248             .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
249             .chain(self.expected_tokens.iter().cloned())
250             .collect::<Vec<_>>();
251         expected.sort_by_cached_key(|x| x.to_string());
252         expected.dedup();
253         let expect = tokens_to_string(&expected[..]);
254         let actual = super::token_descr(&self.token);
255         let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
256             let short_expect = if expected.len() > 6 {
257                 format!("{} possible tokens", expected.len())
258             } else {
259                 expect.clone()
260             };
261             (
262                 format!("expected one of {}, found {}", expect, actual),
263                 (self.prev_span.shrink_to_hi(), format!("expected one of {}", short_expect)),
264             )
265         } else if expected.is_empty() {
266             (
267                 format!("unexpected token: {}", actual),
268                 (self.prev_span, "unexpected token after this".to_string()),
269             )
270         } else {
271             (
272                 format!("expected {}, found {}", expect, actual),
273                 (self.prev_span.shrink_to_hi(), format!("expected {}", expect)),
274             )
275         };
276         self.last_unexpected_token_span = Some(self.token.span);
277         let mut err = self.struct_span_err(self.token.span, &msg_exp);
278         let sp = if self.token == token::Eof {
279             // This is EOF; don't want to point at the following char, but rather the last token.
280             self.prev_span
281         } else {
282             label_sp
283         };
284         match self.recover_closing_delimiter(
285             &expected
286                 .iter()
287                 .filter_map(|tt| match tt {
288                     TokenType::Token(t) => Some(t.clone()),
289                     _ => None,
290                 })
291                 .collect::<Vec<_>>(),
292             err,
293         ) {
294             Err(e) => err = e,
295             Ok(recovered) => {
296                 return Ok(recovered);
297             }
298         }
299
300         let sm = self.sess.source_map();
301         if self.prev_span == DUMMY_SP {
302             // Account for macro context where the previous span might not be
303             // available to avoid incorrect output (#54841).
304             err.span_label(self.token.span, label_exp);
305         } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
306             // When the spans are in the same line, it means that the only content between
307             // them is whitespace, point at the found token in that case:
308             //
309             // X |     () => { syntax error };
310             //   |                    ^^^^^ expected one of 8 possible tokens here
311             //
312             // instead of having:
313             //
314             // X |     () => { syntax error };
315             //   |                   -^^^^^ unexpected token
316             //   |                   |
317             //   |                   expected one of 8 possible tokens here
318             err.span_label(self.token.span, label_exp);
319         } else {
320             err.span_label(sp, label_exp);
321             err.span_label(self.token.span, "unexpected token");
322         }
323         self.maybe_annotate_with_ascription(&mut err, false);
324         Err(err)
325     }
326
327     pub fn maybe_annotate_with_ascription(
328         &mut self,
329         err: &mut DiagnosticBuilder<'_>,
330         maybe_expected_semicolon: bool,
331     ) {
332         if let Some((sp, likely_path)) = self.last_type_ascription.take() {
333             let sm = self.sess.source_map();
334             let next_pos = sm.lookup_char_pos(self.token.span.lo());
335             let op_pos = sm.lookup_char_pos(sp.hi());
336
337             let allow_unstable = self.sess.unstable_features.is_nightly_build();
338
339             if likely_path {
340                 err.span_suggestion(
341                     sp,
342                     "maybe write a path separator here",
343                     "::".to_string(),
344                     if allow_unstable {
345                         Applicability::MaybeIncorrect
346                     } else {
347                         Applicability::MachineApplicable
348                     },
349                 );
350             } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
351                 err.span_suggestion(
352                     sp,
353                     "try using a semicolon",
354                     ";".to_string(),
355                     Applicability::MaybeIncorrect,
356                 );
357             } else if allow_unstable {
358                 err.span_label(sp, "tried to parse a type due to this type ascription");
359             } else {
360                 err.span_label(sp, "tried to parse a type due to this");
361             }
362             if allow_unstable {
363                 // Give extra information about type ascription only if it's a nightly compiler.
364                 err.note(
365                     "`#![feature(type_ascription)]` lets you annotate an expression with a \
366                           type: `<expr>: <type>`",
367                 );
368                 err.note(
369                     "for more information, see \
370                           https://github.com/rust-lang/rust/issues/23416",
371                 );
372             }
373         }
374     }
375
376     /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
377     /// passes through any errors encountered. Used for error recovery.
378     pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
379         if let Err(ref mut err) =
380             self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
381                 Ok(p.parse_token_tree())
382             })
383         {
384             err.cancel();
385         }
386     }
387
388     /// This function checks if there are trailing angle brackets and produces
389     /// a diagnostic to suggest removing them.
390     ///
391     /// ```ignore (diagnostic)
392     /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
393     ///                                                        ^^ help: remove extra angle brackets
394     /// ```
395     pub(super) fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: TokenKind) {
396         // This function is intended to be invoked after parsing a path segment where there are two
397         // cases:
398         //
399         // 1. A specific token is expected after the path segment.
400         //    eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
401         //        `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
402         // 2. No specific token is expected after the path segment.
403         //    eg. `x.foo` (field access)
404         //
405         // This function is called after parsing `.foo` and before parsing the token `end` (if
406         // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
407         // `Foo::<Bar>`.
408
409         // We only care about trailing angle brackets if we previously parsed angle bracket
410         // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
411         // removed in this case:
412         //
413         // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
414         //
415         // This case is particularly tricky as we won't notice it just looking at the tokens -
416         // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
417         // have already been parsed):
418         //
419         // `x.foo::<u32>>>(3)`
420         let parsed_angle_bracket_args =
421             segment.args.as_ref().map(|args| args.is_angle_bracketed()).unwrap_or(false);
422
423         debug!(
424             "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
425             parsed_angle_bracket_args,
426         );
427         if !parsed_angle_bracket_args {
428             return;
429         }
430
431         // Keep the span at the start so we can highlight the sequence of `>` characters to be
432         // removed.
433         let lo = self.token.span;
434
435         // We need to look-ahead to see if we have `>` characters without moving the cursor forward
436         // (since we might have the field access case and the characters we're eating are
437         // actual operators and not trailing characters - ie `x.foo >> 3`).
438         let mut position = 0;
439
440         // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
441         // many of each (so we can correctly pluralize our error messages) and continue to
442         // advance.
443         let mut number_of_shr = 0;
444         let mut number_of_gt = 0;
445         while self.look_ahead(position, |t| {
446             trace!("check_trailing_angle_brackets: t={:?}", t);
447             if *t == token::BinOp(token::BinOpToken::Shr) {
448                 number_of_shr += 1;
449                 true
450             } else if *t == token::Gt {
451                 number_of_gt += 1;
452                 true
453             } else {
454                 false
455             }
456         }) {
457             position += 1;
458         }
459
460         // If we didn't find any trailing `>` characters, then we have nothing to error about.
461         debug!(
462             "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
463             number_of_gt, number_of_shr,
464         );
465         if number_of_gt < 1 && number_of_shr < 1 {
466             return;
467         }
468
469         // Finally, double check that we have our end token as otherwise this is the
470         // second case.
471         if self.look_ahead(position, |t| {
472             trace!("check_trailing_angle_brackets: t={:?}", t);
473             *t == end
474         }) {
475             // Eat from where we started until the end token so that parsing can continue
476             // as if we didn't have those extra angle brackets.
477             self.eat_to_tokens(&[&end]);
478             let span = lo.until(self.token.span);
479
480             let total_num_of_gt = number_of_gt + number_of_shr * 2;
481             self.struct_span_err(
482                 span,
483                 &format!("unmatched angle bracket{}", pluralize!(total_num_of_gt)),
484             )
485             .span_suggestion(
486                 span,
487                 &format!("remove extra angle bracket{}", pluralize!(total_num_of_gt)),
488                 String::new(),
489                 Applicability::MachineApplicable,
490             )
491             .emit();
492         }
493     }
494
495     /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
496     /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
497     /// parenthesising the leftmost comparison.
498     fn attempt_chained_comparison_suggestion(
499         &mut self,
500         err: &mut DiagnosticBuilder<'_>,
501         inner_op: &Expr,
502         outer_op: &Spanned<AssocOp>,
503     ) {
504         if let ExprKind::Binary(op, ref l1, ref r1) = inner_op.kind {
505             match (op.node, &outer_op.node) {
506                 // `x < y < z` and friends.
507                 (BinOpKind::Lt, AssocOp::Less) | (BinOpKind::Lt, AssocOp::LessEqual) |
508                 (BinOpKind::Le, AssocOp::LessEqual) | (BinOpKind::Le, AssocOp::Less) |
509                 // `x > y > z` and friends.
510                 (BinOpKind::Gt, AssocOp::Greater) | (BinOpKind::Gt, AssocOp::GreaterEqual) |
511                 (BinOpKind::Ge, AssocOp::GreaterEqual) | (BinOpKind::Ge, AssocOp::Greater) => {
512                     let expr_to_str = |e: &Expr| {
513                         self.span_to_snippet(e.span)
514                             .unwrap_or_else(|_| pprust::expr_to_string(&e))
515                     };
516                     err.span_suggestion(
517                         inner_op.span.to(outer_op.span),
518                         "split the comparison into two...",
519                         format!(
520                             "{} {} {} && {} {}",
521                             expr_to_str(&l1),
522                             op.node.to_string(),
523                             expr_to_str(&r1),
524                             expr_to_str(&r1),
525                             outer_op.node.to_ast_binop().unwrap().to_string(),
526                         ),
527                         Applicability::MaybeIncorrect,
528                     );
529                     err.span_suggestion(
530                         inner_op.span.to(outer_op.span),
531                         "...or parenthesize one of the comparisons",
532                         format!(
533                             "({} {} {}) {}",
534                             expr_to_str(&l1),
535                             op.node.to_string(),
536                             expr_to_str(&r1),
537                             outer_op.node.to_ast_binop().unwrap().to_string(),
538                         ),
539                         Applicability::MaybeIncorrect,
540                     );
541                 }
542                 _ => {}
543             }
544         }
545     }
546
547     /// Produces an error if comparison operators are chained (RFC #558).
548     /// We only need to check the LHS, not the RHS, because all comparison ops have same
549     /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
550     ///
551     /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
552     /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
553     /// case.
554     ///
555     /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
556     /// associative we can infer that we have:
557     ///
558     ///           outer_op
559     ///           /   \
560     ///     inner_op   r2
561     ///        /  \
562     ///      l1    r1
563     pub(super) fn check_no_chained_comparison(
564         &mut self,
565         inner_op: &Expr,
566         outer_op: &Spanned<AssocOp>,
567     ) -> PResult<'a, Option<P<Expr>>> {
568         debug_assert!(
569             outer_op.node.is_comparison(),
570             "check_no_chained_comparison: {:?} is not comparison",
571             outer_op.node,
572         );
573
574         let mk_err_expr =
575             |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err, AttrVec::new())));
576
577         match inner_op.kind {
578             ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
579                 // Respan to include both operators.
580                 let op_span = op.span.to(self.prev_span);
581                 let mut err =
582                     self.struct_span_err(op_span, "comparison operators cannot be chained");
583
584                 // If it looks like a genuine attempt to chain operators (as opposed to a
585                 // misformatted turbofish, for instance), suggest a correct form.
586                 self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
587
588                 let suggest = |err: &mut DiagnosticBuilder<'_>| {
589                     err.span_suggestion_verbose(
590                         op_span.shrink_to_lo(),
591                         TURBOFISH,
592                         "::".to_string(),
593                         Applicability::MaybeIncorrect,
594                     );
595                 };
596
597                 if op.node == BinOpKind::Lt &&
598                     outer_op.node == AssocOp::Less ||  // Include `<` to provide this recommendation
599                     outer_op.node == AssocOp::Greater
600                 // even in a case like the following:
601                 {
602                     //     Foo<Bar<Baz<Qux, ()>>>
603                     if outer_op.node == AssocOp::Less {
604                         let snapshot = self.clone();
605                         self.bump();
606                         // So far we have parsed `foo<bar<`, consume the rest of the type args.
607                         let modifiers =
608                             [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
609                         self.consume_tts(1, &modifiers[..]);
610
611                         if !&[token::OpenDelim(token::Paren), token::ModSep]
612                             .contains(&self.token.kind)
613                         {
614                             // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
615                             // parser and bail out.
616                             mem::replace(self, snapshot.clone());
617                         }
618                     }
619                     return if token::ModSep == self.token.kind {
620                         // We have some certainty that this was a bad turbofish at this point.
621                         // `foo< bar >::`
622                         suggest(&mut err);
623
624                         let snapshot = self.clone();
625                         self.bump(); // `::`
626
627                         // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
628                         match self.parse_expr() {
629                             Ok(_) => {
630                                 // 99% certain that the suggestion is correct, continue parsing.
631                                 err.emit();
632                                 // FIXME: actually check that the two expressions in the binop are
633                                 // paths and resynthesize new fn call expression instead of using
634                                 // `ExprKind::Err` placeholder.
635                                 mk_err_expr(self, inner_op.span.to(self.prev_span))
636                             }
637                             Err(mut expr_err) => {
638                                 expr_err.cancel();
639                                 // Not entirely sure now, but we bubble the error up with the
640                                 // suggestion.
641                                 mem::replace(self, snapshot);
642                                 Err(err)
643                             }
644                         }
645                     } else if token::OpenDelim(token::Paren) == self.token.kind {
646                         // We have high certainty that this was a bad turbofish at this point.
647                         // `foo< bar >(`
648                         suggest(&mut err);
649                         // Consume the fn call arguments.
650                         match self.consume_fn_args() {
651                             Err(()) => Err(err),
652                             Ok(()) => {
653                                 err.emit();
654                                 // FIXME: actually check that the two expressions in the binop are
655                                 // paths and resynthesize new fn call expression instead of using
656                                 // `ExprKind::Err` placeholder.
657                                 mk_err_expr(self, inner_op.span.to(self.prev_span))
658                             }
659                         }
660                     } else {
661                         // All we know is that this is `foo < bar >` and *nothing* else. Try to
662                         // be helpful, but don't attempt to recover.
663                         err.help(TURBOFISH);
664                         err.help("or use `(...)` if you meant to specify fn arguments");
665                         // These cases cause too many knock-down errors, bail out (#61329).
666                         Err(err)
667                     };
668                 }
669                 err.emit();
670             }
671             _ => {}
672         }
673         Ok(None)
674     }
675
676     fn consume_fn_args(&mut self) -> Result<(), ()> {
677         let snapshot = self.clone();
678         self.bump(); // `(`
679
680         // Consume the fn call arguments.
681         let modifiers =
682             [(token::OpenDelim(token::Paren), 1), (token::CloseDelim(token::Paren), -1)];
683         self.consume_tts(1, &modifiers[..]);
684
685         if self.token.kind == token::Eof {
686             // Not entirely sure that what we consumed were fn arguments, rollback.
687             mem::replace(self, snapshot);
688             Err(())
689         } else {
690             // 99% certain that the suggestion is correct, continue parsing.
691             Ok(())
692         }
693     }
694
695     pub(super) fn maybe_report_ambiguous_plus(
696         &mut self,
697         allow_plus: bool,
698         impl_dyn_multi: bool,
699         ty: &Ty,
700     ) {
701         if !allow_plus && impl_dyn_multi {
702             let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
703             self.struct_span_err(ty.span, "ambiguous `+` in a type")
704                 .span_suggestion(
705                     ty.span,
706                     "use parentheses to disambiguate",
707                     sum_with_parens,
708                     Applicability::MachineApplicable,
709                 )
710                 .emit();
711         }
712     }
713
714     pub(super) fn maybe_recover_from_bad_type_plus(
715         &mut self,
716         allow_plus: bool,
717         ty: &Ty,
718     ) -> PResult<'a, ()> {
719         // Do not add `+` to expected tokens.
720         if !allow_plus || !self.token.is_like_plus() {
721             return Ok(());
722         }
723
724         self.bump(); // `+`
725         let bounds = self.parse_generic_bounds(None)?;
726         let sum_span = ty.span.to(self.prev_span);
727
728         let mut err = struct_span_err!(
729             self.sess.span_diagnostic,
730             sum_span,
731             E0178,
732             "expected a path on the left-hand side of `+`, not `{}`",
733             pprust::ty_to_string(ty)
734         );
735
736         match ty.kind {
737             TyKind::Rptr(ref lifetime, ref mut_ty) => {
738                 let sum_with_parens = pprust::to_string(|s| {
739                     s.s.word("&");
740                     s.print_opt_lifetime(lifetime);
741                     s.print_mutability(mut_ty.mutbl, false);
742                     s.popen();
743                     s.print_type(&mut_ty.ty);
744                     s.print_type_bounds(" +", &bounds);
745                     s.pclose()
746                 });
747                 err.span_suggestion(
748                     sum_span,
749                     "try adding parentheses",
750                     sum_with_parens,
751                     Applicability::MachineApplicable,
752                 );
753             }
754             TyKind::Ptr(..) | TyKind::BareFn(..) => {
755                 err.span_label(sum_span, "perhaps you forgot parentheses?");
756             }
757             _ => {
758                 err.span_label(sum_span, "expected a path");
759             }
760         }
761         err.emit();
762         Ok(())
763     }
764
765     /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
766     /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
767     /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
768     pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
769         &mut self,
770         base: P<T>,
771         allow_recovery: bool,
772     ) -> PResult<'a, P<T>> {
773         // Do not add `::` to expected tokens.
774         if allow_recovery && self.token == token::ModSep {
775             if let Some(ty) = base.to_ty() {
776                 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
777             }
778         }
779         Ok(base)
780     }
781
782     /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
783     /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
784     pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
785         &mut self,
786         ty_span: Span,
787         ty: P<Ty>,
788     ) -> PResult<'a, P<T>> {
789         self.expect(&token::ModSep)?;
790
791         let mut path = ast::Path { segments: Vec::new(), span: DUMMY_SP };
792         self.parse_path_segments(&mut path.segments, T::PATH_STYLE)?;
793         path.span = ty_span.to(self.prev_span);
794
795         let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
796         self.struct_span_err(path.span, "missing angle brackets in associated item path")
797             .span_suggestion(
798                 // This is a best-effort recovery.
799                 path.span,
800                 "try",
801                 format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
802                 Applicability::MaybeIncorrect,
803             )
804             .emit();
805
806         let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
807         Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path)))
808     }
809
810     pub(super) fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
811         if self.eat(&token::Semi) {
812             let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`");
813             err.span_suggestion_short(
814                 self.prev_span,
815                 "remove this semicolon",
816                 String::new(),
817                 Applicability::MachineApplicable,
818             );
819             if !items.is_empty() {
820                 let previous_item = &items[items.len() - 1];
821                 let previous_item_kind_name = match previous_item.kind {
822                     // Say "braced struct" because tuple-structs and
823                     // braceless-empty-struct declarations do take a semicolon.
824                     ItemKind::Struct(..) => Some("braced struct"),
825                     ItemKind::Enum(..) => Some("enum"),
826                     ItemKind::Trait(..) => Some("trait"),
827                     ItemKind::Union(..) => Some("union"),
828                     _ => None,
829                 };
830                 if let Some(name) = previous_item_kind_name {
831                     err.help(&format!("{} declarations are not followed by a semicolon", name));
832                 }
833             }
834             err.emit();
835             true
836         } else {
837             false
838         }
839     }
840
841     /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
842     /// closing delimiter.
843     pub(super) fn unexpected_try_recover(
844         &mut self,
845         t: &TokenKind,
846     ) -> PResult<'a, bool /* recovered */> {
847         let token_str = pprust::token_kind_to_string(t);
848         let this_token_str = super::token_descr(&self.token);
849         let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
850             // Point at the end of the macro call when reaching end of macro arguments.
851             (token::Eof, Some(_)) => {
852                 let sp = self.sess.source_map().next_point(self.token.span);
853                 (sp, sp)
854             }
855             // We don't want to point at the following span after DUMMY_SP.
856             // This happens when the parser finds an empty TokenStream.
857             _ if self.prev_span == DUMMY_SP => (self.token.span, self.token.span),
858             // EOF, don't want to point at the following char, but rather the last token.
859             (token::Eof, None) => (self.prev_span, self.token.span),
860             _ => (self.prev_span.shrink_to_hi(), self.token.span),
861         };
862         let msg = format!(
863             "expected `{}`, found {}",
864             token_str,
865             match (&self.token.kind, self.subparser_name) {
866                 (token::Eof, Some(origin)) => format!("end of {}", origin),
867                 _ => this_token_str,
868             },
869         );
870         let mut err = self.struct_span_err(sp, &msg);
871         let label_exp = format!("expected `{}`", token_str);
872         match self.recover_closing_delimiter(&[t.clone()], err) {
873             Err(e) => err = e,
874             Ok(recovered) => {
875                 return Ok(recovered);
876             }
877         }
878         let sm = self.sess.source_map();
879         if !sm.is_multiline(prev_sp.until(sp)) {
880             // When the spans are in the same line, it means that the only content
881             // between them is whitespace, point only at the found token.
882             err.span_label(sp, label_exp);
883         } else {
884             err.span_label(prev_sp, label_exp);
885             err.span_label(sp, "unexpected token");
886         }
887         Err(err)
888     }
889
890     pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
891         if self.eat(&token::Semi) {
892             return Ok(());
893         }
894         let sm = self.sess.source_map();
895         let msg = format!("expected `;`, found `{}`", super::token_descr(&self.token));
896         let appl = Applicability::MachineApplicable;
897         if self.token.span == DUMMY_SP || self.prev_span == DUMMY_SP {
898             // Likely inside a macro, can't provide meaninful suggestions.
899             return self.expect(&token::Semi).map(drop);
900         } else if !sm.is_multiline(self.prev_span.until(self.token.span)) {
901             // The current token is in the same line as the prior token, not recoverable.
902         } else if self.look_ahead(1, |t| {
903             t == &token::CloseDelim(token::Brace)
904                 || token_can_begin_expr(t) && t.kind != token::Colon
905         }) && [token::Comma, token::Colon].contains(&self.token.kind)
906         {
907             // Likely typo: `,` â†’ `;` or `:` â†’ `;`. This is triggered if the current token is
908             // either `,` or `:`, and the next token could either start a new statement or is a
909             // block close. For example:
910             //
911             //   let x = 32:
912             //   let y = 42;
913             self.bump();
914             let sp = self.prev_span;
915             self.struct_span_err(sp, &msg)
916                 .span_suggestion(sp, "change this to `;`", ";".to_string(), appl)
917                 .emit();
918             return Ok(());
919         } else if self.look_ahead(0, |t| {
920             t == &token::CloseDelim(token::Brace)
921                 || (
922                     token_can_begin_expr(t) && t != &token::Semi && t != &token::Pound
923                     // Avoid triggering with too many trailing `#` in raw string.
924                 )
925         }) {
926             // Missing semicolon typo. This is triggered if the next token could either start a
927             // new statement or is a block close. For example:
928             //
929             //   let x = 32
930             //   let y = 42;
931             let sp = self.prev_span.shrink_to_hi();
932             self.struct_span_err(sp, &msg)
933                 .span_label(self.token.span, "unexpected token")
934                 .span_suggestion_short(sp, "add `;` here", ";".to_string(), appl)
935                 .emit();
936             return Ok(());
937         }
938         self.expect(&token::Semi).map(drop) // Error unconditionally
939     }
940
941     pub(super) fn parse_semi_or_incorrect_foreign_fn_body(
942         &mut self,
943         ident: &Ident,
944         extern_sp: Span,
945     ) -> PResult<'a, ()> {
946         if self.token != token::Semi {
947             // This might be an incorrect fn definition (#62109).
948             let parser_snapshot = self.clone();
949             match self.parse_inner_attrs_and_block() {
950                 Ok((_, body)) => {
951                     self.struct_span_err(ident.span, "incorrect `fn` inside `extern` block")
952                         .span_label(ident.span, "can't have a body")
953                         .span_label(body.span, "this body is invalid here")
954                         .span_label(
955                             extern_sp,
956                             "`extern` blocks define existing foreign functions and `fn`s \
957                              inside of them cannot have a body",
958                         )
959                         .help(
960                             "you might have meant to write a function accessible through ffi, \
961                                which can be done by writing `extern fn` outside of the \
962                                `extern` block",
963                         )
964                         .note(
965                             "for more information, visit \
966                                https://doc.rust-lang.org/std/keyword.extern.html",
967                         )
968                         .emit();
969                 }
970                 Err(mut err) => {
971                     err.cancel();
972                     mem::replace(self, parser_snapshot);
973                     self.expect_semi()?;
974                 }
975             }
976         } else {
977             self.bump();
978         }
979         Ok(())
980     }
981
982     /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
983     /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
984     pub(super) fn recover_incorrect_await_syntax(
985         &mut self,
986         lo: Span,
987         await_sp: Span,
988         attrs: AttrVec,
989     ) -> PResult<'a, P<Expr>> {
990         let (hi, expr, is_question) = if self.token == token::Not {
991             // Handle `await!(<expr>)`.
992             self.recover_await_macro()?
993         } else {
994             self.recover_await_prefix(await_sp)?
995         };
996         let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
997         let expr = self.mk_expr(lo.to(sp), ExprKind::Await(expr), attrs);
998         self.maybe_recover_from_bad_qpath(expr, true)
999     }
1000
1001     fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1002         self.expect(&token::Not)?;
1003         self.expect(&token::OpenDelim(token::Paren))?;
1004         let expr = self.parse_expr()?;
1005         self.expect(&token::CloseDelim(token::Paren))?;
1006         Ok((self.prev_span, expr, false))
1007     }
1008
1009     fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
1010         let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
1011         let expr = if self.token == token::OpenDelim(token::Brace) {
1012             // Handle `await { <expr> }`.
1013             // This needs to be handled separatedly from the next arm to avoid
1014             // interpreting `await { <expr> }?` as `<expr>?.await`.
1015             self.parse_block_expr(None, self.token.span, BlockCheckMode::Default, AttrVec::new())
1016         } else {
1017             self.parse_expr()
1018         }
1019         .map_err(|mut err| {
1020             err.span_label(await_sp, "while parsing this incorrect await expression");
1021             err
1022         })?;
1023         Ok((expr.span, expr, is_question))
1024     }
1025
1026     fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
1027         let expr_str =
1028             self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr));
1029         let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" });
1030         let sp = lo.to(hi);
1031         let app = match expr.kind {
1032             ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
1033             _ => Applicability::MachineApplicable,
1034         };
1035         self.struct_span_err(sp, "incorrect use of `await`")
1036             .span_suggestion(sp, "`await` is a postfix operation", suggestion, app)
1037             .emit();
1038         sp
1039     }
1040
1041     /// If encountering `future.await()`, consumes and emits an error.
1042     pub(super) fn recover_from_await_method_call(&mut self) {
1043         if self.token == token::OpenDelim(token::Paren)
1044             && self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren))
1045         {
1046             // future.await()
1047             let lo = self.token.span;
1048             self.bump(); // (
1049             let sp = lo.to(self.token.span);
1050             self.bump(); // )
1051             self.struct_span_err(sp, "incorrect use of `await`")
1052                 .span_suggestion(
1053                     sp,
1054                     "`await` is not a method call, remove the parentheses",
1055                     String::new(),
1056                     Applicability::MachineApplicable,
1057                 )
1058                 .emit()
1059         }
1060     }
1061
1062     /// Recovers a situation like `for ( $pat in $expr )`
1063     /// and suggest writing `for $pat in $expr` instead.
1064     ///
1065     /// This should be called before parsing the `$block`.
1066     pub(super) fn recover_parens_around_for_head(
1067         &mut self,
1068         pat: P<Pat>,
1069         expr: &Expr,
1070         begin_paren: Option<Span>,
1071     ) -> P<Pat> {
1072         match (&self.token.kind, begin_paren) {
1073             (token::CloseDelim(token::Paren), Some(begin_par_sp)) => {
1074                 self.bump();
1075
1076                 let pat_str = self
1077                     // Remove the `(` from the span of the pattern:
1078                     .span_to_snippet(pat.span.trim_start(begin_par_sp).unwrap())
1079                     .unwrap_or_else(|_| pprust::pat_to_string(&pat));
1080
1081                 self.struct_span_err(self.prev_span, "unexpected closing `)`")
1082                     .span_label(begin_par_sp, "opening `(`")
1083                     .span_suggestion(
1084                         begin_par_sp.to(self.prev_span),
1085                         "remove parenthesis in `for` loop",
1086                         format!("{} in {}", pat_str, pprust::expr_to_string(&expr)),
1087                         // With e.g. `for (x) in y)` this would replace `(x) in y)`
1088                         // with `x) in y)` which is syntactically invalid.
1089                         // However, this is prevented before we get here.
1090                         Applicability::MachineApplicable,
1091                     )
1092                     .emit();
1093
1094                 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1095                 pat.and_then(|pat| match pat.kind {
1096                     PatKind::Paren(pat) => pat,
1097                     _ => P(pat),
1098                 })
1099             }
1100             _ => pat,
1101         }
1102     }
1103
1104     pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1105         (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1106             self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1107             || self.token.is_ident() &&
1108             match node {
1109                 // `foo::` â†’ `foo:` or `foo.bar::` â†’ `foo.bar:`
1110                 ast::ExprKind::Path(..) | ast::ExprKind::Field(..) => true,
1111                 _ => false,
1112             } &&
1113             !self.token.is_reserved_ident() &&           // v `foo:bar(baz)`
1114             self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren))
1115             || self.look_ahead(1, |t| t == &token::Lt) &&     // `foo:bar<baz`
1116             self.look_ahead(2, |t| t.is_ident())
1117             || self.look_ahead(1, |t| t == &token::Colon) &&  // `foo:bar:baz`
1118             self.look_ahead(2, |t| t.is_ident())
1119             || self.look_ahead(1, |t| t == &token::ModSep)
1120                 && (self.look_ahead(2, |t| t.is_ident()) ||   // `foo:bar::baz`
1121              self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1122     }
1123
1124     pub(super) fn recover_seq_parse_error(
1125         &mut self,
1126         delim: token::DelimToken,
1127         lo: Span,
1128         result: PResult<'a, P<Expr>>,
1129     ) -> P<Expr> {
1130         match result {
1131             Ok(x) => x,
1132             Err(mut err) => {
1133                 err.emit();
1134                 // Recover from parse error, callers expect the closing delim to be consumed.
1135                 self.consume_block(delim, ConsumeClosingDelim::Yes);
1136                 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, AttrVec::new())
1137             }
1138         }
1139     }
1140
1141     pub(super) fn recover_closing_delimiter(
1142         &mut self,
1143         tokens: &[TokenKind],
1144         mut err: DiagnosticBuilder<'a>,
1145     ) -> PResult<'a, bool> {
1146         let mut pos = None;
1147         // We want to use the last closing delim that would apply.
1148         for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1149             if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1150                 && Some(self.token.span) > unmatched.unclosed_span
1151             {
1152                 pos = Some(i);
1153             }
1154         }
1155         match pos {
1156             Some(pos) => {
1157                 // Recover and assume that the detected unclosed delimiter was meant for
1158                 // this location. Emit the diagnostic and act as if the delimiter was
1159                 // present for the parser's sake.
1160
1161                 // Don't attempt to recover from this unclosed delimiter more than once.
1162                 let unmatched = self.unclosed_delims.remove(pos);
1163                 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1164                 if unmatched.found_delim.is_none() {
1165                     // We encountered `Eof`, set this fact here to avoid complaining about missing
1166                     // `fn main()` when we found place to suggest the closing brace.
1167                     *self.sess.reached_eof.borrow_mut() = true;
1168                 }
1169
1170                 // We want to suggest the inclusion of the closing delimiter where it makes
1171                 // the most sense, which is immediately after the last token:
1172                 //
1173                 //  {foo(bar {}}
1174                 //      -      ^
1175                 //      |      |
1176                 //      |      help: `)` may belong here
1177                 //      |
1178                 //      unclosed delimiter
1179                 if let Some(sp) = unmatched.unclosed_span {
1180                     err.span_label(sp, "unclosed delimiter");
1181                 }
1182                 err.span_suggestion_short(
1183                     self.prev_span.shrink_to_hi(),
1184                     &format!("{} may belong here", delim.to_string()),
1185                     delim.to_string(),
1186                     Applicability::MaybeIncorrect,
1187                 );
1188                 if unmatched.found_delim.is_none() {
1189                     // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1190                     // errors which would be emitted elsewhere in the parser and let other error
1191                     // recovery consume the rest of the file.
1192                     Err(err)
1193                 } else {
1194                     err.emit();
1195                     self.expected_tokens.clear(); // Reduce the number of errors.
1196                     Ok(true)
1197                 }
1198             }
1199             _ => Err(err),
1200         }
1201     }
1202
1203     /// Eats tokens until we can be relatively sure we reached the end of the
1204     /// statement. This is something of a best-effort heuristic.
1205     ///
1206     /// We terminate when we find an unmatched `}` (without consuming it).
1207     pub(super) fn recover_stmt(&mut self) {
1208         self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1209     }
1210
1211     /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1212     /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1213     /// approximate -- it can mean we break too early due to macros, but that
1214     /// should only lead to sub-optimal recovery, not inaccurate parsing).
1215     ///
1216     /// If `break_on_block` is `Break`, then we will stop consuming tokens
1217     /// after finding (and consuming) a brace-delimited block.
1218     pub(super) fn recover_stmt_(
1219         &mut self,
1220         break_on_semi: SemiColonMode,
1221         break_on_block: BlockMode,
1222     ) {
1223         let mut brace_depth = 0;
1224         let mut bracket_depth = 0;
1225         let mut in_block = false;
1226         debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1227         loop {
1228             debug!("recover_stmt_ loop {:?}", self.token);
1229             match self.token.kind {
1230                 token::OpenDelim(token::DelimToken::Brace) => {
1231                     brace_depth += 1;
1232                     self.bump();
1233                     if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1234                     {
1235                         in_block = true;
1236                     }
1237                 }
1238                 token::OpenDelim(token::DelimToken::Bracket) => {
1239                     bracket_depth += 1;
1240                     self.bump();
1241                 }
1242                 token::CloseDelim(token::DelimToken::Brace) => {
1243                     if brace_depth == 0 {
1244                         debug!("recover_stmt_ return - close delim {:?}", self.token);
1245                         break;
1246                     }
1247                     brace_depth -= 1;
1248                     self.bump();
1249                     if in_block && bracket_depth == 0 && brace_depth == 0 {
1250                         debug!("recover_stmt_ return - block end {:?}", self.token);
1251                         break;
1252                     }
1253                 }
1254                 token::CloseDelim(token::DelimToken::Bracket) => {
1255                     bracket_depth -= 1;
1256                     if bracket_depth < 0 {
1257                         bracket_depth = 0;
1258                     }
1259                     self.bump();
1260                 }
1261                 token::Eof => {
1262                     debug!("recover_stmt_ return - Eof");
1263                     break;
1264                 }
1265                 token::Semi => {
1266                     self.bump();
1267                     if break_on_semi == SemiColonMode::Break
1268                         && brace_depth == 0
1269                         && bracket_depth == 0
1270                     {
1271                         debug!("recover_stmt_ return - Semi");
1272                         break;
1273                     }
1274                 }
1275                 token::Comma
1276                     if break_on_semi == SemiColonMode::Comma
1277                         && brace_depth == 0
1278                         && bracket_depth == 0 =>
1279                 {
1280                     debug!("recover_stmt_ return - Semi");
1281                     break;
1282                 }
1283                 _ => self.bump(),
1284             }
1285         }
1286     }
1287
1288     pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1289         if self.eat_keyword(kw::In) {
1290             // a common typo: `for _ in in bar {}`
1291             self.struct_span_err(self.prev_span, "expected iterable, found keyword `in`")
1292                 .span_suggestion_short(
1293                     in_span.until(self.prev_span),
1294                     "remove the duplicated `in`",
1295                     String::new(),
1296                     Applicability::MachineApplicable,
1297                 )
1298                 .emit();
1299         }
1300     }
1301
1302     pub(super) fn expected_semi_or_open_brace<T>(&mut self) -> PResult<'a, T> {
1303         let token_str = super::token_descr(&self.token);
1304         let msg = &format!("expected `;` or `{{`, found {}", token_str);
1305         let mut err = self.struct_span_err(self.token.span, msg);
1306         err.span_label(self.token.span, "expected `;` or `{`");
1307         Err(err)
1308     }
1309
1310     pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1311         if let token::DocComment(_) = self.token.kind {
1312             self.struct_span_err(
1313                 self.token.span,
1314                 "documentation comments cannot be applied to a function parameter's type",
1315             )
1316             .span_label(self.token.span, "doc comments are not allowed here")
1317             .emit();
1318             self.bump();
1319         } else if self.token == token::Pound
1320             && self.look_ahead(1, |t| *t == token::OpenDelim(token::Bracket))
1321         {
1322             let lo = self.token.span;
1323             // Skip every token until next possible arg.
1324             while self.token != token::CloseDelim(token::Bracket) {
1325                 self.bump();
1326             }
1327             let sp = lo.to(self.token.span);
1328             self.bump();
1329             self.struct_span_err(sp, "attributes cannot be applied to a function parameter's type")
1330                 .span_label(sp, "attributes are not allowed here")
1331                 .emit();
1332         }
1333     }
1334
1335     pub(super) fn parameter_without_type(
1336         &mut self,
1337         err: &mut DiagnosticBuilder<'_>,
1338         pat: P<ast::Pat>,
1339         require_name: bool,
1340         is_self_allowed: bool,
1341         is_trait_item: bool,
1342     ) -> Option<Ident> {
1343         // If we find a pattern followed by an identifier, it could be an (incorrect)
1344         // C-style parameter declaration.
1345         if self.check_ident()
1346             && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseDelim(token::Paren))
1347         {
1348             // `fn foo(String s) {}`
1349             let ident = self.parse_ident().unwrap();
1350             let span = pat.span.with_hi(ident.span.hi());
1351
1352             err.span_suggestion(
1353                 span,
1354                 "declare the type after the parameter binding",
1355                 String::from("<identifier>: <type>"),
1356                 Applicability::HasPlaceholders,
1357             );
1358             return Some(ident);
1359         } else if let PatKind::Ident(_, ident, _) = pat.kind {
1360             if require_name
1361                 && (is_trait_item
1362                     || self.token == token::Comma
1363                     || self.token == token::Lt
1364                     || self.token == token::CloseDelim(token::Paren))
1365             {
1366                 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1367                 if is_self_allowed {
1368                     err.span_suggestion(
1369                         pat.span,
1370                         "if this is a `self` type, give it a parameter name",
1371                         format!("self: {}", ident),
1372                         Applicability::MaybeIncorrect,
1373                     );
1374                 }
1375                 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
1376                 // `fn foo(HashMap: TypeName<u32>)`.
1377                 if self.token != token::Lt {
1378                     err.span_suggestion(
1379                         pat.span,
1380                         "if this was a parameter name, give it a type",
1381                         format!("{}: TypeName", ident),
1382                         Applicability::HasPlaceholders,
1383                     );
1384                 }
1385                 err.span_suggestion(
1386                     pat.span,
1387                     "if this is a type, explicitly ignore the parameter name",
1388                     format!("_: {}", ident),
1389                     Applicability::MachineApplicable,
1390                 );
1391                 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1392
1393                 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
1394                 return if self.token == token::Lt { None } else { Some(ident) };
1395             }
1396         }
1397         None
1398     }
1399
1400     pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
1401         let pat = self.parse_pat(Some("argument name"))?;
1402         self.expect(&token::Colon)?;
1403         let ty = self.parse_ty()?;
1404
1405         struct_span_err!(
1406             self.diagnostic(),
1407             pat.span,
1408             E0642,
1409             "patterns aren't allowed in methods without bodies",
1410         )
1411         .span_suggestion_short(
1412             pat.span,
1413             "give this argument a name or use an underscore to ignore it",
1414             "_".to_owned(),
1415             Applicability::MachineApplicable,
1416         )
1417         .emit();
1418
1419         // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1420         let pat = P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID });
1421         Ok((pat, ty))
1422     }
1423
1424     pub(super) fn recover_bad_self_param(
1425         &mut self,
1426         mut param: ast::Param,
1427         is_trait_item: bool,
1428     ) -> PResult<'a, ast::Param> {
1429         let sp = param.pat.span;
1430         param.ty.kind = TyKind::Err;
1431         let mut err = self.struct_span_err(sp, "unexpected `self` parameter in function");
1432         if is_trait_item {
1433             err.span_label(sp, "must be the first associated function parameter");
1434         } else {
1435             err.span_label(sp, "not valid as function parameter");
1436             err.note("`self` is only valid as the first parameter of an associated function");
1437         }
1438         err.emit();
1439         Ok(param)
1440     }
1441
1442     pub(super) fn consume_block(
1443         &mut self,
1444         delim: token::DelimToken,
1445         consume_close: ConsumeClosingDelim,
1446     ) {
1447         let mut brace_depth = 0;
1448         loop {
1449             if self.eat(&token::OpenDelim(delim)) {
1450                 brace_depth += 1;
1451             } else if self.check(&token::CloseDelim(delim)) {
1452                 if brace_depth == 0 {
1453                     if let ConsumeClosingDelim::Yes = consume_close {
1454                         // Some of the callers of this method expect to be able to parse the
1455                         // closing delimiter themselves, so we leave it alone. Otherwise we advance
1456                         // the parser.
1457                         self.bump();
1458                     }
1459                     return;
1460                 } else {
1461                     self.bump();
1462                     brace_depth -= 1;
1463                     continue;
1464                 }
1465             } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
1466                 return;
1467             } else {
1468                 self.bump();
1469             }
1470         }
1471     }
1472
1473     pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a> {
1474         let (span, msg) = match (&self.token.kind, self.subparser_name) {
1475             (&token::Eof, Some(origin)) => {
1476                 let sp = self.sess.source_map().next_point(self.token.span);
1477                 (sp, format!("expected expression, found end of {}", origin))
1478             }
1479             _ => (
1480                 self.token.span,
1481                 format!("expected expression, found {}", super::token_descr(&self.token),),
1482             ),
1483         };
1484         let mut err = self.struct_span_err(span, &msg);
1485         let sp = self.sess.source_map().start_point(self.token.span);
1486         if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
1487             self.sess.expr_parentheses_needed(&mut err, *sp, None);
1488         }
1489         err.span_label(span, "expected expression");
1490         err
1491     }
1492
1493     fn consume_tts(
1494         &mut self,
1495         mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
1496         // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
1497         modifier: &[(token::TokenKind, i64)],
1498     ) {
1499         while acc > 0 {
1500             if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
1501                 acc += *val;
1502             }
1503             if self.token.kind == token::Eof {
1504                 break;
1505             }
1506             self.bump();
1507         }
1508     }
1509
1510     /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
1511     ///
1512     /// This is necessary because at this point we don't know whether we parsed a function with
1513     /// anonymous parameters or a function with names but no types. In order to minimize
1514     /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
1515     /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
1516     /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
1517     /// we deduplicate them to not complain about duplicated parameter names.
1518     pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
1519         let mut seen_inputs = FxHashSet::default();
1520         for input in fn_inputs.iter_mut() {
1521             let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
1522                 (&input.pat.kind, &input.ty.kind)
1523             {
1524                 Some(*ident)
1525             } else {
1526                 None
1527             };
1528             if let Some(ident) = opt_ident {
1529                 if seen_inputs.contains(&ident) {
1530                     input.pat.kind = PatKind::Wild;
1531                 }
1532                 seen_inputs.insert(ident);
1533             }
1534         }
1535     }
1536 }