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