]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/diagnostics.rs
Rollup merge of #94150 - Enselic:synthetic-generic-parameters-in-json, r=CraftSpider
[rust.git] / compiler / rustc_parse / src / parser / diagnostics.rs
1 use super::pat::Expected;
2 use super::ty::{AllowPlus, RecoverQuestionMark};
3 use super::{
4     BlockMode, CommaRecoveryMode, Parser, PathStyle, RecoverColon, RecoverComma, Restrictions,
5     SemiColonMode, SeqSep, TokenExpectType, TokenType,
6 };
7
8 use rustc_ast as ast;
9 use rustc_ast::ptr::P;
10 use rustc_ast::token::{self, Lit, LitKind, TokenKind};
11 use rustc_ast::util::parser::AssocOp;
12 use rustc_ast::{
13     AngleBracketedArg, AngleBracketedArgs, AnonConst, AttrVec, BinOpKind, BindingMode, Block,
14     BlockCheckMode, Expr, ExprKind, GenericArg, Generics, Item, ItemKind, Mutability, Param, Pat,
15     PatKind, Path, PathSegment, QSelf, Ty, TyKind,
16 };
17 use rustc_ast_pretty::pprust;
18 use rustc_data_structures::fx::FxHashSet;
19 use rustc_errors::{pluralize, struct_span_err, Diagnostic, ErrorGuaranteed};
20 use rustc_errors::{Applicability, DiagnosticBuilder, Handler, PResult};
21 use rustc_span::source_map::Spanned;
22 use rustc_span::symbol::{kw, Ident};
23 use rustc_span::{MultiSpan, Span, SpanSnippetError, DUMMY_SP};
24
25 use std::mem::take;
26
27 use tracing::{debug, trace};
28
29 const TURBOFISH_SUGGESTION_STR: &str =
30     "use `::<...>` instead of `<...>` to specify lifetime, type, or const arguments";
31
32 /// Creates a placeholder argument.
33 pub(super) fn dummy_arg(ident: Ident) -> Param {
34     let pat = P(Pat {
35         id: ast::DUMMY_NODE_ID,
36         kind: PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None),
37         span: ident.span,
38         tokens: None,
39     });
40     let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID, tokens: None };
41     Param {
42         attrs: AttrVec::default(),
43         id: ast::DUMMY_NODE_ID,
44         pat,
45         span: ident.span,
46         ty: P(ty),
47         is_placeholder: false,
48     }
49 }
50
51 pub enum Error {
52     UselessDocComment,
53 }
54
55 impl Error {
56     fn span_err(
57         self,
58         sp: impl Into<MultiSpan>,
59         handler: &Handler,
60     ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
61         match self {
62             Error::UselessDocComment => {
63                 let mut err = struct_span_err!(
64                     handler,
65                     sp,
66                     E0585,
67                     "found a documentation comment that doesn't document anything",
68                 );
69                 err.help(
70                     "doc comments must come before what they document, maybe a comment was \
71                           intended with `//`?",
72                 );
73                 err
74             }
75         }
76     }
77 }
78
79 pub(super) trait RecoverQPath: Sized + 'static {
80     const PATH_STYLE: PathStyle = PathStyle::Expr;
81     fn to_ty(&self) -> Option<P<Ty>>;
82     fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
83 }
84
85 impl RecoverQPath for Ty {
86     const PATH_STYLE: PathStyle = PathStyle::Type;
87     fn to_ty(&self) -> Option<P<Ty>> {
88         Some(P(self.clone()))
89     }
90     fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
91         Self {
92             span: path.span,
93             kind: TyKind::Path(qself, path),
94             id: ast::DUMMY_NODE_ID,
95             tokens: None,
96         }
97     }
98 }
99
100 impl RecoverQPath for Pat {
101     fn to_ty(&self) -> Option<P<Ty>> {
102         self.to_ty()
103     }
104     fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
105         Self {
106             span: path.span,
107             kind: PatKind::Path(qself, path),
108             id: ast::DUMMY_NODE_ID,
109             tokens: None,
110         }
111     }
112 }
113
114 impl RecoverQPath for Expr {
115     fn to_ty(&self) -> Option<P<Ty>> {
116         self.to_ty()
117     }
118     fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
119         Self {
120             span: path.span,
121             kind: ExprKind::Path(qself, path),
122             attrs: AttrVec::new(),
123             id: ast::DUMMY_NODE_ID,
124             tokens: None,
125         }
126     }
127 }
128
129 /// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
130 crate enum ConsumeClosingDelim {
131     Yes,
132     No,
133 }
134
135 #[derive(Clone, Copy)]
136 pub enum AttemptLocalParseRecovery {
137     Yes,
138     No,
139 }
140
141 impl AttemptLocalParseRecovery {
142     pub fn yes(&self) -> bool {
143         match self {
144             AttemptLocalParseRecovery::Yes => true,
145             AttemptLocalParseRecovery::No => false,
146         }
147     }
148
149     pub fn no(&self) -> bool {
150         match self {
151             AttemptLocalParseRecovery::Yes => false,
152             AttemptLocalParseRecovery::No => true,
153         }
154     }
155 }
156
157 impl<'a> Parser<'a> {
158     pub(super) fn span_err<S: Into<MultiSpan>>(
159         &self,
160         sp: S,
161         err: Error,
162     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
163         err.span_err(sp, self.diagnostic())
164     }
165
166     pub fn struct_span_err<S: Into<MultiSpan>>(
167         &self,
168         sp: S,
169         m: &str,
170     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
171         self.sess.span_diagnostic.struct_span_err(sp, m)
172     }
173
174     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
175         self.sess.span_diagnostic.span_bug(sp, m)
176     }
177
178     pub(super) fn diagnostic(&self) -> &'a Handler {
179         &self.sess.span_diagnostic
180     }
181
182     pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
183         self.sess.source_map().span_to_snippet(span)
184     }
185
186     pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
187         let mut err = self.struct_span_err(
188             self.token.span,
189             &format!("expected identifier, found {}", super::token_descr(&self.token)),
190         );
191         let valid_follow = &[
192             TokenKind::Eq,
193             TokenKind::Colon,
194             TokenKind::Comma,
195             TokenKind::Semi,
196             TokenKind::ModSep,
197             TokenKind::OpenDelim(token::DelimToken::Brace),
198             TokenKind::OpenDelim(token::DelimToken::Paren),
199             TokenKind::CloseDelim(token::DelimToken::Brace),
200             TokenKind::CloseDelim(token::DelimToken::Paren),
201         ];
202         match self.token.ident() {
203             Some((ident, false))
204                 if ident.is_raw_guess()
205                     && self.look_ahead(1, |t| valid_follow.contains(&t.kind)) =>
206             {
207                 err.span_suggestion_verbose(
208                     ident.span.shrink_to_lo(),
209                     &format!("escape `{}` to use it as an identifier", ident.name),
210                     "r#".to_owned(),
211                     Applicability::MaybeIncorrect,
212                 );
213             }
214             _ => {}
215         }
216         if let Some(token_descr) = super::token_descr_opt(&self.token) {
217             err.span_label(self.token.span, format!("expected identifier, found {}", token_descr));
218         } else {
219             err.span_label(self.token.span, "expected identifier");
220             if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
221                 err.span_suggestion(
222                     self.token.span,
223                     "remove this comma",
224                     String::new(),
225                     Applicability::MachineApplicable,
226                 );
227             }
228         }
229         err
230     }
231
232     pub(super) fn expected_one_of_not_found(
233         &mut self,
234         edible: &[TokenKind],
235         inedible: &[TokenKind],
236     ) -> PResult<'a, bool /* recovered */> {
237         debug!("expected_one_of_not_found(edible: {:?}, inedible: {:?})", edible, inedible);
238         fn tokens_to_string(tokens: &[TokenType]) -> String {
239             let mut i = tokens.iter();
240             // This might be a sign we need a connect method on `Iterator`.
241             let b = i.next().map_or_else(String::new, |t| t.to_string());
242             i.enumerate().fold(b, |mut b, (i, a)| {
243                 if tokens.len() > 2 && i == tokens.len() - 2 {
244                     b.push_str(", or ");
245                 } else if tokens.len() == 2 && i == tokens.len() - 2 {
246                     b.push_str(" or ");
247                 } else {
248                     b.push_str(", ");
249                 }
250                 b.push_str(&a.to_string());
251                 b
252             })
253         }
254
255         let mut expected = edible
256             .iter()
257             .map(|x| TokenType::Token(x.clone()))
258             .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
259             .chain(self.expected_tokens.iter().cloned())
260             .collect::<Vec<_>>();
261         expected.sort_by_cached_key(|x| x.to_string());
262         expected.dedup();
263
264         let sm = self.sess.source_map();
265         let msg = format!("expected `;`, found {}", super::token_descr(&self.token));
266         let appl = Applicability::MachineApplicable;
267         if expected.contains(&TokenType::Token(token::Semi)) {
268             if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
269                 // Likely inside a macro, can't provide meaningful suggestions.
270             } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
271                 // The current token is in the same line as the prior token, not recoverable.
272             } else if [token::Comma, token::Colon].contains(&self.token.kind)
273                 && self.prev_token.kind == token::CloseDelim(token::Paren)
274             {
275                 // Likely typo: The current token is on a new line and is expected to be
276                 // `.`, `;`, `?`, or an operator after a close delimiter token.
277                 //
278                 // let a = std::process::Command::new("echo")
279                 //         .arg("1")
280                 //         ,arg("2")
281                 //         ^
282                 // https://github.com/rust-lang/rust/issues/72253
283             } else if self.look_ahead(1, |t| {
284                 t == &token::CloseDelim(token::Brace)
285                     || t.can_begin_expr() && t.kind != token::Colon
286             }) && [token::Comma, token::Colon].contains(&self.token.kind)
287             {
288                 // Likely typo: `,` â†’ `;` or `:` â†’ `;`. This is triggered if the current token is
289                 // either `,` or `:`, and the next token could either start a new statement or is a
290                 // block close. For example:
291                 //
292                 //   let x = 32:
293                 //   let y = 42;
294                 self.bump();
295                 let sp = self.prev_token.span;
296                 self.struct_span_err(sp, &msg)
297                     .span_suggestion_short(sp, "change this to `;`", ";".to_string(), appl)
298                     .emit();
299                 return Ok(true);
300             } else if self.look_ahead(0, |t| {
301                 t == &token::CloseDelim(token::Brace)
302                     || (
303                         t.can_begin_expr() && t != &token::Semi && t != &token::Pound
304                         // Avoid triggering with too many trailing `#` in raw string.
305                     )
306             }) {
307                 // Missing semicolon typo. This is triggered if the next token could either start a
308                 // new statement or is a block close. For example:
309                 //
310                 //   let x = 32
311                 //   let y = 42;
312                 let sp = self.prev_token.span.shrink_to_hi();
313                 self.struct_span_err(sp, &msg)
314                     .span_label(self.token.span, "unexpected token")
315                     .span_suggestion_short(sp, "add `;` here", ";".to_string(), appl)
316                     .emit();
317                 return Ok(true);
318             }
319         }
320
321         let expect = tokens_to_string(&expected);
322         let actual = super::token_descr(&self.token);
323         let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
324             let short_expect = if expected.len() > 6 {
325                 format!("{} possible tokens", expected.len())
326             } else {
327                 expect.clone()
328             };
329             (
330                 format!("expected one of {}, found {}", expect, actual),
331                 (self.prev_token.span.shrink_to_hi(), format!("expected one of {}", short_expect)),
332             )
333         } else if expected.is_empty() {
334             (
335                 format!("unexpected token: {}", actual),
336                 (self.prev_token.span, "unexpected token after this".to_string()),
337             )
338         } else {
339             (
340                 format!("expected {}, found {}", expect, actual),
341                 (self.prev_token.span.shrink_to_hi(), format!("expected {}", expect)),
342             )
343         };
344         self.last_unexpected_token_span = Some(self.token.span);
345         let mut err = self.struct_span_err(self.token.span, &msg_exp);
346
347         // Add suggestion for a missing closing angle bracket if '>' is included in expected_tokens
348         // there are unclosed angle brackets
349         if self.unmatched_angle_bracket_count > 0
350             && self.token.kind == TokenKind::Eq
351             && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Gt)))
352         {
353             err.span_label(self.prev_token.span, "maybe try to close unmatched angle bracket");
354         }
355
356         let sp = if self.token == token::Eof {
357             // This is EOF; don't want to point at the following char, but rather the last token.
358             self.prev_token.span
359         } else {
360             label_sp
361         };
362         match self.recover_closing_delimiter(
363             &expected
364                 .iter()
365                 .filter_map(|tt| match tt {
366                     TokenType::Token(t) => Some(t.clone()),
367                     _ => None,
368                 })
369                 .collect::<Vec<_>>(),
370             err,
371         ) {
372             Err(e) => err = e,
373             Ok(recovered) => {
374                 return Ok(recovered);
375             }
376         }
377
378         if self.check_too_many_raw_str_terminators(&mut err) {
379             return Err(err);
380         }
381
382         if self.prev_token.span == DUMMY_SP {
383             // Account for macro context where the previous span might not be
384             // available to avoid incorrect output (#54841).
385             err.span_label(self.token.span, label_exp);
386         } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
387             // When the spans are in the same line, it means that the only content between
388             // them is whitespace, point at the found token in that case:
389             //
390             // X |     () => { syntax error };
391             //   |                    ^^^^^ expected one of 8 possible tokens here
392             //
393             // instead of having:
394             //
395             // X |     () => { syntax error };
396             //   |                   -^^^^^ unexpected token
397             //   |                   |
398             //   |                   expected one of 8 possible tokens here
399             err.span_label(self.token.span, label_exp);
400         } else {
401             err.span_label(sp, label_exp);
402             err.span_label(self.token.span, "unexpected token");
403         }
404         self.maybe_annotate_with_ascription(&mut err, false);
405         Err(err)
406     }
407
408     fn check_too_many_raw_str_terminators(&mut self, err: &mut Diagnostic) -> bool {
409         match (&self.prev_token.kind, &self.token.kind) {
410             (
411                 TokenKind::Literal(Lit {
412                     kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
413                     ..
414                 }),
415                 TokenKind::Pound,
416             ) => {
417                 err.set_primary_message("too many `#` when terminating raw string");
418                 err.span_suggestion(
419                     self.token.span,
420                     "remove the extra `#`",
421                     String::new(),
422                     Applicability::MachineApplicable,
423                 );
424                 err.note(&format!("the raw string started with {} `#`s", n_hashes));
425                 true
426             }
427             _ => false,
428         }
429     }
430
431     pub fn maybe_suggest_struct_literal(
432         &mut self,
433         lo: Span,
434         s: BlockCheckMode,
435     ) -> Option<PResult<'a, P<Block>>> {
436         if self.token.is_ident() && self.look_ahead(1, |t| t == &token::Colon) {
437             // We might be having a struct literal where people forgot to include the path:
438             // fn foo() -> Foo {
439             //     field: value,
440             // }
441             let mut snapshot = self.clone();
442             let path =
443                 Path { segments: vec![], span: self.prev_token.span.shrink_to_lo(), tokens: None };
444             let struct_expr = snapshot.parse_struct_expr(None, path, AttrVec::new(), false);
445             let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No);
446             return Some(match (struct_expr, block_tail) {
447                 (Ok(expr), Err(mut err)) => {
448                     // We have encountered the following:
449                     // fn foo() -> Foo {
450                     //     field: value,
451                     // }
452                     // Suggest:
453                     // fn foo() -> Foo { Path {
454                     //     field: value,
455                     // } }
456                     err.delay_as_bug();
457                     self.struct_span_err(expr.span, "struct literal body without path")
458                         .multipart_suggestion(
459                             "you might have forgotten to add the struct literal inside the block",
460                             vec![
461                                 (expr.span.shrink_to_lo(), "{ SomeStruct ".to_string()),
462                                 (expr.span.shrink_to_hi(), " }".to_string()),
463                             ],
464                             Applicability::MaybeIncorrect,
465                         )
466                         .emit();
467                     *self = snapshot;
468                     let mut tail = self.mk_block(
469                         vec![self.mk_stmt_err(expr.span)],
470                         s,
471                         lo.to(self.prev_token.span),
472                     );
473                     tail.could_be_bare_literal = true;
474                     Ok(tail)
475                 }
476                 (Err(err), Ok(tail)) => {
477                     // We have a block tail that contains a somehow valid type ascription expr.
478                     err.cancel();
479                     Ok(tail)
480                 }
481                 (Err(snapshot_err), Err(err)) => {
482                     // We don't know what went wrong, emit the normal error.
483                     snapshot_err.cancel();
484                     self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
485                     Err(err)
486                 }
487                 (Ok(_), Ok(mut tail)) => {
488                     tail.could_be_bare_literal = true;
489                     Ok(tail)
490                 }
491             });
492         }
493         None
494     }
495
496     pub fn maybe_annotate_with_ascription(
497         &mut self,
498         err: &mut Diagnostic,
499         maybe_expected_semicolon: bool,
500     ) {
501         if let Some((sp, likely_path)) = self.last_type_ascription.take() {
502             let sm = self.sess.source_map();
503             let next_pos = sm.lookup_char_pos(self.token.span.lo());
504             let op_pos = sm.lookup_char_pos(sp.hi());
505
506             let allow_unstable = self.sess.unstable_features.is_nightly_build();
507
508             if likely_path {
509                 err.span_suggestion(
510                     sp,
511                     "maybe write a path separator here",
512                     "::".to_string(),
513                     if allow_unstable {
514                         Applicability::MaybeIncorrect
515                     } else {
516                         Applicability::MachineApplicable
517                     },
518                 );
519                 self.sess.type_ascription_path_suggestions.borrow_mut().insert(sp);
520             } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
521                 err.span_suggestion(
522                     sp,
523                     "try using a semicolon",
524                     ";".to_string(),
525                     Applicability::MaybeIncorrect,
526                 );
527             } else if allow_unstable {
528                 err.span_label(sp, "tried to parse a type due to this type ascription");
529             } else {
530                 err.span_label(sp, "tried to parse a type due to this");
531             }
532             if allow_unstable {
533                 // Give extra information about type ascription only if it's a nightly compiler.
534                 err.note(
535                     "`#![feature(type_ascription)]` lets you annotate an expression with a type: \
536                      `<expr>: <type>`",
537                 );
538                 if !likely_path {
539                     // Avoid giving too much info when it was likely an unrelated typo.
540                     err.note(
541                         "see issue #23416 <https://github.com/rust-lang/rust/issues/23416> \
542                         for more information",
543                     );
544                 }
545             }
546         }
547     }
548
549     /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
550     /// passes through any errors encountered. Used for error recovery.
551     pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
552         if let Err(err) =
553             self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
554                 Ok(p.parse_token_tree())
555             })
556         {
557             err.cancel();
558         }
559     }
560
561     /// This function checks if there are trailing angle brackets and produces
562     /// a diagnostic to suggest removing them.
563     ///
564     /// ```ignore (diagnostic)
565     /// let _ = [1, 2, 3].into_iter().collect::<Vec<usize>>>>();
566     ///                                                    ^^ help: remove extra angle brackets
567     /// ```
568     ///
569     /// If `true` is returned, then trailing brackets were recovered, tokens were consumed
570     /// up until one of the tokens in 'end' was encountered, and an error was emitted.
571     pub(super) fn check_trailing_angle_brackets(
572         &mut self,
573         segment: &PathSegment,
574         end: &[&TokenKind],
575     ) -> bool {
576         // This function is intended to be invoked after parsing a path segment where there are two
577         // cases:
578         //
579         // 1. A specific token is expected after the path segment.
580         //    eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
581         //        `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
582         // 2. No specific token is expected after the path segment.
583         //    eg. `x.foo` (field access)
584         //
585         // This function is called after parsing `.foo` and before parsing the token `end` (if
586         // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
587         // `Foo::<Bar>`.
588
589         // We only care about trailing angle brackets if we previously parsed angle bracket
590         // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
591         // removed in this case:
592         //
593         // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
594         //
595         // This case is particularly tricky as we won't notice it just looking at the tokens -
596         // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
597         // have already been parsed):
598         //
599         // `x.foo::<u32>>>(3)`
600         let parsed_angle_bracket_args =
601             segment.args.as_ref().map_or(false, |args| args.is_angle_bracketed());
602
603         debug!(
604             "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
605             parsed_angle_bracket_args,
606         );
607         if !parsed_angle_bracket_args {
608             return false;
609         }
610
611         // Keep the span at the start so we can highlight the sequence of `>` characters to be
612         // removed.
613         let lo = self.token.span;
614
615         // We need to look-ahead to see if we have `>` characters without moving the cursor forward
616         // (since we might have the field access case and the characters we're eating are
617         // actual operators and not trailing characters - ie `x.foo >> 3`).
618         let mut position = 0;
619
620         // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
621         // many of each (so we can correctly pluralize our error messages) and continue to
622         // advance.
623         let mut number_of_shr = 0;
624         let mut number_of_gt = 0;
625         while self.look_ahead(position, |t| {
626             trace!("check_trailing_angle_brackets: t={:?}", t);
627             if *t == token::BinOp(token::BinOpToken::Shr) {
628                 number_of_shr += 1;
629                 true
630             } else if *t == token::Gt {
631                 number_of_gt += 1;
632                 true
633             } else {
634                 false
635             }
636         }) {
637             position += 1;
638         }
639
640         // If we didn't find any trailing `>` characters, then we have nothing to error about.
641         debug!(
642             "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
643             number_of_gt, number_of_shr,
644         );
645         if number_of_gt < 1 && number_of_shr < 1 {
646             return false;
647         }
648
649         // Finally, double check that we have our end token as otherwise this is the
650         // second case.
651         if self.look_ahead(position, |t| {
652             trace!("check_trailing_angle_brackets: t={:?}", t);
653             end.contains(&&t.kind)
654         }) {
655             // Eat from where we started until the end token so that parsing can continue
656             // as if we didn't have those extra angle brackets.
657             self.eat_to_tokens(end);
658             let span = lo.until(self.token.span);
659
660             let total_num_of_gt = number_of_gt + number_of_shr * 2;
661             self.struct_span_err(
662                 span,
663                 &format!("unmatched angle bracket{}", pluralize!(total_num_of_gt)),
664             )
665             .span_suggestion(
666                 span,
667                 &format!("remove extra angle bracket{}", pluralize!(total_num_of_gt)),
668                 String::new(),
669                 Applicability::MachineApplicable,
670             )
671             .emit();
672             return true;
673         }
674         false
675     }
676
677     /// Check if a method call with an intended turbofish has been written without surrounding
678     /// angle brackets.
679     pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
680         if token::ModSep == self.token.kind && segment.args.is_none() {
681             let snapshot = self.clone();
682             self.bump();
683             let lo = self.token.span;
684             match self.parse_angle_args(None) {
685                 Ok(args) => {
686                     let span = lo.to(self.prev_token.span);
687                     // Detect trailing `>` like in `x.collect::Vec<_>>()`.
688                     let mut trailing_span = self.prev_token.span.shrink_to_hi();
689                     while self.token.kind == token::BinOp(token::Shr)
690                         || self.token.kind == token::Gt
691                     {
692                         trailing_span = trailing_span.to(self.token.span);
693                         self.bump();
694                     }
695                     if self.token.kind == token::OpenDelim(token::Paren) {
696                         // Recover from bad turbofish: `foo.collect::Vec<_>()`.
697                         let args = AngleBracketedArgs { args, span }.into();
698                         segment.args = args;
699
700                         self.struct_span_err(
701                             span,
702                             "generic parameters without surrounding angle brackets",
703                         )
704                         .multipart_suggestion(
705                             "surround the type parameters with angle brackets",
706                             vec![
707                                 (span.shrink_to_lo(), "<".to_string()),
708                                 (trailing_span, ">".to_string()),
709                             ],
710                             Applicability::MachineApplicable,
711                         )
712                         .emit();
713                     } else {
714                         // This doesn't look like an invalid turbofish, can't recover parse state.
715                         *self = snapshot;
716                     }
717                 }
718                 Err(err) => {
719                     // We couldn't parse generic parameters, unlikely to be a turbofish. Rely on
720                     // generic parse error instead.
721                     err.cancel();
722                     *self = snapshot;
723                 }
724             }
725         }
726     }
727
728     /// When writing a turbofish with multiple type parameters missing the leading `::`, we will
729     /// encounter a parse error when encountering the first `,`.
730     pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
731         &mut self,
732         mut e: DiagnosticBuilder<'a, ErrorGuaranteed>,
733         expr: &mut P<Expr>,
734     ) -> PResult<'a, ()> {
735         if let ExprKind::Binary(binop, _, _) = &expr.kind
736             && let ast::BinOpKind::Lt = binop.node
737             && self.eat(&token::Comma)
738         {
739             let x = self.parse_seq_to_before_end(
740                 &token::Gt,
741                 SeqSep::trailing_allowed(token::Comma),
742                 |p| p.parse_generic_arg(None),
743             );
744             match x {
745                 Ok((_, _, false)) => {
746                     if self.eat(&token::Gt) {
747                         e.span_suggestion_verbose(
748                             binop.span.shrink_to_lo(),
749                             TURBOFISH_SUGGESTION_STR,
750                             "::".to_string(),
751                             Applicability::MaybeIncorrect,
752                         )
753                         .emit();
754                         match self.parse_expr() {
755                             Ok(_) => {
756                                 *expr =
757                                     self.mk_expr_err(expr.span.to(self.prev_token.span));
758                                 return Ok(());
759                             }
760                             Err(err) => {
761                                 *expr = self.mk_expr_err(expr.span);
762                                 err.cancel();
763                             }
764                         }
765                     }
766                 }
767                 Err(err) => {
768                     err.cancel();
769                 }
770                 _ => {}
771             }
772         }
773         Err(e)
774     }
775
776     /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
777     /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
778     /// parenthesising the leftmost comparison.
779     fn attempt_chained_comparison_suggestion(
780         &mut self,
781         err: &mut Diagnostic,
782         inner_op: &Expr,
783         outer_op: &Spanned<AssocOp>,
784     ) -> bool /* advanced the cursor */ {
785         if let ExprKind::Binary(op, ref l1, ref r1) = inner_op.kind {
786             if let ExprKind::Field(_, ident) = l1.kind
787                 && ident.as_str().parse::<i32>().is_err()
788                 && !matches!(r1.kind, ExprKind::Lit(_))
789             {
790                 // The parser has encountered `foo.bar<baz`, the likelihood of the turbofish
791                 // suggestion being the only one to apply is high.
792                 return false;
793             }
794             let mut enclose = |left: Span, right: Span| {
795                 err.multipart_suggestion(
796                     "parenthesize the comparison",
797                     vec![
798                         (left.shrink_to_lo(), "(".to_string()),
799                         (right.shrink_to_hi(), ")".to_string()),
800                     ],
801                     Applicability::MaybeIncorrect,
802                 );
803             };
804             return match (op.node, &outer_op.node) {
805                 // `x == y == z`
806                 (BinOpKind::Eq, AssocOp::Equal) |
807                 // `x < y < z` and friends.
808                 (BinOpKind::Lt, AssocOp::Less | AssocOp::LessEqual) |
809                 (BinOpKind::Le, AssocOp::LessEqual | AssocOp::Less) |
810                 // `x > y > z` and friends.
811                 (BinOpKind::Gt, AssocOp::Greater | AssocOp::GreaterEqual) |
812                 (BinOpKind::Ge, AssocOp::GreaterEqual | AssocOp::Greater) => {
813                     let expr_to_str = |e: &Expr| {
814                         self.span_to_snippet(e.span)
815                             .unwrap_or_else(|_| pprust::expr_to_string(&e))
816                     };
817                     err.span_suggestion_verbose(
818                         inner_op.span.shrink_to_hi(),
819                         "split the comparison into two",
820                         format!(" && {}", expr_to_str(&r1)),
821                         Applicability::MaybeIncorrect,
822                     );
823                     false // Keep the current parse behavior, where the AST is `(x < y) < z`.
824                 }
825                 // `x == y < z`
826                 (BinOpKind::Eq, AssocOp::Less | AssocOp::LessEqual | AssocOp::Greater | AssocOp::GreaterEqual) => {
827                     // Consume `z`/outer-op-rhs.
828                     let snapshot = self.clone();
829                     match self.parse_expr() {
830                         Ok(r2) => {
831                             // We are sure that outer-op-rhs could be consumed, the suggestion is
832                             // likely correct.
833                             enclose(r1.span, r2.span);
834                             true
835                         }
836                         Err(expr_err) => {
837                             expr_err.cancel();
838                             *self = snapshot;
839                             false
840                         }
841                     }
842                 }
843                 // `x > y == z`
844                 (BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge, AssocOp::Equal) => {
845                     let snapshot = self.clone();
846                     // At this point it is always valid to enclose the lhs in parentheses, no
847                     // further checks are necessary.
848                     match self.parse_expr() {
849                         Ok(_) => {
850                             enclose(l1.span, r1.span);
851                             true
852                         }
853                         Err(expr_err) => {
854                             expr_err.cancel();
855                             *self = snapshot;
856                             false
857                         }
858                     }
859                 }
860                 _ => false,
861             };
862         }
863         false
864     }
865
866     /// Produces an error if comparison operators are chained (RFC #558).
867     /// We only need to check the LHS, not the RHS, because all comparison ops have same
868     /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
869     ///
870     /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
871     /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
872     /// case.
873     ///
874     /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
875     /// associative we can infer that we have:
876     ///
877     /// ```text
878     ///           outer_op
879     ///           /   \
880     ///     inner_op   r2
881     ///        /  \
882     ///      l1    r1
883     /// ```
884     pub(super) fn check_no_chained_comparison(
885         &mut self,
886         inner_op: &Expr,
887         outer_op: &Spanned<AssocOp>,
888     ) -> PResult<'a, Option<P<Expr>>> {
889         debug_assert!(
890             outer_op.node.is_comparison(),
891             "check_no_chained_comparison: {:?} is not comparison",
892             outer_op.node,
893         );
894
895         let mk_err_expr =
896             |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err, AttrVec::new())));
897
898         match inner_op.kind {
899             ExprKind::Binary(op, ref l1, ref r1) if op.node.is_comparison() => {
900                 let mut err = self.struct_span_err(
901                     vec![op.span, self.prev_token.span],
902                     "comparison operators cannot be chained",
903                 );
904
905                 let suggest = |err: &mut Diagnostic| {
906                     err.span_suggestion_verbose(
907                         op.span.shrink_to_lo(),
908                         TURBOFISH_SUGGESTION_STR,
909                         "::".to_string(),
910                         Applicability::MaybeIncorrect,
911                     );
912                 };
913
914                 // Include `<` to provide this recommendation even in a case like
915                 // `Foo<Bar<Baz<Qux, ()>>>`
916                 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Less
917                     || outer_op.node == AssocOp::Greater
918                 {
919                     if outer_op.node == AssocOp::Less {
920                         let snapshot = self.clone();
921                         self.bump();
922                         // So far we have parsed `foo<bar<`, consume the rest of the type args.
923                         let modifiers =
924                             [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
925                         self.consume_tts(1, &modifiers);
926
927                         if !&[token::OpenDelim(token::Paren), token::ModSep]
928                             .contains(&self.token.kind)
929                         {
930                             // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
931                             // parser and bail out.
932                             *self = snapshot.clone();
933                         }
934                     }
935                     return if token::ModSep == self.token.kind {
936                         // We have some certainty that this was a bad turbofish at this point.
937                         // `foo< bar >::`
938                         suggest(&mut err);
939
940                         let snapshot = self.clone();
941                         self.bump(); // `::`
942
943                         // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
944                         match self.parse_expr() {
945                             Ok(_) => {
946                                 // 99% certain that the suggestion is correct, continue parsing.
947                                 err.emit();
948                                 // FIXME: actually check that the two expressions in the binop are
949                                 // paths and resynthesize new fn call expression instead of using
950                                 // `ExprKind::Err` placeholder.
951                                 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
952                             }
953                             Err(expr_err) => {
954                                 expr_err.cancel();
955                                 // Not entirely sure now, but we bubble the error up with the
956                                 // suggestion.
957                                 *self = snapshot;
958                                 Err(err)
959                             }
960                         }
961                     } else if token::OpenDelim(token::Paren) == self.token.kind {
962                         // We have high certainty that this was a bad turbofish at this point.
963                         // `foo< bar >(`
964                         suggest(&mut err);
965                         // Consume the fn call arguments.
966                         match self.consume_fn_args() {
967                             Err(()) => Err(err),
968                             Ok(()) => {
969                                 err.emit();
970                                 // FIXME: actually check that the two expressions in the binop are
971                                 // paths and resynthesize new fn call expression instead of using
972                                 // `ExprKind::Err` placeholder.
973                                 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
974                             }
975                         }
976                     } else {
977                         if !matches!(l1.kind, ExprKind::Lit(_))
978                             && !matches!(r1.kind, ExprKind::Lit(_))
979                         {
980                             // All we know is that this is `foo < bar >` and *nothing* else. Try to
981                             // be helpful, but don't attempt to recover.
982                             err.help(TURBOFISH_SUGGESTION_STR);
983                             err.help("or use `(...)` if you meant to specify fn arguments");
984                         }
985
986                         // If it looks like a genuine attempt to chain operators (as opposed to a
987                         // misformatted turbofish, for instance), suggest a correct form.
988                         if self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op)
989                         {
990                             err.emit();
991                             mk_err_expr(self, inner_op.span.to(self.prev_token.span))
992                         } else {
993                             // These cases cause too many knock-down errors, bail out (#61329).
994                             Err(err)
995                         }
996                     };
997                 }
998                 let recover =
999                     self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1000                 err.emit();
1001                 if recover {
1002                     return mk_err_expr(self, inner_op.span.to(self.prev_token.span));
1003                 }
1004             }
1005             _ => {}
1006         }
1007         Ok(None)
1008     }
1009
1010     fn consume_fn_args(&mut self) -> Result<(), ()> {
1011         let snapshot = self.clone();
1012         self.bump(); // `(`
1013
1014         // Consume the fn call arguments.
1015         let modifiers =
1016             [(token::OpenDelim(token::Paren), 1), (token::CloseDelim(token::Paren), -1)];
1017         self.consume_tts(1, &modifiers);
1018
1019         if self.token.kind == token::Eof {
1020             // Not entirely sure that what we consumed were fn arguments, rollback.
1021             *self = snapshot;
1022             Err(())
1023         } else {
1024             // 99% certain that the suggestion is correct, continue parsing.
1025             Ok(())
1026         }
1027     }
1028
1029     pub(super) fn maybe_report_ambiguous_plus(
1030         &mut self,
1031         allow_plus: AllowPlus,
1032         impl_dyn_multi: bool,
1033         ty: &Ty,
1034     ) {
1035         if matches!(allow_plus, AllowPlus::No) && impl_dyn_multi {
1036             let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1037             self.struct_span_err(ty.span, "ambiguous `+` in a type")
1038                 .span_suggestion(
1039                     ty.span,
1040                     "use parentheses to disambiguate",
1041                     sum_with_parens,
1042                     Applicability::MachineApplicable,
1043                 )
1044                 .emit();
1045         }
1046     }
1047
1048     /// Swift lets users write `Ty?` to mean `Option<Ty>`. Parse the construct and recover from it.
1049     pub(super) fn maybe_recover_from_question_mark(
1050         &mut self,
1051         ty: P<Ty>,
1052         recover_question_mark: RecoverQuestionMark,
1053     ) -> P<Ty> {
1054         if let RecoverQuestionMark::No = recover_question_mark {
1055             return ty;
1056         }
1057         if self.token == token::Question {
1058             self.bump();
1059             self.struct_span_err(self.prev_token.span, "invalid `?` in type")
1060                 .span_label(self.prev_token.span, "`?` is only allowed on expressions, not types")
1061                 .multipart_suggestion(
1062                     "if you meant to express that the type might not contain a value, use the `Option` wrapper type",
1063                     vec![
1064                         (ty.span.shrink_to_lo(), "Option<".to_string()),
1065                         (self.prev_token.span, ">".to_string()),
1066                     ],
1067                     Applicability::MachineApplicable,
1068                 )
1069                 .emit();
1070             self.mk_ty(ty.span.to(self.prev_token.span), TyKind::Err)
1071         } else {
1072             ty
1073         }
1074     }
1075
1076     pub(super) fn maybe_recover_from_bad_type_plus(
1077         &mut self,
1078         allow_plus: AllowPlus,
1079         ty: &Ty,
1080     ) -> PResult<'a, ()> {
1081         // Do not add `+` to expected tokens.
1082         if matches!(allow_plus, AllowPlus::No) || !self.token.is_like_plus() {
1083             return Ok(());
1084         }
1085
1086         self.bump(); // `+`
1087         let bounds = self.parse_generic_bounds(None)?;
1088         let sum_span = ty.span.to(self.prev_token.span);
1089
1090         let mut err = struct_span_err!(
1091             self.sess.span_diagnostic,
1092             sum_span,
1093             E0178,
1094             "expected a path on the left-hand side of `+`, not `{}`",
1095             pprust::ty_to_string(ty)
1096         );
1097
1098         match ty.kind {
1099             TyKind::Rptr(ref lifetime, ref mut_ty) => {
1100                 let sum_with_parens = pprust::to_string(|s| {
1101                     s.s.word("&");
1102                     s.print_opt_lifetime(lifetime);
1103                     s.print_mutability(mut_ty.mutbl, false);
1104                     s.popen();
1105                     s.print_type(&mut_ty.ty);
1106                     s.print_type_bounds(" +", &bounds);
1107                     s.pclose()
1108                 });
1109                 err.span_suggestion(
1110                     sum_span,
1111                     "try adding parentheses",
1112                     sum_with_parens,
1113                     Applicability::MachineApplicable,
1114                 );
1115             }
1116             TyKind::Ptr(..) | TyKind::BareFn(..) => {
1117                 err.span_label(sum_span, "perhaps you forgot parentheses?");
1118             }
1119             _ => {
1120                 err.span_label(sum_span, "expected a path");
1121             }
1122         }
1123         err.emit();
1124         Ok(())
1125     }
1126
1127     /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
1128     /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
1129     /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
1130     pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
1131         &mut self,
1132         base: P<T>,
1133         allow_recovery: bool,
1134     ) -> PResult<'a, P<T>> {
1135         // Do not add `::` to expected tokens.
1136         if allow_recovery && self.token == token::ModSep {
1137             if let Some(ty) = base.to_ty() {
1138                 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1139             }
1140         }
1141         Ok(base)
1142     }
1143
1144     /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
1145     /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
1146     pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
1147         &mut self,
1148         ty_span: Span,
1149         ty: P<Ty>,
1150     ) -> PResult<'a, P<T>> {
1151         self.expect(&token::ModSep)?;
1152
1153         let mut path = ast::Path { segments: Vec::new(), span: DUMMY_SP, tokens: None };
1154         self.parse_path_segments(&mut path.segments, T::PATH_STYLE, None)?;
1155         path.span = ty_span.to(self.prev_token.span);
1156
1157         let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
1158         self.struct_span_err(path.span, "missing angle brackets in associated item path")
1159             .span_suggestion(
1160                 // This is a best-effort recovery.
1161                 path.span,
1162                 "try",
1163                 format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
1164                 Applicability::MaybeIncorrect,
1165             )
1166             .emit();
1167
1168         let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
1169         Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path)))
1170     }
1171
1172     pub fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
1173         if self.token.kind == TokenKind::Semi {
1174             self.bump();
1175             let mut err = self.struct_span_err(self.prev_token.span, "expected item, found `;`");
1176             err.span_suggestion_short(
1177                 self.prev_token.span,
1178                 "remove this semicolon",
1179                 String::new(),
1180                 Applicability::MachineApplicable,
1181             );
1182             if !items.is_empty() {
1183                 let previous_item = &items[items.len() - 1];
1184                 let previous_item_kind_name = match previous_item.kind {
1185                     // Say "braced struct" because tuple-structs and
1186                     // braceless-empty-struct declarations do take a semicolon.
1187                     ItemKind::Struct(..) => Some("braced struct"),
1188                     ItemKind::Enum(..) => Some("enum"),
1189                     ItemKind::Trait(..) => Some("trait"),
1190                     ItemKind::Union(..) => Some("union"),
1191                     _ => None,
1192                 };
1193                 if let Some(name) = previous_item_kind_name {
1194                     err.help(&format!("{} declarations are not followed by a semicolon", name));
1195                 }
1196             }
1197             err.emit();
1198             true
1199         } else {
1200             false
1201         }
1202     }
1203
1204     /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
1205     /// closing delimiter.
1206     pub(super) fn unexpected_try_recover(
1207         &mut self,
1208         t: &TokenKind,
1209     ) -> PResult<'a, bool /* recovered */> {
1210         let token_str = pprust::token_kind_to_string(t);
1211         let this_token_str = super::token_descr(&self.token);
1212         let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1213             // Point at the end of the macro call when reaching end of macro arguments.
1214             (token::Eof, Some(_)) => {
1215                 let sp = self.sess.source_map().next_point(self.prev_token.span);
1216                 (sp, sp)
1217             }
1218             // We don't want to point at the following span after DUMMY_SP.
1219             // This happens when the parser finds an empty TokenStream.
1220             _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
1221             // EOF, don't want to point at the following char, but rather the last token.
1222             (token::Eof, None) => (self.prev_token.span, self.token.span),
1223             _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
1224         };
1225         let msg = format!(
1226             "expected `{}`, found {}",
1227             token_str,
1228             match (&self.token.kind, self.subparser_name) {
1229                 (token::Eof, Some(origin)) => format!("end of {}", origin),
1230                 _ => this_token_str,
1231             },
1232         );
1233         let mut err = self.struct_span_err(sp, &msg);
1234         let label_exp = format!("expected `{}`", token_str);
1235         match self.recover_closing_delimiter(&[t.clone()], err) {
1236             Err(e) => err = e,
1237             Ok(recovered) => {
1238                 return Ok(recovered);
1239             }
1240         }
1241         let sm = self.sess.source_map();
1242         if !sm.is_multiline(prev_sp.until(sp)) {
1243             // When the spans are in the same line, it means that the only content
1244             // between them is whitespace, point only at the found token.
1245             err.span_label(sp, label_exp);
1246         } else {
1247             err.span_label(prev_sp, label_exp);
1248             err.span_label(sp, "unexpected token");
1249         }
1250         Err(err)
1251     }
1252
1253     pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1254         if self.eat(&token::Semi) {
1255             return Ok(());
1256         }
1257         self.expect(&token::Semi).map(drop) // Error unconditionally
1258     }
1259
1260     /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
1261     /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
1262     pub(super) fn recover_incorrect_await_syntax(
1263         &mut self,
1264         lo: Span,
1265         await_sp: Span,
1266         attrs: AttrVec,
1267     ) -> PResult<'a, P<Expr>> {
1268         let (hi, expr, is_question) = if self.token == token::Not {
1269             // Handle `await!(<expr>)`.
1270             self.recover_await_macro()?
1271         } else {
1272             self.recover_await_prefix(await_sp)?
1273         };
1274         let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
1275         let kind = match expr.kind {
1276             // Avoid knock-down errors as we don't know whether to interpret this as `foo().await?`
1277             // or `foo()?.await` (the very reason we went with postfix syntax ðŸ˜…).
1278             ExprKind::Try(_) => ExprKind::Err,
1279             _ => ExprKind::Await(expr),
1280         };
1281         let expr = self.mk_expr(lo.to(sp), kind, attrs);
1282         self.maybe_recover_from_bad_qpath(expr, true)
1283     }
1284
1285     fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1286         self.expect(&token::Not)?;
1287         self.expect(&token::OpenDelim(token::Paren))?;
1288         let expr = self.parse_expr()?;
1289         self.expect(&token::CloseDelim(token::Paren))?;
1290         Ok((self.prev_token.span, expr, false))
1291     }
1292
1293     fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
1294         let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
1295         let expr = if self.token == token::OpenDelim(token::Brace) {
1296             // Handle `await { <expr> }`.
1297             // This needs to be handled separately from the next arm to avoid
1298             // interpreting `await { <expr> }?` as `<expr>?.await`.
1299             self.parse_block_expr(None, self.token.span, BlockCheckMode::Default, AttrVec::new())
1300         } else {
1301             self.parse_expr()
1302         }
1303         .map_err(|mut err| {
1304             err.span_label(await_sp, "while parsing this incorrect await expression");
1305             err
1306         })?;
1307         Ok((expr.span, expr, is_question))
1308     }
1309
1310     fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
1311         let expr_str =
1312             self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr));
1313         let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" });
1314         let sp = lo.to(hi);
1315         let app = match expr.kind {
1316             ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
1317             _ => Applicability::MachineApplicable,
1318         };
1319         self.struct_span_err(sp, "incorrect use of `await`")
1320             .span_suggestion(sp, "`await` is a postfix operation", suggestion, app)
1321             .emit();
1322         sp
1323     }
1324
1325     /// If encountering `future.await()`, consumes and emits an error.
1326     pub(super) fn recover_from_await_method_call(&mut self) {
1327         if self.token == token::OpenDelim(token::Paren)
1328             && self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren))
1329         {
1330             // future.await()
1331             let lo = self.token.span;
1332             self.bump(); // (
1333             let sp = lo.to(self.token.span);
1334             self.bump(); // )
1335             self.struct_span_err(sp, "incorrect use of `await`")
1336                 .span_suggestion(
1337                     sp,
1338                     "`await` is not a method call, remove the parentheses",
1339                     String::new(),
1340                     Applicability::MachineApplicable,
1341                 )
1342                 .emit();
1343         }
1344     }
1345
1346     pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, P<Expr>> {
1347         let is_try = self.token.is_keyword(kw::Try);
1348         let is_questionmark = self.look_ahead(1, |t| t == &token::Not); //check for !
1349         let is_open = self.look_ahead(2, |t| t == &token::OpenDelim(token::Paren)); //check for (
1350
1351         if is_try && is_questionmark && is_open {
1352             let lo = self.token.span;
1353             self.bump(); //remove try
1354             self.bump(); //remove !
1355             let try_span = lo.to(self.token.span); //we take the try!( span
1356             self.bump(); //remove (
1357             let is_empty = self.token == token::CloseDelim(token::Paren); //check if the block is empty
1358             self.consume_block(token::Paren, ConsumeClosingDelim::No); //eat the block
1359             let hi = self.token.span;
1360             self.bump(); //remove )
1361             let mut err = self.struct_span_err(lo.to(hi), "use of deprecated `try` macro");
1362             err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
1363             let prefix = if is_empty { "" } else { "alternatively, " };
1364             if !is_empty {
1365                 err.multipart_suggestion(
1366                     "you can use the `?` operator instead",
1367                     vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
1368                     Applicability::MachineApplicable,
1369                 );
1370             }
1371             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);
1372             err.emit();
1373             Ok(self.mk_expr_err(lo.to(hi)))
1374         } else {
1375             Err(self.expected_expression_found()) // The user isn't trying to invoke the try! macro
1376         }
1377     }
1378
1379     /// Recovers a situation like `for ( $pat in $expr )`
1380     /// and suggest writing `for $pat in $expr` instead.
1381     ///
1382     /// This should be called before parsing the `$block`.
1383     pub(super) fn recover_parens_around_for_head(
1384         &mut self,
1385         pat: P<Pat>,
1386         begin_paren: Option<Span>,
1387     ) -> P<Pat> {
1388         match (&self.token.kind, begin_paren) {
1389             (token::CloseDelim(token::Paren), Some(begin_par_sp)) => {
1390                 self.bump();
1391
1392                 self.struct_span_err(
1393                     MultiSpan::from_spans(vec![begin_par_sp, self.prev_token.span]),
1394                     "unexpected parentheses surrounding `for` loop head",
1395                 )
1396                 .multipart_suggestion(
1397                     "remove parentheses in `for` loop",
1398                     vec![(begin_par_sp, String::new()), (self.prev_token.span, String::new())],
1399                     // With e.g. `for (x) in y)` this would replace `(x) in y)`
1400                     // with `x) in y)` which is syntactically invalid.
1401                     // However, this is prevented before we get here.
1402                     Applicability::MachineApplicable,
1403                 )
1404                 .emit();
1405
1406                 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1407                 pat.and_then(|pat| match pat.kind {
1408                     PatKind::Paren(pat) => pat,
1409                     _ => P(pat),
1410                 })
1411             }
1412             _ => pat,
1413         }
1414     }
1415
1416     pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1417         (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1418             self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1419             || self.token.is_ident() &&
1420             matches!(node, ast::ExprKind::Path(..) | ast::ExprKind::Field(..)) &&
1421             !self.token.is_reserved_ident() &&           // v `foo:bar(baz)`
1422             self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren))
1423             || self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) // `foo:bar {`
1424             || self.look_ahead(1, |t| t == &token::Colon) &&     // `foo:bar::<baz`
1425             self.look_ahead(2, |t| t == &token::Lt) &&
1426             self.look_ahead(3, |t| t.is_ident())
1427             || self.look_ahead(1, |t| t == &token::Colon) &&  // `foo:bar:baz`
1428             self.look_ahead(2, |t| t.is_ident())
1429             || self.look_ahead(1, |t| t == &token::ModSep)
1430                 && (self.look_ahead(2, |t| t.is_ident()) ||   // `foo:bar::baz`
1431             self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1432     }
1433
1434     pub(super) fn recover_seq_parse_error(
1435         &mut self,
1436         delim: token::DelimToken,
1437         lo: Span,
1438         result: PResult<'a, P<Expr>>,
1439     ) -> P<Expr> {
1440         match result {
1441             Ok(x) => x,
1442             Err(mut err) => {
1443                 err.emit();
1444                 // Recover from parse error, callers expect the closing delim to be consumed.
1445                 self.consume_block(delim, ConsumeClosingDelim::Yes);
1446                 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err, AttrVec::new())
1447             }
1448         }
1449     }
1450
1451     pub(super) fn recover_closing_delimiter(
1452         &mut self,
1453         tokens: &[TokenKind],
1454         mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
1455     ) -> PResult<'a, bool> {
1456         let mut pos = None;
1457         // We want to use the last closing delim that would apply.
1458         for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1459             if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1460                 && Some(self.token.span) > unmatched.unclosed_span
1461             {
1462                 pos = Some(i);
1463             }
1464         }
1465         match pos {
1466             Some(pos) => {
1467                 // Recover and assume that the detected unclosed delimiter was meant for
1468                 // this location. Emit the diagnostic and act as if the delimiter was
1469                 // present for the parser's sake.
1470
1471                 // Don't attempt to recover from this unclosed delimiter more than once.
1472                 let unmatched = self.unclosed_delims.remove(pos);
1473                 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1474                 if unmatched.found_delim.is_none() {
1475                     // We encountered `Eof`, set this fact here to avoid complaining about missing
1476                     // `fn main()` when we found place to suggest the closing brace.
1477                     *self.sess.reached_eof.borrow_mut() = true;
1478                 }
1479
1480                 // We want to suggest the inclusion of the closing delimiter where it makes
1481                 // the most sense, which is immediately after the last token:
1482                 //
1483                 //  {foo(bar {}}
1484                 //      ^      ^
1485                 //      |      |
1486                 //      |      help: `)` may belong here
1487                 //      |
1488                 //      unclosed delimiter
1489                 if let Some(sp) = unmatched.unclosed_span {
1490                     let mut primary_span: Vec<Span> =
1491                         err.span.primary_spans().iter().cloned().collect();
1492                     primary_span.push(sp);
1493                     let mut primary_span: MultiSpan = primary_span.into();
1494                     for span_label in err.span.span_labels() {
1495                         if let Some(label) = span_label.label {
1496                             primary_span.push_span_label(span_label.span, label);
1497                         }
1498                     }
1499                     err.set_span(primary_span);
1500                     err.span_label(sp, "unclosed delimiter");
1501                 }
1502                 // Backticks should be removed to apply suggestions.
1503                 let mut delim = delim.to_string();
1504                 delim.retain(|c| c != '`');
1505                 err.span_suggestion_short(
1506                     self.prev_token.span.shrink_to_hi(),
1507                     &format!("`{}` may belong here", delim),
1508                     delim,
1509                     Applicability::MaybeIncorrect,
1510                 );
1511                 if unmatched.found_delim.is_none() {
1512                     // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1513                     // errors which would be emitted elsewhere in the parser and let other error
1514                     // recovery consume the rest of the file.
1515                     Err(err)
1516                 } else {
1517                     err.emit();
1518                     self.expected_tokens.clear(); // Reduce the number of errors.
1519                     Ok(true)
1520                 }
1521             }
1522             _ => Err(err),
1523         }
1524     }
1525
1526     /// Eats tokens until we can be relatively sure we reached the end of the
1527     /// statement. This is something of a best-effort heuristic.
1528     ///
1529     /// We terminate when we find an unmatched `}` (without consuming it).
1530     pub(super) fn recover_stmt(&mut self) {
1531         self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1532     }
1533
1534     /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1535     /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1536     /// approximate -- it can mean we break too early due to macros, but that
1537     /// should only lead to sub-optimal recovery, not inaccurate parsing).
1538     ///
1539     /// If `break_on_block` is `Break`, then we will stop consuming tokens
1540     /// after finding (and consuming) a brace-delimited block.
1541     pub(super) fn recover_stmt_(
1542         &mut self,
1543         break_on_semi: SemiColonMode,
1544         break_on_block: BlockMode,
1545     ) {
1546         let mut brace_depth = 0;
1547         let mut bracket_depth = 0;
1548         let mut in_block = false;
1549         debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1550         loop {
1551             debug!("recover_stmt_ loop {:?}", self.token);
1552             match self.token.kind {
1553                 token::OpenDelim(token::DelimToken::Brace) => {
1554                     brace_depth += 1;
1555                     self.bump();
1556                     if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1557                     {
1558                         in_block = true;
1559                     }
1560                 }
1561                 token::OpenDelim(token::DelimToken::Bracket) => {
1562                     bracket_depth += 1;
1563                     self.bump();
1564                 }
1565                 token::CloseDelim(token::DelimToken::Brace) => {
1566                     if brace_depth == 0 {
1567                         debug!("recover_stmt_ return - close delim {:?}", self.token);
1568                         break;
1569                     }
1570                     brace_depth -= 1;
1571                     self.bump();
1572                     if in_block && bracket_depth == 0 && brace_depth == 0 {
1573                         debug!("recover_stmt_ return - block end {:?}", self.token);
1574                         break;
1575                     }
1576                 }
1577                 token::CloseDelim(token::DelimToken::Bracket) => {
1578                     bracket_depth -= 1;
1579                     if bracket_depth < 0 {
1580                         bracket_depth = 0;
1581                     }
1582                     self.bump();
1583                 }
1584                 token::Eof => {
1585                     debug!("recover_stmt_ return - Eof");
1586                     break;
1587                 }
1588                 token::Semi => {
1589                     self.bump();
1590                     if break_on_semi == SemiColonMode::Break
1591                         && brace_depth == 0
1592                         && bracket_depth == 0
1593                     {
1594                         debug!("recover_stmt_ return - Semi");
1595                         break;
1596                     }
1597                 }
1598                 token::Comma
1599                     if break_on_semi == SemiColonMode::Comma
1600                         && brace_depth == 0
1601                         && bracket_depth == 0 =>
1602                 {
1603                     debug!("recover_stmt_ return - Semi");
1604                     break;
1605                 }
1606                 _ => self.bump(),
1607             }
1608         }
1609     }
1610
1611     pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1612         if self.eat_keyword(kw::In) {
1613             // a common typo: `for _ in in bar {}`
1614             self.struct_span_err(self.prev_token.span, "expected iterable, found keyword `in`")
1615                 .span_suggestion_short(
1616                     in_span.until(self.prev_token.span),
1617                     "remove the duplicated `in`",
1618                     String::new(),
1619                     Applicability::MachineApplicable,
1620                 )
1621                 .emit();
1622         }
1623     }
1624
1625     pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1626         if let token::DocComment(..) = self.token.kind {
1627             self.struct_span_err(
1628                 self.token.span,
1629                 "documentation comments cannot be applied to a function parameter's type",
1630             )
1631             .span_label(self.token.span, "doc comments are not allowed here")
1632             .emit();
1633             self.bump();
1634         } else if self.token == token::Pound
1635             && self.look_ahead(1, |t| *t == token::OpenDelim(token::Bracket))
1636         {
1637             let lo = self.token.span;
1638             // Skip every token until next possible arg.
1639             while self.token != token::CloseDelim(token::Bracket) {
1640                 self.bump();
1641             }
1642             let sp = lo.to(self.token.span);
1643             self.bump();
1644             self.struct_span_err(sp, "attributes cannot be applied to a function parameter's type")
1645                 .span_label(sp, "attributes are not allowed here")
1646                 .emit();
1647         }
1648     }
1649
1650     pub(super) fn parameter_without_type(
1651         &mut self,
1652         err: &mut Diagnostic,
1653         pat: P<ast::Pat>,
1654         require_name: bool,
1655         first_param: bool,
1656     ) -> Option<Ident> {
1657         // If we find a pattern followed by an identifier, it could be an (incorrect)
1658         // C-style parameter declaration.
1659         if self.check_ident()
1660             && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseDelim(token::Paren))
1661         {
1662             // `fn foo(String s) {}`
1663             let ident = self.parse_ident().unwrap();
1664             let span = pat.span.with_hi(ident.span.hi());
1665
1666             err.span_suggestion(
1667                 span,
1668                 "declare the type after the parameter binding",
1669                 String::from("<identifier>: <type>"),
1670                 Applicability::HasPlaceholders,
1671             );
1672             return Some(ident);
1673         } else if require_name
1674             && (self.token == token::Comma
1675                 || self.token == token::Lt
1676                 || self.token == token::CloseDelim(token::Paren))
1677         {
1678             let rfc_note = "anonymous parameters are removed in the 2018 edition (see RFC 1685)";
1679
1680             let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
1681                 match pat.kind {
1682                     PatKind::Ident(_, ident, _) => (
1683                         ident,
1684                         "self: ".to_string(),
1685                         ": TypeName".to_string(),
1686                         "_: ".to_string(),
1687                         pat.span.shrink_to_lo(),
1688                         pat.span.shrink_to_hi(),
1689                         pat.span.shrink_to_lo(),
1690                     ),
1691                     // Also catches `fn foo(&a)`.
1692                     PatKind::Ref(ref inner_pat, mutab)
1693                         if matches!(inner_pat.clone().into_inner().kind, PatKind::Ident(..)) =>
1694                     {
1695                         match inner_pat.clone().into_inner().kind {
1696                             PatKind::Ident(_, ident, _) => {
1697                                 let mutab = mutab.prefix_str();
1698                                 (
1699                                     ident,
1700                                     "self: ".to_string(),
1701                                     format!("{}: &{}TypeName", ident, mutab),
1702                                     "_: ".to_string(),
1703                                     pat.span.shrink_to_lo(),
1704                                     pat.span,
1705                                     pat.span.shrink_to_lo(),
1706                                 )
1707                             }
1708                             _ => unreachable!(),
1709                         }
1710                     }
1711                     _ => {
1712                         // Otherwise, try to get a type and emit a suggestion.
1713                         if let Some(ty) = pat.to_ty() {
1714                             err.span_suggestion_verbose(
1715                                 pat.span,
1716                                 "explicitly ignore the parameter name",
1717                                 format!("_: {}", pprust::ty_to_string(&ty)),
1718                                 Applicability::MachineApplicable,
1719                             );
1720                             err.note(rfc_note);
1721                         }
1722
1723                         return None;
1724                     }
1725                 };
1726
1727             // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1728             if first_param {
1729                 err.span_suggestion(
1730                     self_span,
1731                     "if this is a `self` type, give it a parameter name",
1732                     self_sugg,
1733                     Applicability::MaybeIncorrect,
1734                 );
1735             }
1736             // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
1737             // `fn foo(HashMap: TypeName<u32>)`.
1738             if self.token != token::Lt {
1739                 err.span_suggestion(
1740                     param_span,
1741                     "if this is a parameter name, give it a type",
1742                     param_sugg,
1743                     Applicability::HasPlaceholders,
1744                 );
1745             }
1746             err.span_suggestion(
1747                 type_span,
1748                 "if this is a type, explicitly ignore the parameter name",
1749                 type_sugg,
1750                 Applicability::MachineApplicable,
1751             );
1752             err.note(rfc_note);
1753
1754             // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
1755             return if self.token == token::Lt { None } else { Some(ident) };
1756         }
1757         None
1758     }
1759
1760     pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
1761         let pat = self.parse_pat_no_top_alt(Some("argument name"))?;
1762         self.expect(&token::Colon)?;
1763         let ty = self.parse_ty()?;
1764
1765         struct_span_err!(
1766             self.diagnostic(),
1767             pat.span,
1768             E0642,
1769             "patterns aren't allowed in methods without bodies",
1770         )
1771         .span_suggestion_short(
1772             pat.span,
1773             "give this argument a name or use an underscore to ignore it",
1774             "_".to_owned(),
1775             Applicability::MachineApplicable,
1776         )
1777         .emit();
1778
1779         // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1780         let pat =
1781             P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID, tokens: None });
1782         Ok((pat, ty))
1783     }
1784
1785     pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
1786         let sp = param.pat.span;
1787         param.ty.kind = TyKind::Err;
1788         self.struct_span_err(sp, "unexpected `self` parameter in function")
1789             .span_label(sp, "must be the first parameter of an associated function")
1790             .emit();
1791         Ok(param)
1792     }
1793
1794     pub(super) fn consume_block(
1795         &mut self,
1796         delim: token::DelimToken,
1797         consume_close: ConsumeClosingDelim,
1798     ) {
1799         let mut brace_depth = 0;
1800         loop {
1801             if self.eat(&token::OpenDelim(delim)) {
1802                 brace_depth += 1;
1803             } else if self.check(&token::CloseDelim(delim)) {
1804                 if brace_depth == 0 {
1805                     if let ConsumeClosingDelim::Yes = consume_close {
1806                         // Some of the callers of this method expect to be able to parse the
1807                         // closing delimiter themselves, so we leave it alone. Otherwise we advance
1808                         // the parser.
1809                         self.bump();
1810                     }
1811                     return;
1812                 } else {
1813                     self.bump();
1814                     brace_depth -= 1;
1815                     continue;
1816                 }
1817             } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
1818                 return;
1819             } else {
1820                 self.bump();
1821             }
1822         }
1823     }
1824
1825     pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1826         let (span, msg) = match (&self.token.kind, self.subparser_name) {
1827             (&token::Eof, Some(origin)) => {
1828                 let sp = self.sess.source_map().next_point(self.prev_token.span);
1829                 (sp, format!("expected expression, found end of {}", origin))
1830             }
1831             _ => (
1832                 self.token.span,
1833                 format!("expected expression, found {}", super::token_descr(&self.token),),
1834             ),
1835         };
1836         let mut err = self.struct_span_err(span, &msg);
1837         let sp = self.sess.source_map().start_point(self.token.span);
1838         if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
1839             self.sess.expr_parentheses_needed(&mut err, *sp);
1840         }
1841         err.span_label(span, "expected expression");
1842         err
1843     }
1844
1845     fn consume_tts(
1846         &mut self,
1847         mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
1848         // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
1849         modifier: &[(token::TokenKind, i64)],
1850     ) {
1851         while acc > 0 {
1852             if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
1853                 acc += *val;
1854             }
1855             if self.token.kind == token::Eof {
1856                 break;
1857             }
1858             self.bump();
1859         }
1860     }
1861
1862     /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
1863     ///
1864     /// This is necessary because at this point we don't know whether we parsed a function with
1865     /// anonymous parameters or a function with names but no types. In order to minimize
1866     /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
1867     /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
1868     /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
1869     /// we deduplicate them to not complain about duplicated parameter names.
1870     pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
1871         let mut seen_inputs = FxHashSet::default();
1872         for input in fn_inputs.iter_mut() {
1873             let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
1874                 (&input.pat.kind, &input.ty.kind)
1875             {
1876                 Some(*ident)
1877             } else {
1878                 None
1879             };
1880             if let Some(ident) = opt_ident {
1881                 if seen_inputs.contains(&ident) {
1882                     input.pat.kind = PatKind::Wild;
1883                 }
1884                 seen_inputs.insert(ident);
1885             }
1886         }
1887     }
1888
1889     /// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
1890     /// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
1891     /// like the user has forgotten them.
1892     pub fn handle_ambiguous_unbraced_const_arg(
1893         &mut self,
1894         args: &mut Vec<AngleBracketedArg>,
1895     ) -> PResult<'a, bool> {
1896         // If we haven't encountered a closing `>`, then the argument is malformed.
1897         // It's likely that the user has written a const expression without enclosing it
1898         // in braces, so we try to recover here.
1899         let arg = args.pop().unwrap();
1900         // FIXME: for some reason using `unexpected` or `expected_one_of_not_found` has
1901         // adverse side-effects to subsequent errors and seems to advance the parser.
1902         // We are causing this error here exclusively in case that a `const` expression
1903         // could be recovered from the current parser state, even if followed by more
1904         // arguments after a comma.
1905         let mut err = self.struct_span_err(
1906             self.token.span,
1907             &format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
1908         );
1909         err.span_label(self.token.span, "expected one of `,` or `>`");
1910         match self.recover_const_arg(arg.span(), err) {
1911             Ok(arg) => {
1912                 args.push(AngleBracketedArg::Arg(arg));
1913                 if self.eat(&token::Comma) {
1914                     return Ok(true); // Continue
1915                 }
1916             }
1917             Err(mut err) => {
1918                 args.push(arg);
1919                 // We will emit a more generic error later.
1920                 err.delay_as_bug();
1921             }
1922         }
1923         return Ok(false); // Don't continue.
1924     }
1925
1926     /// Attempt to parse a generic const argument that has not been enclosed in braces.
1927     /// There are a limited number of expressions that are permitted without being encoded
1928     /// in braces:
1929     /// - Literals.
1930     /// - Single-segment paths (i.e. standalone generic const parameters).
1931     /// All other expressions that can be parsed will emit an error suggesting the expression be
1932     /// wrapped in braces.
1933     pub fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
1934         let start = self.token.span;
1935         let expr = self.parse_expr_res(Restrictions::CONST_EXPR, None).map_err(|mut err| {
1936             err.span_label(
1937                 start.shrink_to_lo(),
1938                 "while parsing a const generic argument starting here",
1939             );
1940             err
1941         })?;
1942         if !self.expr_is_valid_const_arg(&expr) {
1943             self.struct_span_err(
1944                 expr.span,
1945                 "expressions must be enclosed in braces to be used as const generic \
1946                     arguments",
1947             )
1948             .multipart_suggestion(
1949                 "enclose the `const` expression in braces",
1950                 vec![
1951                     (expr.span.shrink_to_lo(), "{ ".to_string()),
1952                     (expr.span.shrink_to_hi(), " }".to_string()),
1953                 ],
1954                 Applicability::MachineApplicable,
1955             )
1956             .emit();
1957         }
1958         Ok(expr)
1959     }
1960
1961     fn recover_const_param_decl(&mut self, ty_generics: Option<&Generics>) -> Option<GenericArg> {
1962         let snapshot = self.clone();
1963         let param = match self.parse_const_param(vec![]) {
1964             Ok(param) => param,
1965             Err(err) => {
1966                 err.cancel();
1967                 *self = snapshot;
1968                 return None;
1969             }
1970         };
1971         let mut err =
1972             self.struct_span_err(param.span(), "unexpected `const` parameter declaration");
1973         err.span_label(param.span(), "expected a `const` expression, not a parameter declaration");
1974         if let (Some(generics), Ok(snippet)) =
1975             (ty_generics, self.sess.source_map().span_to_snippet(param.span()))
1976         {
1977             let (span, sugg) = match &generics.params[..] {
1978                 [] => (generics.span, format!("<{}>", snippet)),
1979                 [.., generic] => (generic.span().shrink_to_hi(), format!(", {}", snippet)),
1980             };
1981             err.multipart_suggestion(
1982                 "`const` parameters must be declared for the `impl`",
1983                 vec![(span, sugg), (param.span(), param.ident.to_string())],
1984                 Applicability::MachineApplicable,
1985             );
1986         }
1987         let value = self.mk_expr_err(param.span());
1988         err.emit();
1989         Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }))
1990     }
1991
1992     pub fn recover_const_param_declaration(
1993         &mut self,
1994         ty_generics: Option<&Generics>,
1995     ) -> PResult<'a, Option<GenericArg>> {
1996         // We have to check for a few different cases.
1997         if let Some(arg) = self.recover_const_param_decl(ty_generics) {
1998             return Ok(Some(arg));
1999         }
2000
2001         // We haven't consumed `const` yet.
2002         let start = self.token.span;
2003         self.bump(); // `const`
2004
2005         // Detect and recover from the old, pre-RFC2000 syntax for const generics.
2006         let mut err = self
2007             .struct_span_err(start, "expected lifetime, type, or constant, found keyword `const`");
2008         if self.check_const_arg() {
2009             err.span_suggestion_verbose(
2010                 start.until(self.token.span),
2011                 "the `const` keyword is only needed in the definition of the type",
2012                 String::new(),
2013                 Applicability::MaybeIncorrect,
2014             );
2015             err.emit();
2016             Ok(Some(GenericArg::Const(self.parse_const_arg()?)))
2017         } else {
2018             let after_kw_const = self.token.span;
2019             self.recover_const_arg(after_kw_const, err).map(Some)
2020         }
2021     }
2022
2023     /// Try to recover from possible generic const argument without `{` and `}`.
2024     ///
2025     /// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
2026     /// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
2027     /// if we think that that the resulting expression would be well formed.
2028     pub fn recover_const_arg(
2029         &mut self,
2030         start: Span,
2031         mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2032     ) -> PResult<'a, GenericArg> {
2033         let is_op_or_dot = AssocOp::from_token(&self.token)
2034             .and_then(|op| {
2035                 if let AssocOp::Greater
2036                 | AssocOp::Less
2037                 | AssocOp::ShiftRight
2038                 | AssocOp::GreaterEqual
2039                 // Don't recover from `foo::<bar = baz>`, because this could be an attempt to
2040                 // assign a value to a defaulted generic parameter.
2041                 | AssocOp::Assign
2042                 | AssocOp::AssignOp(_) = op
2043                 {
2044                     None
2045                 } else {
2046                     Some(op)
2047                 }
2048             })
2049             .is_some()
2050             || self.token.kind == TokenKind::Dot;
2051         // This will be true when a trait object type `Foo +` or a path which was a `const fn` with
2052         // type params has been parsed.
2053         let was_op =
2054             matches!(self.prev_token.kind, token::BinOp(token::Plus | token::Shr) | token::Gt);
2055         if !is_op_or_dot && !was_op {
2056             // We perform these checks and early return to avoid taking a snapshot unnecessarily.
2057             return Err(err);
2058         }
2059         let snapshot = self.clone();
2060         if is_op_or_dot {
2061             self.bump();
2062         }
2063         match self.parse_expr_res(Restrictions::CONST_EXPR, None) {
2064             Ok(expr) => {
2065                 // Find a mistake like `MyTrait<Assoc == S::Assoc>`.
2066                 if token::EqEq == snapshot.token.kind {
2067                     err.span_suggestion(
2068                         snapshot.token.span,
2069                         "if you meant to use an associated type binding, replace `==` with `=`",
2070                         "=".to_string(),
2071                         Applicability::MaybeIncorrect,
2072                     );
2073                     let value = self.mk_expr_err(start.to(expr.span));
2074                     err.emit();
2075                     return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
2076                 } else if token::Comma == self.token.kind || self.token.kind.should_end_const_arg()
2077                 {
2078                     // Avoid the following output by checking that we consumed a full const arg:
2079                     // help: expressions must be enclosed in braces to be used as const generic
2080                     //       arguments
2081                     //    |
2082                     // LL |     let sr: Vec<{ (u32, _, _) = vec![] };
2083                     //    |                 ^                      ^
2084                     return Ok(self.dummy_const_arg_needs_braces(err, start.to(expr.span)));
2085                 }
2086             }
2087             Err(err) => {
2088                 err.cancel();
2089             }
2090         }
2091         *self = snapshot;
2092         Err(err)
2093     }
2094
2095     /// Creates a dummy const argument, and reports that the expression must be enclosed in braces
2096     pub fn dummy_const_arg_needs_braces(
2097         &self,
2098         mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2099         span: Span,
2100     ) -> GenericArg {
2101         err.multipart_suggestion(
2102             "expressions must be enclosed in braces to be used as const generic \
2103              arguments",
2104             vec![(span.shrink_to_lo(), "{ ".to_string()), (span.shrink_to_hi(), " }".to_string())],
2105             Applicability::MaybeIncorrect,
2106         );
2107         let value = self.mk_expr_err(span);
2108         err.emit();
2109         GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })
2110     }
2111
2112     /// Get the diagnostics for the cases where `move async` is found.
2113     ///
2114     /// `move_async_span` starts at the 'm' of the move keyword and ends with the 'c' of the async keyword
2115     pub(super) fn incorrect_move_async_order_found(
2116         &self,
2117         move_async_span: Span,
2118     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2119         let mut err =
2120             self.struct_span_err(move_async_span, "the order of `move` and `async` is incorrect");
2121         err.span_suggestion_verbose(
2122             move_async_span,
2123             "try switching the order",
2124             "async move".to_owned(),
2125             Applicability::MaybeIncorrect,
2126         );
2127         err
2128     }
2129
2130     /// Some special error handling for the "top-level" patterns in a match arm,
2131     /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2132     crate fn maybe_recover_colon_colon_in_pat_typo(
2133         &mut self,
2134         mut first_pat: P<Pat>,
2135         ra: RecoverColon,
2136         expected: Expected,
2137     ) -> P<Pat> {
2138         if RecoverColon::Yes != ra || token::Colon != self.token.kind {
2139             return first_pat;
2140         }
2141         if !matches!(first_pat.kind, PatKind::Ident(_, _, None) | PatKind::Path(..))
2142             || !self.look_ahead(1, |token| token.is_ident() && !token.is_reserved_ident())
2143         {
2144             return first_pat;
2145         }
2146         // The pattern looks like it might be a path with a `::` -> `:` typo:
2147         // `match foo { bar:baz => {} }`
2148         let span = self.token.span;
2149         // We only emit "unexpected `:`" error here if we can successfully parse the
2150         // whole pattern correctly in that case.
2151         let snapshot = self.clone();
2152
2153         // Create error for "unexpected `:`".
2154         match self.expected_one_of_not_found(&[], &[]) {
2155             Err(mut err) => {
2156                 self.bump(); // Skip the `:`.
2157                 match self.parse_pat_no_top_alt(expected) {
2158                     Err(inner_err) => {
2159                         // Carry on as if we had not done anything, callers will emit a
2160                         // reasonable error.
2161                         inner_err.cancel();
2162                         err.cancel();
2163                         *self = snapshot;
2164                     }
2165                     Ok(mut pat) => {
2166                         // We've parsed the rest of the pattern.
2167                         let new_span = first_pat.span.to(pat.span);
2168                         let mut show_sugg = false;
2169                         // Try to construct a recovered pattern.
2170                         match &mut pat.kind {
2171                             PatKind::Struct(qself @ None, path, ..)
2172                             | PatKind::TupleStruct(qself @ None, path, _)
2173                             | PatKind::Path(qself @ None, path) => match &first_pat.kind {
2174                                 PatKind::Ident(_, ident, _) => {
2175                                     path.segments.insert(0, PathSegment::from_ident(*ident));
2176                                     path.span = new_span;
2177                                     show_sugg = true;
2178                                     first_pat = pat;
2179                                 }
2180                                 PatKind::Path(old_qself, old_path) => {
2181                                     path.segments = old_path
2182                                         .segments
2183                                         .iter()
2184                                         .cloned()
2185                                         .chain(take(&mut path.segments))
2186                                         .collect();
2187                                     path.span = new_span;
2188                                     *qself = old_qself.clone();
2189                                     first_pat = pat;
2190                                     show_sugg = true;
2191                                 }
2192                                 _ => {}
2193                             },
2194                             PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
2195                                 match &first_pat.kind {
2196                                     PatKind::Ident(_, old_ident, _) => {
2197                                         let path = PatKind::Path(
2198                                             None,
2199                                             Path {
2200                                                 span: new_span,
2201                                                 segments: vec![
2202                                                     PathSegment::from_ident(*old_ident),
2203                                                     PathSegment::from_ident(*ident),
2204                                                 ],
2205                                                 tokens: None,
2206                                             },
2207                                         );
2208                                         first_pat = self.mk_pat(new_span, path);
2209                                         show_sugg = true;
2210                                     }
2211                                     PatKind::Path(old_qself, old_path) => {
2212                                         let mut segments = old_path.segments.clone();
2213                                         segments.push(PathSegment::from_ident(*ident));
2214                                         let path = PatKind::Path(
2215                                             old_qself.clone(),
2216                                             Path { span: new_span, segments, tokens: None },
2217                                         );
2218                                         first_pat = self.mk_pat(new_span, path);
2219                                         show_sugg = true;
2220                                     }
2221                                     _ => {}
2222                                 }
2223                             }
2224                             _ => {}
2225                         }
2226                         if show_sugg {
2227                             err.span_suggestion(
2228                                 span,
2229                                 "maybe write a path separator here",
2230                                 "::".to_string(),
2231                                 Applicability::MaybeIncorrect,
2232                             );
2233                         } else {
2234                             first_pat = self.mk_pat(new_span, PatKind::Wild);
2235                         }
2236                         err.emit();
2237                     }
2238                 }
2239             }
2240             _ => {
2241                 // Carry on as if we had not done anything. This should be unreachable.
2242                 *self = snapshot;
2243             }
2244         };
2245         first_pat
2246     }
2247
2248     crate fn maybe_recover_unexpected_block_label(&mut self) -> bool {
2249         let Some(label) = self.eat_label().filter(|_| {
2250             self.eat(&token::Colon) && self.token.kind == token::OpenDelim(token::Brace)
2251         }) else {
2252             return false;
2253         };
2254         let span = label.ident.span.to(self.prev_token.span);
2255         let mut err = self.struct_span_err(span, "block label not supported here");
2256         err.span_label(span, "not supported here");
2257         err.tool_only_span_suggestion(
2258             label.ident.span.until(self.token.span),
2259             "remove this block label",
2260             String::new(),
2261             Applicability::MachineApplicable,
2262         );
2263         err.emit();
2264         true
2265     }
2266
2267     /// Some special error handling for the "top-level" patterns in a match arm,
2268     /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2269     crate fn maybe_recover_unexpected_comma(
2270         &mut self,
2271         lo: Span,
2272         rc: RecoverComma,
2273         rt: CommaRecoveryMode,
2274     ) -> PResult<'a, ()> {
2275         if rc == RecoverComma::No || self.token != token::Comma {
2276             return Ok(());
2277         }
2278
2279         // An unexpected comma after a top-level pattern is a clue that the
2280         // user (perhaps more accustomed to some other language) forgot the
2281         // parentheses in what should have been a tuple pattern; return a
2282         // suggestion-enhanced error here rather than choking on the comma later.
2283         let comma_span = self.token.span;
2284         self.bump();
2285         if let Err(err) = self.skip_pat_list() {
2286             // We didn't expect this to work anyway; we just wanted to advance to the
2287             // end of the comma-sequence so we know the span to suggest parenthesizing.
2288             err.cancel();
2289         }
2290         let seq_span = lo.to(self.prev_token.span);
2291         let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
2292         if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
2293             err.multipart_suggestion(
2294                 &format!(
2295                     "try adding parentheses to match on a tuple{}",
2296                     if let CommaRecoveryMode::LikelyTuple = rt { "" } else { "..." },
2297                 ),
2298                 vec![
2299                     (seq_span.shrink_to_lo(), "(".to_string()),
2300                     (seq_span.shrink_to_hi(), ")".to_string()),
2301                 ],
2302                 Applicability::MachineApplicable,
2303             );
2304             if let CommaRecoveryMode::EitherTupleOrPipe = rt {
2305                 err.span_suggestion(
2306                     seq_span,
2307                     "...or a vertical bar to match on multiple alternatives",
2308                     seq_snippet.replace(',', " |"),
2309                     Applicability::MachineApplicable,
2310                 );
2311             }
2312         }
2313         Err(err)
2314     }
2315
2316     /// Parse and throw away a parenthesized comma separated
2317     /// sequence of patterns until `)` is reached.
2318     fn skip_pat_list(&mut self) -> PResult<'a, ()> {
2319         while !self.check(&token::CloseDelim(token::Paren)) {
2320             self.parse_pat_no_top_alt(None)?;
2321             if !self.eat(&token::Comma) {
2322                 return Ok(());
2323             }
2324         }
2325         Ok(())
2326     }
2327 }