]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/diagnostics.rs
Point at unclosed delimiters as part of the primary MultiSpan
[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                     let mut primary_span: Vec<Span> =
1442                         err.span.primary_spans().iter().cloned().collect();
1443                     primary_span.push(sp);
1444                     let mut primary_span: MultiSpan = primary_span.into();
1445                     for span_label in err.span.span_labels() {
1446                         if let Some(label) = span_label.label {
1447                             primary_span.push_span_label(span_label.span, label);
1448                         }
1449                     }
1450                     err.set_span(primary_span);
1451                     err.span_label(sp, "unclosed delimiter");
1452                 }
1453                 // Backticks should be removed to apply suggestions.
1454                 let mut delim = delim.to_string();
1455                 delim.retain(|c| c != '`');
1456                 err.span_suggestion_short(
1457                     self.prev_token.span.shrink_to_hi(),
1458                     &format!("`{}` may belong here", delim),
1459                     delim,
1460                     Applicability::MaybeIncorrect,
1461                 );
1462                 if unmatched.found_delim.is_none() {
1463                     // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1464                     // errors which would be emitted elsewhere in the parser and let other error
1465                     // recovery consume the rest of the file.
1466                     Err(err)
1467                 } else {
1468                     err.emit();
1469                     self.expected_tokens.clear(); // Reduce the number of errors.
1470                     Ok(true)
1471                 }
1472             }
1473             _ => Err(err),
1474         }
1475     }
1476
1477     /// Eats tokens until we can be relatively sure we reached the end of the
1478     /// statement. This is something of a best-effort heuristic.
1479     ///
1480     /// We terminate when we find an unmatched `}` (without consuming it).
1481     pub(super) fn recover_stmt(&mut self) {
1482         self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1483     }
1484
1485     /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1486     /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1487     /// approximate -- it can mean we break too early due to macros, but that
1488     /// should only lead to sub-optimal recovery, not inaccurate parsing).
1489     ///
1490     /// If `break_on_block` is `Break`, then we will stop consuming tokens
1491     /// after finding (and consuming) a brace-delimited block.
1492     pub(super) fn recover_stmt_(
1493         &mut self,
1494         break_on_semi: SemiColonMode,
1495         break_on_block: BlockMode,
1496     ) {
1497         let mut brace_depth = 0;
1498         let mut bracket_depth = 0;
1499         let mut in_block = false;
1500         debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1501         loop {
1502             debug!("recover_stmt_ loop {:?}", self.token);
1503             match self.token.kind {
1504                 token::OpenDelim(token::DelimToken::Brace) => {
1505                     brace_depth += 1;
1506                     self.bump();
1507                     if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1508                     {
1509                         in_block = true;
1510                     }
1511                 }
1512                 token::OpenDelim(token::DelimToken::Bracket) => {
1513                     bracket_depth += 1;
1514                     self.bump();
1515                 }
1516                 token::CloseDelim(token::DelimToken::Brace) => {
1517                     if brace_depth == 0 {
1518                         debug!("recover_stmt_ return - close delim {:?}", self.token);
1519                         break;
1520                     }
1521                     brace_depth -= 1;
1522                     self.bump();
1523                     if in_block && bracket_depth == 0 && brace_depth == 0 {
1524                         debug!("recover_stmt_ return - block end {:?}", self.token);
1525                         break;
1526                     }
1527                 }
1528                 token::CloseDelim(token::DelimToken::Bracket) => {
1529                     bracket_depth -= 1;
1530                     if bracket_depth < 0 {
1531                         bracket_depth = 0;
1532                     }
1533                     self.bump();
1534                 }
1535                 token::Eof => {
1536                     debug!("recover_stmt_ return - Eof");
1537                     break;
1538                 }
1539                 token::Semi => {
1540                     self.bump();
1541                     if break_on_semi == SemiColonMode::Break
1542                         && brace_depth == 0
1543                         && bracket_depth == 0
1544                     {
1545                         debug!("recover_stmt_ return - Semi");
1546                         break;
1547                     }
1548                 }
1549                 token::Comma
1550                     if break_on_semi == SemiColonMode::Comma
1551                         && brace_depth == 0
1552                         && bracket_depth == 0 =>
1553                 {
1554                     debug!("recover_stmt_ return - Semi");
1555                     break;
1556                 }
1557                 _ => self.bump(),
1558             }
1559         }
1560     }
1561
1562     pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1563         if self.eat_keyword(kw::In) {
1564             // a common typo: `for _ in in bar {}`
1565             self.struct_span_err(self.prev_token.span, "expected iterable, found keyword `in`")
1566                 .span_suggestion_short(
1567                     in_span.until(self.prev_token.span),
1568                     "remove the duplicated `in`",
1569                     String::new(),
1570                     Applicability::MachineApplicable,
1571                 )
1572                 .emit();
1573         }
1574     }
1575
1576     pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1577         if let token::DocComment(..) = self.token.kind {
1578             self.struct_span_err(
1579                 self.token.span,
1580                 "documentation comments cannot be applied to a function parameter's type",
1581             )
1582             .span_label(self.token.span, "doc comments are not allowed here")
1583             .emit();
1584             self.bump();
1585         } else if self.token == token::Pound
1586             && self.look_ahead(1, |t| *t == token::OpenDelim(token::Bracket))
1587         {
1588             let lo = self.token.span;
1589             // Skip every token until next possible arg.
1590             while self.token != token::CloseDelim(token::Bracket) {
1591                 self.bump();
1592             }
1593             let sp = lo.to(self.token.span);
1594             self.bump();
1595             self.struct_span_err(sp, "attributes cannot be applied to a function parameter's type")
1596                 .span_label(sp, "attributes are not allowed here")
1597                 .emit();
1598         }
1599     }
1600
1601     pub(super) fn parameter_without_type(
1602         &mut self,
1603         err: &mut DiagnosticBuilder<'_>,
1604         pat: P<ast::Pat>,
1605         require_name: bool,
1606         first_param: bool,
1607     ) -> Option<Ident> {
1608         // If we find a pattern followed by an identifier, it could be an (incorrect)
1609         // C-style parameter declaration.
1610         if self.check_ident()
1611             && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseDelim(token::Paren))
1612         {
1613             // `fn foo(String s) {}`
1614             let ident = self.parse_ident().unwrap();
1615             let span = pat.span.with_hi(ident.span.hi());
1616
1617             err.span_suggestion(
1618                 span,
1619                 "declare the type after the parameter binding",
1620                 String::from("<identifier>: <type>"),
1621                 Applicability::HasPlaceholders,
1622             );
1623             return Some(ident);
1624         } else if require_name
1625             && (self.token == token::Comma
1626                 || self.token == token::Lt
1627                 || self.token == token::CloseDelim(token::Paren))
1628         {
1629             let rfc_note = "anonymous parameters are removed in the 2018 edition (see RFC 1685)";
1630
1631             let (ident, self_sugg, param_sugg, type_sugg) = match pat.kind {
1632                 PatKind::Ident(_, ident, _) => (
1633                     ident,
1634                     format!("self: {}", ident),
1635                     format!("{}: TypeName", ident),
1636                     format!("_: {}", ident),
1637                 ),
1638                 // Also catches `fn foo(&a)`.
1639                 PatKind::Ref(ref pat, mutab)
1640                     if matches!(pat.clone().into_inner().kind, PatKind::Ident(..)) =>
1641                 {
1642                     match pat.clone().into_inner().kind {
1643                         PatKind::Ident(_, ident, _) => {
1644                             let mutab = mutab.prefix_str();
1645                             (
1646                                 ident,
1647                                 format!("self: &{}{}", mutab, ident),
1648                                 format!("{}: &{}TypeName", ident, mutab),
1649                                 format!("_: &{}{}", mutab, ident),
1650                             )
1651                         }
1652                         _ => unreachable!(),
1653                     }
1654                 }
1655                 _ => {
1656                     // Otherwise, try to get a type and emit a suggestion.
1657                     if let Some(ty) = pat.to_ty() {
1658                         err.span_suggestion_verbose(
1659                             pat.span,
1660                             "explicitly ignore the parameter name",
1661                             format!("_: {}", pprust::ty_to_string(&ty)),
1662                             Applicability::MachineApplicable,
1663                         );
1664                         err.note(rfc_note);
1665                     }
1666
1667                     return None;
1668                 }
1669             };
1670
1671             // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1672             if first_param {
1673                 err.span_suggestion(
1674                     pat.span,
1675                     "if this is a `self` type, give it a parameter name",
1676                     self_sugg,
1677                     Applicability::MaybeIncorrect,
1678                 );
1679             }
1680             // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
1681             // `fn foo(HashMap: TypeName<u32>)`.
1682             if self.token != token::Lt {
1683                 err.span_suggestion(
1684                     pat.span,
1685                     "if this is a parameter name, give it a type",
1686                     param_sugg,
1687                     Applicability::HasPlaceholders,
1688                 );
1689             }
1690             err.span_suggestion(
1691                 pat.span,
1692                 "if this is a type, explicitly ignore the parameter name",
1693                 type_sugg,
1694                 Applicability::MachineApplicable,
1695             );
1696             err.note(rfc_note);
1697
1698             // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
1699             return if self.token == token::Lt { None } else { Some(ident) };
1700         }
1701         None
1702     }
1703
1704     pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
1705         let pat = self.parse_pat_no_top_alt(Some("argument name"))?;
1706         self.expect(&token::Colon)?;
1707         let ty = self.parse_ty()?;
1708
1709         struct_span_err!(
1710             self.diagnostic(),
1711             pat.span,
1712             E0642,
1713             "patterns aren't allowed in methods without bodies",
1714         )
1715         .span_suggestion_short(
1716             pat.span,
1717             "give this argument a name or use an underscore to ignore it",
1718             "_".to_owned(),
1719             Applicability::MachineApplicable,
1720         )
1721         .emit();
1722
1723         // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1724         let pat =
1725             P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID, tokens: None });
1726         Ok((pat, ty))
1727     }
1728
1729     pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
1730         let sp = param.pat.span;
1731         param.ty.kind = TyKind::Err;
1732         self.struct_span_err(sp, "unexpected `self` parameter in function")
1733             .span_label(sp, "must be the first parameter of an associated function")
1734             .emit();
1735         Ok(param)
1736     }
1737
1738     pub(super) fn consume_block(
1739         &mut self,
1740         delim: token::DelimToken,
1741         consume_close: ConsumeClosingDelim,
1742     ) {
1743         let mut brace_depth = 0;
1744         loop {
1745             if self.eat(&token::OpenDelim(delim)) {
1746                 brace_depth += 1;
1747             } else if self.check(&token::CloseDelim(delim)) {
1748                 if brace_depth == 0 {
1749                     if let ConsumeClosingDelim::Yes = consume_close {
1750                         // Some of the callers of this method expect to be able to parse the
1751                         // closing delimiter themselves, so we leave it alone. Otherwise we advance
1752                         // the parser.
1753                         self.bump();
1754                     }
1755                     return;
1756                 } else {
1757                     self.bump();
1758                     brace_depth -= 1;
1759                     continue;
1760                 }
1761             } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
1762                 return;
1763             } else {
1764                 self.bump();
1765             }
1766         }
1767     }
1768
1769     pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a> {
1770         let (span, msg) = match (&self.token.kind, self.subparser_name) {
1771             (&token::Eof, Some(origin)) => {
1772                 let sp = self.sess.source_map().next_point(self.prev_token.span);
1773                 (sp, format!("expected expression, found end of {}", origin))
1774             }
1775             _ => (
1776                 self.token.span,
1777                 format!("expected expression, found {}", super::token_descr(&self.token),),
1778             ),
1779         };
1780         let mut err = self.struct_span_err(span, &msg);
1781         let sp = self.sess.source_map().start_point(self.token.span);
1782         if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
1783             self.sess.expr_parentheses_needed(&mut err, *sp);
1784         }
1785         err.span_label(span, "expected expression");
1786         err
1787     }
1788
1789     fn consume_tts(
1790         &mut self,
1791         mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
1792         // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
1793         modifier: &[(token::TokenKind, i64)],
1794     ) {
1795         while acc > 0 {
1796             if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
1797                 acc += *val;
1798             }
1799             if self.token.kind == token::Eof {
1800                 break;
1801             }
1802             self.bump();
1803         }
1804     }
1805
1806     /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
1807     ///
1808     /// This is necessary because at this point we don't know whether we parsed a function with
1809     /// anonymous parameters or a function with names but no types. In order to minimize
1810     /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
1811     /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
1812     /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
1813     /// we deduplicate them to not complain about duplicated parameter names.
1814     pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
1815         let mut seen_inputs = FxHashSet::default();
1816         for input in fn_inputs.iter_mut() {
1817             let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
1818                 (&input.pat.kind, &input.ty.kind)
1819             {
1820                 Some(*ident)
1821             } else {
1822                 None
1823             };
1824             if let Some(ident) = opt_ident {
1825                 if seen_inputs.contains(&ident) {
1826                     input.pat.kind = PatKind::Wild;
1827                 }
1828                 seen_inputs.insert(ident);
1829             }
1830         }
1831     }
1832
1833     /// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
1834     /// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
1835     /// like the user has forgotten them.
1836     pub fn handle_ambiguous_unbraced_const_arg(
1837         &mut self,
1838         args: &mut Vec<AngleBracketedArg>,
1839     ) -> PResult<'a, bool> {
1840         // If we haven't encountered a closing `>`, then the argument is malformed.
1841         // It's likely that the user has written a const expression without enclosing it
1842         // in braces, so we try to recover here.
1843         let arg = args.pop().unwrap();
1844         // FIXME: for some reason using `unexpected` or `expected_one_of_not_found` has
1845         // adverse side-effects to subsequent errors and seems to advance the parser.
1846         // We are causing this error here exclusively in case that a `const` expression
1847         // could be recovered from the current parser state, even if followed by more
1848         // arguments after a comma.
1849         let mut err = self.struct_span_err(
1850             self.token.span,
1851             &format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
1852         );
1853         err.span_label(self.token.span, "expected one of `,` or `>`");
1854         match self.recover_const_arg(arg.span(), err) {
1855             Ok(arg) => {
1856                 args.push(AngleBracketedArg::Arg(arg));
1857                 if self.eat(&token::Comma) {
1858                     return Ok(true); // Continue
1859                 }
1860             }
1861             Err(mut err) => {
1862                 args.push(arg);
1863                 // We will emit a more generic error later.
1864                 err.delay_as_bug();
1865             }
1866         }
1867         return Ok(false); // Don't continue.
1868     }
1869
1870     /// Attempt to parse a generic const argument that has not been enclosed in braces.
1871     /// There are a limited number of expressions that are permitted without being encoded
1872     /// in braces:
1873     /// - Literals.
1874     /// - Single-segment paths (i.e. standalone generic const parameters).
1875     /// All other expressions that can be parsed will emit an error suggesting the expression be
1876     /// wrapped in braces.
1877     pub fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
1878         let start = self.token.span;
1879         let expr = self.parse_expr_res(Restrictions::CONST_EXPR, None).map_err(|mut err| {
1880             err.span_label(
1881                 start.shrink_to_lo(),
1882                 "while parsing a const generic argument starting here",
1883             );
1884             err
1885         })?;
1886         if !self.expr_is_valid_const_arg(&expr) {
1887             self.struct_span_err(
1888                 expr.span,
1889                 "expressions must be enclosed in braces to be used as const generic \
1890                     arguments",
1891             )
1892             .multipart_suggestion(
1893                 "enclose the `const` expression in braces",
1894                 vec![
1895                     (expr.span.shrink_to_lo(), "{ ".to_string()),
1896                     (expr.span.shrink_to_hi(), " }".to_string()),
1897                 ],
1898                 Applicability::MachineApplicable,
1899             )
1900             .emit();
1901         }
1902         Ok(expr)
1903     }
1904
1905     /// Try to recover from possible generic const argument without `{` and `}`.
1906     ///
1907     /// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
1908     /// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
1909     /// if we think that that the resulting expression would be well formed.
1910     pub fn recover_const_arg(
1911         &mut self,
1912         start: Span,
1913         mut err: DiagnosticBuilder<'a>,
1914     ) -> PResult<'a, GenericArg> {
1915         let is_op = AssocOp::from_token(&self.token)
1916             .and_then(|op| {
1917                 if let AssocOp::Greater
1918                 | AssocOp::Less
1919                 | AssocOp::ShiftRight
1920                 | AssocOp::GreaterEqual
1921                 // Don't recover from `foo::<bar = baz>`, because this could be an attempt to
1922                 // assign a value to a defaulted generic parameter.
1923                 | AssocOp::Assign
1924                 | AssocOp::AssignOp(_) = op
1925                 {
1926                     None
1927                 } else {
1928                     Some(op)
1929                 }
1930             })
1931             .is_some();
1932         // This will be true when a trait object type `Foo +` or a path which was a `const fn` with
1933         // type params has been parsed.
1934         let was_op =
1935             matches!(self.prev_token.kind, token::BinOp(token::Plus | token::Shr) | token::Gt);
1936         if !is_op && !was_op {
1937             // We perform these checks and early return to avoid taking a snapshot unnecessarily.
1938             return Err(err);
1939         }
1940         let snapshot = self.clone();
1941         if is_op {
1942             self.bump();
1943         }
1944         match self.parse_expr_res(Restrictions::CONST_EXPR, None) {
1945             Ok(expr) => {
1946                 if token::Comma == self.token.kind || self.token.kind.should_end_const_arg() {
1947                     // Avoid the following output by checking that we consumed a full const arg:
1948                     // help: expressions must be enclosed in braces to be used as const generic
1949                     //       arguments
1950                     //    |
1951                     // LL |     let sr: Vec<{ (u32, _, _) = vec![] };
1952                     //    |                 ^                      ^
1953                     err.multipart_suggestion(
1954                         "expressions must be enclosed in braces to be used as const generic \
1955                          arguments",
1956                         vec![
1957                             (start.shrink_to_lo(), "{ ".to_string()),
1958                             (expr.span.shrink_to_hi(), " }".to_string()),
1959                         ],
1960                         Applicability::MaybeIncorrect,
1961                     );
1962                     let value = self.mk_expr_err(start.to(expr.span));
1963                     err.emit();
1964                     return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
1965                 }
1966             }
1967             Err(mut err) => {
1968                 err.cancel();
1969             }
1970         }
1971         *self = snapshot;
1972         Err(err)
1973     }
1974
1975     /// Get the diagnostics for the cases where `move async` is found.
1976     ///
1977     /// `move_async_span` starts at the 'm' of the move keyword and ends with the 'c' of the async keyword
1978     pub(super) fn incorrect_move_async_order_found(
1979         &self,
1980         move_async_span: Span,
1981     ) -> DiagnosticBuilder<'a> {
1982         let mut err =
1983             self.struct_span_err(move_async_span, "the order of `move` and `async` is incorrect");
1984         err.span_suggestion_verbose(
1985             move_async_span,
1986             "try switching the order",
1987             "async move".to_owned(),
1988             Applicability::MaybeIncorrect,
1989         );
1990         err
1991     }
1992 }