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