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