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