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