1 use super::ty::AllowPlus;
2 use super::{BlockMode, Parser, PathStyle, SemiColonMode, SeqSep, TokenExpectType, TokenType};
5 self, AngleBracketedArgs, AttrVec, BinOpKind, BindingMode, BlockCheckMode, Expr, ExprKind,
6 Item, ItemKind, Mutability, Param, Pat, PatKind, PathSegment, QSelf, Ty, TyKind,
9 use rustc_ast::token::{self, Lit, LitKind, TokenKind};
10 use rustc_ast::util::parser::AssocOp;
11 use rustc_ast_pretty::pprust;
12 use rustc_data_structures::fx::FxHashSet;
13 use rustc_errors::{pluralize, struct_span_err};
14 use rustc_errors::{Applicability, DiagnosticBuilder, Handler, PResult};
15 use rustc_span::source_map::Spanned;
16 use rustc_span::symbol::{kw, Ident};
17 use rustc_span::{MultiSpan, Span, SpanSnippetError, DUMMY_SP};
19 use log::{debug, trace};
21 const TURBOFISH: &str = "use `::<...>` instead of `<...>` to specify type arguments";
23 /// Creates a placeholder argument.
24 pub(super) fn dummy_arg(ident: Ident) -> Param {
26 id: ast::DUMMY_NODE_ID,
27 kind: PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None),
30 let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID };
32 attrs: AttrVec::default(),
33 id: ast::DUMMY_NODE_ID,
37 is_placeholder: false,
46 fn span_err(self, sp: impl Into<MultiSpan>, handler: &Handler) -> DiagnosticBuilder<'_> {
48 Error::UselessDocComment => {
49 let mut err = struct_span_err!(
53 "found a documentation comment that doesn't document anything",
56 "doc comments must come before what they document, maybe a comment was \
65 pub(super) trait RecoverQPath: Sized + 'static {
66 const PATH_STYLE: PathStyle = PathStyle::Expr;
67 fn to_ty(&self) -> Option<P<Ty>>;
68 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
71 impl RecoverQPath for Ty {
72 const PATH_STYLE: PathStyle = PathStyle::Type;
73 fn to_ty(&self) -> Option<P<Ty>> {
76 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
77 Self { span: path.span, kind: TyKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
81 impl RecoverQPath for Pat {
82 fn to_ty(&self) -> Option<P<Ty>> {
85 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
86 Self { span: path.span, kind: PatKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
90 impl RecoverQPath for Expr {
91 fn to_ty(&self) -> Option<P<Ty>> {
94 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
97 kind: ExprKind::Path(qself, path),
98 attrs: AttrVec::new(),
99 id: ast::DUMMY_NODE_ID,
105 /// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
106 crate enum ConsumeClosingDelim {
111 impl<'a> Parser<'a> {
112 pub(super) fn span_fatal_err<S: Into<MultiSpan>>(
116 ) -> DiagnosticBuilder<'a> {
117 err.span_err(sp, self.diagnostic())
120 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
121 self.sess.span_diagnostic.struct_span_err(sp, m)
124 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
125 self.sess.span_diagnostic.span_bug(sp, m)
128 pub(super) fn diagnostic(&self) -> &'a Handler {
129 &self.sess.span_diagnostic
132 pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
133 self.sess.source_map().span_to_snippet(span)
136 pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
137 let mut err = self.struct_span_err(
139 &format!("expected identifier, found {}", super::token_descr(&self.token)),
141 let valid_follow = &[
147 TokenKind::OpenDelim(token::DelimToken::Brace),
148 TokenKind::OpenDelim(token::DelimToken::Paren),
149 TokenKind::CloseDelim(token::DelimToken::Brace),
150 TokenKind::CloseDelim(token::DelimToken::Paren),
152 match self.token.ident() {
154 if ident.is_raw_guess()
155 && self.look_ahead(1, |t| valid_follow.contains(&t.kind)) =>
159 "you can escape reserved keywords to use them as identifiers",
160 format!("r#{}", ident.name),
161 Applicability::MaybeIncorrect,
166 if let Some(token_descr) = super::token_descr_opt(&self.token) {
167 err.span_label(self.token.span, format!("expected identifier, found {}", token_descr));
169 err.span_label(self.token.span, "expected identifier");
170 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
175 Applicability::MachineApplicable,
182 pub(super) fn expected_one_of_not_found(
184 edible: &[TokenKind],
185 inedible: &[TokenKind],
186 ) -> PResult<'a, bool /* recovered */> {
187 fn tokens_to_string(tokens: &[TokenType]) -> String {
188 let mut i = tokens.iter();
189 // This might be a sign we need a connect method on `Iterator`.
190 let b = i.next().map_or(String::new(), |t| t.to_string());
191 i.enumerate().fold(b, |mut b, (i, a)| {
192 if tokens.len() > 2 && i == tokens.len() - 2 {
194 } else if tokens.len() == 2 && i == tokens.len() - 2 {
199 b.push_str(&a.to_string());
204 let mut expected = edible
206 .map(|x| TokenType::Token(x.clone()))
207 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
208 .chain(self.expected_tokens.iter().cloned())
209 .collect::<Vec<_>>();
210 expected.sort_by_cached_key(|x| x.to_string());
212 let expect = tokens_to_string(&expected[..]);
213 let actual = super::token_descr(&self.token);
214 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
215 let short_expect = if expected.len() > 6 {
216 format!("{} possible tokens", expected.len())
221 format!("expected one of {}, found {}", expect, actual),
222 (self.prev_token.span.shrink_to_hi(), format!("expected one of {}", short_expect)),
224 } else if expected.is_empty() {
226 format!("unexpected token: {}", actual),
227 (self.prev_token.span, "unexpected token after this".to_string()),
231 format!("expected {}, found {}", expect, actual),
232 (self.prev_token.span.shrink_to_hi(), format!("expected {}", expect)),
235 self.last_unexpected_token_span = Some(self.token.span);
236 let mut err = self.struct_span_err(self.token.span, &msg_exp);
237 let sp = if self.token == token::Eof {
238 // This is EOF; don't want to point at the following char, but rather the last token.
243 match self.recover_closing_delimiter(
246 .filter_map(|tt| match tt {
247 TokenType::Token(t) => Some(t.clone()),
250 .collect::<Vec<_>>(),
255 return Ok(recovered);
259 if self.check_too_many_raw_str_terminators(&mut err) {
263 let sm = self.sess.source_map();
264 if self.prev_token.span == DUMMY_SP {
265 // Account for macro context where the previous span might not be
266 // available to avoid incorrect output (#54841).
267 err.span_label(self.token.span, label_exp);
268 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
269 // When the spans are in the same line, it means that the only content between
270 // them is whitespace, point at the found token in that case:
272 // X | () => { syntax error };
273 // | ^^^^^ expected one of 8 possible tokens here
275 // instead of having:
277 // X | () => { syntax error };
278 // | -^^^^^ unexpected token
280 // | expected one of 8 possible tokens here
281 err.span_label(self.token.span, label_exp);
283 err.span_label(sp, label_exp);
284 err.span_label(self.token.span, "unexpected token");
286 self.maybe_annotate_with_ascription(&mut err, false);
290 fn check_too_many_raw_str_terminators(&mut self, err: &mut DiagnosticBuilder<'_>) -> bool {
291 match (&self.prev_token.kind, &self.token.kind) {
293 TokenKind::Literal(Lit {
294 kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
299 err.set_primary_message("too many `#` when terminating raw string");
302 "remove the extra `#`",
304 Applicability::MachineApplicable,
306 err.note(&format!("the raw string started with {} `#`s", n_hashes));
313 pub fn maybe_annotate_with_ascription(
315 err: &mut DiagnosticBuilder<'_>,
316 maybe_expected_semicolon: bool,
318 if let Some((sp, likely_path)) = self.last_type_ascription.take() {
319 let sm = self.sess.source_map();
320 let next_pos = sm.lookup_char_pos(self.token.span.lo());
321 let op_pos = sm.lookup_char_pos(sp.hi());
323 let allow_unstable = self.sess.unstable_features.is_nightly_build();
328 "maybe write a path separator here",
331 Applicability::MaybeIncorrect
333 Applicability::MachineApplicable
336 self.sess.type_ascription_path_suggestions.borrow_mut().insert(sp);
337 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
340 "try using a semicolon",
342 Applicability::MaybeIncorrect,
344 } else if allow_unstable {
345 err.span_label(sp, "tried to parse a type due to this type ascription");
347 err.span_label(sp, "tried to parse a type due to this");
350 // Give extra information about type ascription only if it's a nightly compiler.
352 "`#![feature(type_ascription)]` lets you annotate an expression with a type: \
356 // Avoid giving too much info when it was likely an unrelated typo.
358 "see issue #23416 <https://github.com/rust-lang/rust/issues/23416> \
359 for more information",
366 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
367 /// passes through any errors encountered. Used for error recovery.
368 pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
369 if let Err(ref mut err) =
370 self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
371 Ok(p.parse_token_tree())
378 /// This function checks if there are trailing angle brackets and produces
379 /// a diagnostic to suggest removing them.
381 /// ```ignore (diagnostic)
382 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
383 /// ^^ help: remove extra angle brackets
386 /// If `true` is returned, then trailing brackets were recovered, tokens were consumed
387 /// up until one of the tokens in 'end' was encountered, and an error was emitted.
388 pub(super) fn check_trailing_angle_brackets(
390 segment: &PathSegment,
393 // This function is intended to be invoked after parsing a path segment where there are two
396 // 1. A specific token is expected after the path segment.
397 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
398 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
399 // 2. No specific token is expected after the path segment.
400 // eg. `x.foo` (field access)
402 // This function is called after parsing `.foo` and before parsing the token `end` (if
403 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
406 // We only care about trailing angle brackets if we previously parsed angle bracket
407 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
408 // removed in this case:
410 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
412 // This case is particularly tricky as we won't notice it just looking at the tokens -
413 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
414 // have already been parsed):
416 // `x.foo::<u32>>>(3)`
417 let parsed_angle_bracket_args =
418 segment.args.as_ref().map(|args| args.is_angle_bracketed()).unwrap_or(false);
421 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
422 parsed_angle_bracket_args,
424 if !parsed_angle_bracket_args {
428 // Keep the span at the start so we can highlight the sequence of `>` characters to be
430 let lo = self.token.span;
432 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
433 // (since we might have the field access case and the characters we're eating are
434 // actual operators and not trailing characters - ie `x.foo >> 3`).
435 let mut position = 0;
437 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
438 // many of each (so we can correctly pluralize our error messages) and continue to
440 let mut number_of_shr = 0;
441 let mut number_of_gt = 0;
442 while self.look_ahead(position, |t| {
443 trace!("check_trailing_angle_brackets: t={:?}", t);
444 if *t == token::BinOp(token::BinOpToken::Shr) {
447 } else if *t == token::Gt {
457 // If we didn't find any trailing `>` characters, then we have nothing to error about.
459 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
460 number_of_gt, number_of_shr,
462 if number_of_gt < 1 && number_of_shr < 1 {
466 // Finally, double check that we have our end token as otherwise this is the
468 if self.look_ahead(position, |t| {
469 trace!("check_trailing_angle_brackets: t={:?}", t);
470 end.contains(&&t.kind)
472 // Eat from where we started until the end token so that parsing can continue
473 // as if we didn't have those extra angle brackets.
474 self.eat_to_tokens(end);
475 let span = lo.until(self.token.span);
477 let total_num_of_gt = number_of_gt + number_of_shr * 2;
478 self.struct_span_err(
480 &format!("unmatched angle bracket{}", pluralize!(total_num_of_gt)),
484 &format!("remove extra angle bracket{}", pluralize!(total_num_of_gt)),
486 Applicability::MachineApplicable,
494 /// Check if a method call with an intended turbofish has been written without surrounding
496 pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
497 if token::ModSep == self.token.kind && segment.args.is_none() {
498 let snapshot = self.clone();
500 let lo = self.token.span;
501 match self.parse_angle_args() {
503 let span = lo.to(self.prev_token.span);
504 // Detect trailing `>` like in `x.collect::Vec<_>>()`.
505 let mut trailing_span = self.prev_token.span.shrink_to_hi();
506 while self.token.kind == token::BinOp(token::Shr)
507 || self.token.kind == token::Gt
509 trailing_span = trailing_span.to(self.token.span);
512 if self.token.kind == token::OpenDelim(token::Paren) {
513 // Recover from bad turbofish: `foo.collect::Vec<_>()`.
514 let args = AngleBracketedArgs { args, span }.into();
517 self.struct_span_err(
519 "generic parameters without surrounding angle brackets",
521 .multipart_suggestion(
522 "surround the type parameters with angle brackets",
524 (span.shrink_to_lo(), "<".to_string()),
525 (trailing_span, ">".to_string()),
527 Applicability::MachineApplicable,
531 // This doesn't look like an invalid turbofish, can't recover parse state.
536 // We could't parse generic parameters, unlikely to be a turbofish. Rely on
537 // generic parse error instead.
545 /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
546 /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
547 /// parenthesising the leftmost comparison.
548 fn attempt_chained_comparison_suggestion(
550 err: &mut DiagnosticBuilder<'_>,
552 outer_op: &Spanned<AssocOp>,
553 ) -> bool /* advanced the cursor */ {
554 if let ExprKind::Binary(op, ref l1, ref r1) = inner_op.kind {
555 if let ExprKind::Field(_, ident) = l1.kind {
556 if ident.as_str().parse::<i32>().is_err() && !matches!(r1.kind, ExprKind::Lit(_)) {
557 // The parser has encountered `foo.bar<baz`, the likelihood of the turbofish
558 // suggestion being the only one to apply is high.
562 let mut enclose = |left: Span, right: Span| {
563 err.multipart_suggestion(
564 "parenthesize the comparison",
566 (left.shrink_to_lo(), "(".to_string()),
567 (right.shrink_to_hi(), ")".to_string()),
569 Applicability::MaybeIncorrect,
572 return match (op.node, &outer_op.node) {
574 (BinOpKind::Eq, AssocOp::Equal) |
575 // `x < y < z` and friends.
576 (BinOpKind::Lt, AssocOp::Less | AssocOp::LessEqual) |
577 (BinOpKind::Le, AssocOp::LessEqual | AssocOp::Less) |
578 // `x > y > z` and friends.
579 (BinOpKind::Gt, AssocOp::Greater | AssocOp::GreaterEqual) |
580 (BinOpKind::Ge, AssocOp::GreaterEqual | AssocOp::Greater) => {
581 let expr_to_str = |e: &Expr| {
582 self.span_to_snippet(e.span)
583 .unwrap_or_else(|_| pprust::expr_to_string(&e))
585 err.span_suggestion_verbose(
586 inner_op.span.shrink_to_hi(),
587 "split the comparison into two",
588 format!(" && {}", expr_to_str(&r1)),
589 Applicability::MaybeIncorrect,
591 false // Keep the current parse behavior, where the AST is `(x < y) < z`.
594 (BinOpKind::Eq, AssocOp::Less | AssocOp::LessEqual | AssocOp::Greater | AssocOp::GreaterEqual) => {
595 // Consume `z`/outer-op-rhs.
596 let snapshot = self.clone();
597 match self.parse_expr() {
599 // We are sure that outer-op-rhs could be consumed, the suggestion is
601 enclose(r1.span, r2.span);
604 Err(mut expr_err) => {
612 (BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge, AssocOp::Equal) => {
613 let snapshot = self.clone();
614 // At this point it is always valid to enclose the lhs in parentheses, no
615 // further checks are necessary.
616 match self.parse_expr() {
618 enclose(l1.span, r1.span);
621 Err(mut expr_err) => {
634 /// Produces an error if comparison operators are chained (RFC #558).
635 /// We only need to check the LHS, not the RHS, because all comparison ops have same
636 /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
638 /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
639 /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
642 /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
643 /// associative we can infer that we have:
652 pub(super) fn check_no_chained_comparison(
655 outer_op: &Spanned<AssocOp>,
656 ) -> PResult<'a, Option<P<Expr>>> {
658 outer_op.node.is_comparison(),
659 "check_no_chained_comparison: {:?} is not comparison",
664 |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err, AttrVec::new())));
666 match inner_op.kind {
667 ExprKind::Binary(op, ref l1, ref r1) if op.node.is_comparison() => {
668 let mut err = self.struct_span_err(
669 vec![op.span, self.prev_token.span],
670 "comparison operators cannot be chained",
673 let suggest = |err: &mut DiagnosticBuilder<'_>| {
674 err.span_suggestion_verbose(
675 op.span.shrink_to_lo(),
678 Applicability::MaybeIncorrect,
682 // Include `<` to provide this recommendation even in a case like
683 // `Foo<Bar<Baz<Qux, ()>>>`
684 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Less
685 || outer_op.node == AssocOp::Greater
687 if outer_op.node == AssocOp::Less {
688 let snapshot = self.clone();
690 // So far we have parsed `foo<bar<`, consume the rest of the type args.
692 [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
693 self.consume_tts(1, &modifiers[..]);
695 if !&[token::OpenDelim(token::Paren), token::ModSep]
696 .contains(&self.token.kind)
698 // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
699 // parser and bail out.
700 *self = snapshot.clone();
703 return if token::ModSep == self.token.kind {
704 // We have some certainty that this was a bad turbofish at this point.
708 let snapshot = self.clone();
711 // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
712 match self.parse_expr() {
714 // 99% certain that the suggestion is correct, continue parsing.
716 // FIXME: actually check that the two expressions in the binop are
717 // paths and resynthesize new fn call expression instead of using
718 // `ExprKind::Err` placeholder.
719 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
721 Err(mut expr_err) => {
723 // Not entirely sure now, but we bubble the error up with the
729 } else if token::OpenDelim(token::Paren) == self.token.kind {
730 // We have high certainty that this was a bad turbofish at this point.
733 // Consume the fn call arguments.
734 match self.consume_fn_args() {
738 // FIXME: actually check that the two expressions in the binop are
739 // paths and resynthesize new fn call expression instead of using
740 // `ExprKind::Err` placeholder.
741 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
745 if !matches!(l1.kind, ExprKind::Lit(_))
746 && !matches!(r1.kind, ExprKind::Lit(_))
748 // All we know is that this is `foo < bar >` and *nothing* else. Try to
749 // be helpful, but don't attempt to recover.
751 err.help("or use `(...)` if you meant to specify fn arguments");
754 // If it looks like a genuine attempt to chain operators (as opposed to a
755 // misformatted turbofish, for instance), suggest a correct form.
756 if self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op)
759 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
761 // These cases cause too many knock-down errors, bail out (#61329).
767 self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
770 return mk_err_expr(self, inner_op.span.to(self.prev_token.span));
778 fn consume_fn_args(&mut self) -> Result<(), ()> {
779 let snapshot = self.clone();
782 // Consume the fn call arguments.
784 [(token::OpenDelim(token::Paren), 1), (token::CloseDelim(token::Paren), -1)];
785 self.consume_tts(1, &modifiers[..]);
787 if self.token.kind == token::Eof {
788 // Not entirely sure that what we consumed were fn arguments, rollback.
792 // 99% certain that the suggestion is correct, continue parsing.
797 pub(super) fn maybe_report_ambiguous_plus(
799 allow_plus: AllowPlus,
800 impl_dyn_multi: bool,
803 if matches!(allow_plus, AllowPlus::No) && impl_dyn_multi {
804 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
805 self.struct_span_err(ty.span, "ambiguous `+` in a type")
808 "use parentheses to disambiguate",
810 Applicability::MachineApplicable,
816 pub(super) fn maybe_recover_from_bad_type_plus(
818 allow_plus: AllowPlus,
820 ) -> PResult<'a, ()> {
821 // Do not add `+` to expected tokens.
822 if matches!(allow_plus, AllowPlus::No) || !self.token.is_like_plus() {
827 let bounds = self.parse_generic_bounds(None)?;
828 let sum_span = ty.span.to(self.prev_token.span);
830 let mut err = struct_span_err!(
831 self.sess.span_diagnostic,
834 "expected a path on the left-hand side of `+`, not `{}`",
835 pprust::ty_to_string(ty)
839 TyKind::Rptr(ref lifetime, ref mut_ty) => {
840 let sum_with_parens = pprust::to_string(|s| {
842 s.print_opt_lifetime(lifetime);
843 s.print_mutability(mut_ty.mutbl, false);
845 s.print_type(&mut_ty.ty);
846 s.print_type_bounds(" +", &bounds);
851 "try adding parentheses",
853 Applicability::MachineApplicable,
856 TyKind::Ptr(..) | TyKind::BareFn(..) => {
857 err.span_label(sum_span, "perhaps you forgot parentheses?");
860 err.span_label(sum_span, "expected a path");
867 /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
868 /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
869 /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
870 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
873 allow_recovery: bool,
874 ) -> PResult<'a, P<T>> {
875 // Do not add `::` to expected tokens.
876 if allow_recovery && self.token == token::ModSep {
877 if let Some(ty) = base.to_ty() {
878 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
884 /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
885 /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
886 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
890 ) -> PResult<'a, P<T>> {
891 self.expect(&token::ModSep)?;
893 let mut path = ast::Path { segments: Vec::new(), span: DUMMY_SP };
894 self.parse_path_segments(&mut path.segments, T::PATH_STYLE)?;
895 path.span = ty_span.to(self.prev_token.span);
897 let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
898 self.struct_span_err(path.span, "missing angle brackets in associated item path")
900 // This is a best-effort recovery.
903 format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
904 Applicability::MaybeIncorrect,
908 let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
909 Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path)))
912 pub(super) fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
913 if self.eat(&token::Semi) {
914 let mut err = self.struct_span_err(self.prev_token.span, "expected item, found `;`");
915 err.span_suggestion_short(
916 self.prev_token.span,
917 "remove this semicolon",
919 Applicability::MachineApplicable,
921 if !items.is_empty() {
922 let previous_item = &items[items.len() - 1];
923 let previous_item_kind_name = match previous_item.kind {
924 // Say "braced struct" because tuple-structs and
925 // braceless-empty-struct declarations do take a semicolon.
926 ItemKind::Struct(..) => Some("braced struct"),
927 ItemKind::Enum(..) => Some("enum"),
928 ItemKind::Trait(..) => Some("trait"),
929 ItemKind::Union(..) => Some("union"),
932 if let Some(name) = previous_item_kind_name {
933 err.help(&format!("{} declarations are not followed by a semicolon", name));
943 /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
944 /// closing delimiter.
945 pub(super) fn unexpected_try_recover(
948 ) -> PResult<'a, bool /* recovered */> {
949 let token_str = pprust::token_kind_to_string(t);
950 let this_token_str = super::token_descr(&self.token);
951 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
952 // Point at the end of the macro call when reaching end of macro arguments.
953 (token::Eof, Some(_)) => {
954 let sp = self.sess.source_map().next_point(self.token.span);
957 // We don't want to point at the following span after DUMMY_SP.
958 // This happens when the parser finds an empty TokenStream.
959 _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
960 // EOF, don't want to point at the following char, but rather the last token.
961 (token::Eof, None) => (self.prev_token.span, self.token.span),
962 _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
965 "expected `{}`, found {}",
967 match (&self.token.kind, self.subparser_name) {
968 (token::Eof, Some(origin)) => format!("end of {}", origin),
972 let mut err = self.struct_span_err(sp, &msg);
973 let label_exp = format!("expected `{}`", token_str);
974 match self.recover_closing_delimiter(&[t.clone()], err) {
977 return Ok(recovered);
980 let sm = self.sess.source_map();
981 if !sm.is_multiline(prev_sp.until(sp)) {
982 // When the spans are in the same line, it means that the only content
983 // between them is whitespace, point only at the found token.
984 err.span_label(sp, label_exp);
986 err.span_label(prev_sp, label_exp);
987 err.span_label(sp, "unexpected token");
992 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
993 if self.eat(&token::Semi) {
996 let sm = self.sess.source_map();
997 let msg = format!("expected `;`, found {}", super::token_descr(&self.token));
998 let appl = Applicability::MachineApplicable;
999 if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
1000 // Likely inside a macro, can't provide meaningful suggestions.
1001 return self.expect(&token::Semi).map(drop);
1002 } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
1003 // The current token is in the same line as the prior token, not recoverable.
1004 } else if [token::Comma, token::Colon].contains(&self.token.kind)
1005 && self.prev_token.kind == token::CloseDelim(token::Paren)
1007 // Likely typo: The current token is on a new line and is expected to be
1008 // `.`, `;`, `?`, or an operator after a close delimiter token.
1010 // let a = std::process::Command::new("echo")
1014 // https://github.com/rust-lang/rust/issues/72253
1015 self.expect(&token::Semi)?;
1017 } else if self.look_ahead(1, |t| {
1018 t == &token::CloseDelim(token::Brace) || t.can_begin_expr() && t.kind != token::Colon
1019 }) && [token::Comma, token::Colon].contains(&self.token.kind)
1021 // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is
1022 // either `,` or `:`, and the next token could either start a new statement or is a
1023 // block close. For example:
1028 let sp = self.prev_token.span;
1029 self.struct_span_err(sp, &msg)
1030 .span_suggestion_short(sp, "change this to `;`", ";".to_string(), appl)
1033 } else if self.look_ahead(0, |t| {
1034 t == &token::CloseDelim(token::Brace)
1036 t.can_begin_expr() && t != &token::Semi && t != &token::Pound
1037 // Avoid triggering with too many trailing `#` in raw string.
1040 // Missing semicolon typo. This is triggered if the next token could either start a
1041 // new statement or is a block close. For example:
1045 let sp = self.prev_token.span.shrink_to_hi();
1046 self.struct_span_err(sp, &msg)
1047 .span_label(self.token.span, "unexpected token")
1048 .span_suggestion_short(sp, "add `;` here", ";".to_string(), appl)
1052 self.expect(&token::Semi).map(drop) // Error unconditionally
1055 /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
1056 /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
1057 pub(super) fn recover_incorrect_await_syntax(
1062 ) -> PResult<'a, P<Expr>> {
1063 let (hi, expr, is_question) = if self.token == token::Not {
1064 // Handle `await!(<expr>)`.
1065 self.recover_await_macro()?
1067 self.recover_await_prefix(await_sp)?
1069 let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
1070 let expr = self.mk_expr(lo.to(sp), ExprKind::Await(expr), attrs);
1071 self.maybe_recover_from_bad_qpath(expr, true)
1074 fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1075 self.expect(&token::Not)?;
1076 self.expect(&token::OpenDelim(token::Paren))?;
1077 let expr = self.parse_expr()?;
1078 self.expect(&token::CloseDelim(token::Paren))?;
1079 Ok((self.prev_token.span, expr, false))
1082 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
1083 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
1084 let expr = if self.token == token::OpenDelim(token::Brace) {
1085 // Handle `await { <expr> }`.
1086 // This needs to be handled separatedly from the next arm to avoid
1087 // interpreting `await { <expr> }?` as `<expr>?.await`.
1088 self.parse_block_expr(None, self.token.span, BlockCheckMode::Default, AttrVec::new())
1092 .map_err(|mut err| {
1093 err.span_label(await_sp, "while parsing this incorrect await expression");
1096 Ok((expr.span, expr, is_question))
1099 fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
1101 self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr));
1102 let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" });
1104 let app = match expr.kind {
1105 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
1106 _ => Applicability::MachineApplicable,
1108 self.struct_span_err(sp, "incorrect use of `await`")
1109 .span_suggestion(sp, "`await` is a postfix operation", suggestion, app)
1114 /// If encountering `future.await()`, consumes and emits an error.
1115 pub(super) fn recover_from_await_method_call(&mut self) {
1116 if self.token == token::OpenDelim(token::Paren)
1117 && self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren))
1120 let lo = self.token.span;
1122 let sp = lo.to(self.token.span);
1124 self.struct_span_err(sp, "incorrect use of `await`")
1127 "`await` is not a method call, remove the parentheses",
1129 Applicability::MachineApplicable,
1135 pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, P<Expr>> {
1136 let is_try = self.token.is_keyword(kw::Try);
1137 let is_questionmark = self.look_ahead(1, |t| t == &token::Not); //check for !
1138 let is_open = self.look_ahead(2, |t| t == &token::OpenDelim(token::Paren)); //check for (
1140 if is_try && is_questionmark && is_open {
1141 let lo = self.token.span;
1142 self.bump(); //remove try
1143 self.bump(); //remove !
1144 let try_span = lo.to(self.token.span); //we take the try!( span
1145 self.bump(); //remove (
1146 let is_empty = self.token == token::CloseDelim(token::Paren); //check if the block is empty
1147 self.consume_block(token::Paren, ConsumeClosingDelim::No); //eat the block
1148 let hi = self.token.span;
1149 self.bump(); //remove )
1150 let mut err = self.struct_span_err(lo.to(hi), "use of deprecated `try` macro");
1151 err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
1152 let prefix = if is_empty { "" } else { "alternatively, " };
1154 err.multipart_suggestion(
1155 "you can use the `?` operator instead",
1156 vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
1157 Applicability::MachineApplicable,
1160 err.span_suggestion(lo.shrink_to_lo(), &format!("{}you can still access the deprecated `try!()` macro using the \"raw identifier\" syntax", prefix), "r#".to_string(), Applicability::MachineApplicable);
1162 Ok(self.mk_expr_err(lo.to(hi)))
1164 Err(self.expected_expression_found()) // The user isn't trying to invoke the try! macro
1168 /// Recovers a situation like `for ( $pat in $expr )`
1169 /// and suggest writing `for $pat in $expr` instead.
1171 /// This should be called before parsing the `$block`.
1172 pub(super) fn recover_parens_around_for_head(
1176 begin_paren: Option<Span>,
1178 match (&self.token.kind, begin_paren) {
1179 (token::CloseDelim(token::Paren), Some(begin_par_sp)) => {
1183 // Remove the `(` from the span of the pattern:
1184 .span_to_snippet(pat.span.trim_start(begin_par_sp).unwrap())
1185 .unwrap_or_else(|_| pprust::pat_to_string(&pat));
1187 self.struct_span_err(self.prev_token.span, "unexpected closing `)`")
1188 .span_label(begin_par_sp, "opening `(`")
1190 begin_par_sp.to(self.prev_token.span),
1191 "remove parenthesis in `for` loop",
1192 format!("{} in {}", pat_str, pprust::expr_to_string(&expr)),
1193 // With e.g. `for (x) in y)` this would replace `(x) in y)`
1194 // with `x) in y)` which is syntactically invalid.
1195 // However, this is prevented before we get here.
1196 Applicability::MachineApplicable,
1200 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1201 pat.and_then(|pat| match pat.kind {
1202 PatKind::Paren(pat) => pat,
1210 pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1211 (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1212 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1213 || self.token.is_ident() &&
1215 // `foo::` → `foo:` or `foo.bar::` → `foo.bar:`
1216 ast::ExprKind::Path(..) | ast::ExprKind::Field(..) => true,
1219 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
1220 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren))
1221 || self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) // `foo:bar {`
1222 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar::<baz`
1223 self.look_ahead(2, |t| t == &token::Lt) &&
1224 self.look_ahead(3, |t| t.is_ident())
1225 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
1226 self.look_ahead(2, |t| t.is_ident())
1227 || self.look_ahead(1, |t| t == &token::ModSep)
1228 && (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
1229 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1232 pub(super) fn recover_seq_parse_error(
1234 delim: token::DelimToken,
1236 result: PResult<'a, P<Expr>>,
1242 // Recover from parse error, callers expect the closing delim to be consumed.
1243 self.consume_block(delim, ConsumeClosingDelim::Yes);
1244 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err, AttrVec::new())
1249 pub(super) fn recover_closing_delimiter(
1251 tokens: &[TokenKind],
1252 mut err: DiagnosticBuilder<'a>,
1253 ) -> PResult<'a, bool> {
1255 // We want to use the last closing delim that would apply.
1256 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1257 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1258 && Some(self.token.span) > unmatched.unclosed_span
1265 // Recover and assume that the detected unclosed delimiter was meant for
1266 // this location. Emit the diagnostic and act as if the delimiter was
1267 // present for the parser's sake.
1269 // Don't attempt to recover from this unclosed delimiter more than once.
1270 let unmatched = self.unclosed_delims.remove(pos);
1271 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1272 if unmatched.found_delim.is_none() {
1273 // We encountered `Eof`, set this fact here to avoid complaining about missing
1274 // `fn main()` when we found place to suggest the closing brace.
1275 *self.sess.reached_eof.borrow_mut() = true;
1278 // We want to suggest the inclusion of the closing delimiter where it makes
1279 // the most sense, which is immediately after the last token:
1284 // | help: `)` may belong here
1286 // unclosed delimiter
1287 if let Some(sp) = unmatched.unclosed_span {
1288 err.span_label(sp, "unclosed delimiter");
1290 // Backticks should be removed to apply suggestions.
1291 let mut delim = delim.to_string();
1292 delim.retain(|c| c != '`');
1293 err.span_suggestion_short(
1294 self.prev_token.span.shrink_to_hi(),
1295 &format!("`{}` may belong here", delim),
1297 Applicability::MaybeIncorrect,
1299 if unmatched.found_delim.is_none() {
1300 // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1301 // errors which would be emitted elsewhere in the parser and let other error
1302 // recovery consume the rest of the file.
1306 self.expected_tokens.clear(); // Reduce the number of errors.
1314 /// Eats tokens until we can be relatively sure we reached the end of the
1315 /// statement. This is something of a best-effort heuristic.
1317 /// We terminate when we find an unmatched `}` (without consuming it).
1318 pub(super) fn recover_stmt(&mut self) {
1319 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1322 /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1323 /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1324 /// approximate -- it can mean we break too early due to macros, but that
1325 /// should only lead to sub-optimal recovery, not inaccurate parsing).
1327 /// If `break_on_block` is `Break`, then we will stop consuming tokens
1328 /// after finding (and consuming) a brace-delimited block.
1329 pub(super) fn recover_stmt_(
1331 break_on_semi: SemiColonMode,
1332 break_on_block: BlockMode,
1334 let mut brace_depth = 0;
1335 let mut bracket_depth = 0;
1336 let mut in_block = false;
1337 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1339 debug!("recover_stmt_ loop {:?}", self.token);
1340 match self.token.kind {
1341 token::OpenDelim(token::DelimToken::Brace) => {
1344 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1349 token::OpenDelim(token::DelimToken::Bracket) => {
1353 token::CloseDelim(token::DelimToken::Brace) => {
1354 if brace_depth == 0 {
1355 debug!("recover_stmt_ return - close delim {:?}", self.token);
1360 if in_block && bracket_depth == 0 && brace_depth == 0 {
1361 debug!("recover_stmt_ return - block end {:?}", self.token);
1365 token::CloseDelim(token::DelimToken::Bracket) => {
1367 if bracket_depth < 0 {
1373 debug!("recover_stmt_ return - Eof");
1378 if break_on_semi == SemiColonMode::Break
1380 && bracket_depth == 0
1382 debug!("recover_stmt_ return - Semi");
1387 if break_on_semi == SemiColonMode::Comma
1389 && bracket_depth == 0 =>
1391 debug!("recover_stmt_ return - Semi");
1399 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1400 if self.eat_keyword(kw::In) {
1401 // a common typo: `for _ in in bar {}`
1402 self.struct_span_err(self.prev_token.span, "expected iterable, found keyword `in`")
1403 .span_suggestion_short(
1404 in_span.until(self.prev_token.span),
1405 "remove the duplicated `in`",
1407 Applicability::MachineApplicable,
1413 pub(super) fn expected_semi_or_open_brace<T>(&mut self) -> PResult<'a, T> {
1414 let token_str = super::token_descr(&self.token);
1415 let msg = &format!("expected `;` or `{{`, found {}", token_str);
1416 let mut err = self.struct_span_err(self.token.span, msg);
1417 err.span_label(self.token.span, "expected `;` or `{`");
1421 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1422 if let token::DocComment(..) = self.token.kind {
1423 self.struct_span_err(
1425 "documentation comments cannot be applied to a function parameter's type",
1427 .span_label(self.token.span, "doc comments are not allowed here")
1430 } else if self.token == token::Pound
1431 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Bracket))
1433 let lo = self.token.span;
1434 // Skip every token until next possible arg.
1435 while self.token != token::CloseDelim(token::Bracket) {
1438 let sp = lo.to(self.token.span);
1440 self.struct_span_err(sp, "attributes cannot be applied to a function parameter's type")
1441 .span_label(sp, "attributes are not allowed here")
1446 pub(super) fn parameter_without_type(
1448 err: &mut DiagnosticBuilder<'_>,
1452 ) -> Option<Ident> {
1453 // If we find a pattern followed by an identifier, it could be an (incorrect)
1454 // C-style parameter declaration.
1455 if self.check_ident()
1456 && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseDelim(token::Paren))
1458 // `fn foo(String s) {}`
1459 let ident = self.parse_ident().unwrap();
1460 let span = pat.span.with_hi(ident.span.hi());
1462 err.span_suggestion(
1464 "declare the type after the parameter binding",
1465 String::from("<identifier>: <type>"),
1466 Applicability::HasPlaceholders,
1469 } else if let PatKind::Ident(_, ident, _) = pat.kind {
1471 && (self.token == token::Comma
1472 || self.token == token::Lt
1473 || self.token == token::CloseDelim(token::Paren))
1475 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1477 err.span_suggestion(
1479 "if this is a `self` type, give it a parameter name",
1480 format!("self: {}", ident),
1481 Applicability::MaybeIncorrect,
1484 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
1485 // `fn foo(HashMap: TypeName<u32>)`.
1486 if self.token != token::Lt {
1487 err.span_suggestion(
1489 "if this is a parameter name, give it a type",
1490 format!("{}: TypeName", ident),
1491 Applicability::HasPlaceholders,
1494 err.span_suggestion(
1496 "if this is a type, explicitly ignore the parameter name",
1497 format!("_: {}", ident),
1498 Applicability::MachineApplicable,
1500 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1502 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
1503 return if self.token == token::Lt { None } else { Some(ident) };
1509 pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
1510 let pat = self.parse_pat(Some("argument name"))?;
1511 self.expect(&token::Colon)?;
1512 let ty = self.parse_ty()?;
1518 "patterns aren't allowed in methods without bodies",
1520 .span_suggestion_short(
1522 "give this argument a name or use an underscore to ignore it",
1524 Applicability::MachineApplicable,
1528 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1529 let pat = P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID });
1533 pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
1534 let sp = param.pat.span;
1535 param.ty.kind = TyKind::Err;
1536 self.struct_span_err(sp, "unexpected `self` parameter in function")
1537 .span_label(sp, "must be the first parameter of an associated function")
1542 pub(super) fn consume_block(
1544 delim: token::DelimToken,
1545 consume_close: ConsumeClosingDelim,
1547 let mut brace_depth = 0;
1549 if self.eat(&token::OpenDelim(delim)) {
1551 } else if self.check(&token::CloseDelim(delim)) {
1552 if brace_depth == 0 {
1553 if let ConsumeClosingDelim::Yes = consume_close {
1554 // Some of the callers of this method expect to be able to parse the
1555 // closing delimiter themselves, so we leave it alone. Otherwise we advance
1565 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
1573 pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a> {
1574 let (span, msg) = match (&self.token.kind, self.subparser_name) {
1575 (&token::Eof, Some(origin)) => {
1576 let sp = self.sess.source_map().next_point(self.token.span);
1577 (sp, format!("expected expression, found end of {}", origin))
1581 format!("expected expression, found {}", super::token_descr(&self.token),),
1584 let mut err = self.struct_span_err(span, &msg);
1585 let sp = self.sess.source_map().start_point(self.token.span);
1586 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
1587 self.sess.expr_parentheses_needed(&mut err, *sp, None);
1589 err.span_label(span, "expected expression");
1595 mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
1596 // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
1597 modifier: &[(token::TokenKind, i64)],
1600 if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
1603 if self.token.kind == token::Eof {
1610 /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
1612 /// This is necessary because at this point we don't know whether we parsed a function with
1613 /// anonymous parameters or a function with names but no types. In order to minimize
1614 /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
1615 /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
1616 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
1617 /// we deduplicate them to not complain about duplicated parameter names.
1618 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
1619 let mut seen_inputs = FxHashSet::default();
1620 for input in fn_inputs.iter_mut() {
1621 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
1622 (&input.pat.kind, &input.ty.kind)
1628 if let Some(ident) = opt_ident {
1629 if seen_inputs.contains(&ident) {
1630 input.pat.kind = PatKind::Wild;
1632 seen_inputs.insert(ident);