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