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