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