1 use super::pat::Expected;
3 BlockMode, CommaRecoveryMode, Parser, PathStyle, Restrictions, SemiColonMode, SeqSep,
4 TokenExpectType, TokenType,
7 AmbiguousPlus, AttributeOnParamType, BadQPathStage2, BadTypePlus, BadTypePlusSub,
8 ComparisonOperatorsCannotBeChained, ComparisonOperatorsCannotBeChainedSugg,
9 ConstGenericWithoutBraces, ConstGenericWithoutBracesSugg, DocCommentOnParamType,
10 DoubleColonInBound, ExpectedIdentifier, ExpectedSemi, ExpectedSemiSugg,
11 GenericParamsWithoutAngleBrackets, GenericParamsWithoutAngleBracketsSugg, InInTypo,
12 IncorrectAwait, IncorrectSemicolon, IncorrectUseOfAwait, ParenthesesInForHead,
13 ParenthesesInForHeadSugg, PatternMethodParamWithoutBody, QuestionMarkInType,
14 QuestionMarkInTypeSugg, SelfParamNotFirst, StructLiteralBodyWithoutPath,
15 StructLiteralBodyWithoutPathSugg, SuggEscapeToUseAsIdentifier, SuggRemoveComma,
16 UnexpectedConstInGenericParam, UnexpectedConstParamDeclaration,
17 UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets, UseEqInstead,
20 use crate::lexer::UnmatchedBrace;
23 use rustc_ast::ptr::P;
24 use rustc_ast::token::{self, Delimiter, Lit, LitKind, TokenKind};
25 use rustc_ast::util::parser::AssocOp;
27 AngleBracketedArg, AngleBracketedArgs, AnonConst, AttrVec, BinOpKind, BindingAnnotation, Block,
28 BlockCheckMode, Expr, ExprKind, GenericArg, Generics, Item, ItemKind, Param, Pat, PatKind,
29 Path, PathSegment, QSelf, Ty, TyKind,
31 use rustc_ast_pretty::pprust;
32 use rustc_data_structures::fx::FxHashSet;
34 fluent, Applicability, DiagnosticBuilder, DiagnosticMessage, FatalError, Handler, MultiSpan,
37 use rustc_errors::{pluralize, Diagnostic, ErrorGuaranteed, IntoDiagnostic};
38 use rustc_session::errors::ExprParenthesesNeeded;
39 use rustc_span::source_map::Spanned;
40 use rustc_span::symbol::{kw, sym, Ident};
41 use rustc_span::{Span, SpanSnippetError, DUMMY_SP};
43 use std::ops::{Deref, DerefMut};
44 use thin_vec::{thin_vec, ThinVec};
46 /// Creates a placeholder argument.
47 pub(super) fn dummy_arg(ident: Ident) -> Param {
49 id: ast::DUMMY_NODE_ID,
50 kind: PatKind::Ident(BindingAnnotation::NONE, ident, None),
54 let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID, tokens: None };
56 attrs: AttrVec::default(),
57 id: ast::DUMMY_NODE_ID,
61 is_placeholder: false,
65 pub(super) trait RecoverQPath: Sized + 'static {
66 const PATH_STYLE: PathStyle = PathStyle::Expr;
67 fn to_ty(&self) -> Option<P<Ty>>;
68 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self;
71 impl RecoverQPath for Ty {
72 const PATH_STYLE: PathStyle = PathStyle::Type;
73 fn to_ty(&self) -> Option<P<Ty>> {
76 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
79 kind: TyKind::Path(qself, path),
80 id: ast::DUMMY_NODE_ID,
86 impl RecoverQPath for Pat {
87 fn to_ty(&self) -> Option<P<Ty>> {
90 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
93 kind: PatKind::Path(qself, path),
94 id: ast::DUMMY_NODE_ID,
100 impl RecoverQPath for Expr {
101 fn to_ty(&self) -> Option<P<Ty>> {
104 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
107 kind: ExprKind::Path(qself, path),
108 attrs: AttrVec::new(),
109 id: ast::DUMMY_NODE_ID,
115 /// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
116 pub(crate) enum ConsumeClosingDelim {
121 #[derive(Clone, Copy)]
122 pub enum AttemptLocalParseRecovery {
127 impl AttemptLocalParseRecovery {
128 pub fn yes(&self) -> bool {
130 AttemptLocalParseRecovery::Yes => true,
131 AttemptLocalParseRecovery::No => false,
135 pub fn no(&self) -> bool {
137 AttemptLocalParseRecovery::Yes => false,
138 AttemptLocalParseRecovery::No => true,
143 /// Information for emitting suggestions and recovering from
144 /// C-style `i++`, `--i`, etc.
145 #[derive(Debug, Copy, Clone)]
146 struct IncDecRecovery {
147 /// Is this increment/decrement its own statement?
148 standalone: IsStandalone,
149 /// Is this an increment or decrement?
151 /// Is this pre- or postfix?
155 /// Is an increment or decrement expression its own statement?
156 #[derive(Debug, Copy, Clone)]
158 /// It's standalone, i.e., its own statement.
160 /// It's a subexpression, i.e., *not* standalone.
164 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
167 // FIXME: `i--` recovery isn't implemented yet
172 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
179 fn chr(&self) -> char {
186 fn name(&self) -> &'static str {
188 Self::Inc => "increment",
189 Self::Dec => "decrement",
194 impl std::fmt::Display for UnaryFixity {
195 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197 Self::Pre => write!(f, "prefix"),
198 Self::Post => write!(f, "postfix"),
205 patches: Vec<(Span, String)>,
206 applicability: Applicability,
210 fn emit(self, err: &mut Diagnostic) {
211 err.multipart_suggestion(&self.msg, self.patches, self.applicability);
214 fn emit_verbose(self, err: &mut Diagnostic) {
215 err.multipart_suggestion_verbose(&self.msg, self.patches, self.applicability);
219 /// SnapshotParser is used to create a snapshot of the parser
220 /// without causing duplicate errors being emitted when the `Parser`
222 pub struct SnapshotParser<'a> {
224 unclosed_delims: Vec<UnmatchedBrace>,
227 impl<'a> Deref for SnapshotParser<'a> {
228 type Target = Parser<'a>;
230 fn deref(&self) -> &Self::Target {
235 impl<'a> DerefMut for SnapshotParser<'a> {
236 fn deref_mut(&mut self) -> &mut Self::Target {
241 impl<'a> Parser<'a> {
242 #[rustc_lint_diagnostics]
243 pub fn struct_span_err<S: Into<MultiSpan>>(
246 m: impl Into<DiagnosticMessage>,
247 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
248 self.sess.span_diagnostic.struct_span_err(sp, m)
251 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: impl Into<DiagnosticMessage>) -> ! {
252 self.sess.span_diagnostic.span_bug(sp, m)
255 pub(super) fn diagnostic(&self) -> &'a Handler {
256 &self.sess.span_diagnostic
259 /// Replace `self` with `snapshot.parser` and extend `unclosed_delims` with `snapshot.unclosed_delims`.
260 /// This is to avoid losing unclosed delims errors `create_snapshot_for_diagnostic` clears.
261 pub(super) fn restore_snapshot(&mut self, snapshot: SnapshotParser<'a>) {
262 *self = snapshot.parser;
263 self.unclosed_delims.extend(snapshot.unclosed_delims);
266 pub fn unclosed_delims(&self) -> &[UnmatchedBrace] {
267 &self.unclosed_delims
270 /// Create a snapshot of the `Parser`.
271 pub fn create_snapshot_for_diagnostic(&self) -> SnapshotParser<'a> {
272 let mut snapshot = self.clone();
273 let unclosed_delims = self.unclosed_delims.clone();
274 // Clear `unclosed_delims` in snapshot to avoid
275 // duplicate errors being emitted when the `Parser`
276 // is dropped (which may or may not happen, depending
277 // if the parsing the snapshot is created for is successful)
278 snapshot.unclosed_delims.clear();
279 SnapshotParser { parser: snapshot, unclosed_delims }
282 pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
283 self.sess.source_map().span_to_snippet(span)
286 pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
287 let valid_follow = &[
293 TokenKind::OpenDelim(Delimiter::Brace),
294 TokenKind::OpenDelim(Delimiter::Parenthesis),
295 TokenKind::CloseDelim(Delimiter::Brace),
296 TokenKind::CloseDelim(Delimiter::Parenthesis),
298 let suggest_raw = match self.token.ident() {
300 if ident.is_raw_guess()
301 && self.look_ahead(1, |t| valid_follow.contains(&t.kind)) =>
303 Some(SuggEscapeToUseAsIdentifier {
304 span: ident.span.shrink_to_lo(),
305 // `Symbol::to_string()` is different from `Symbol::into_diagnostic_arg()`,
306 // which uses `Symbol::to_ident_string()` and "helpfully" adds an implicit `r#`
307 ident_name: ident.name.to_string(),
313 let suggest_remove_comma =
314 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
315 Some(SuggRemoveComma { span: self.token.span })
320 let err = ExpectedIdentifier {
321 span: self.token.span,
322 token: self.token.clone(),
324 suggest_remove_comma,
326 err.into_diagnostic(&self.sess.span_diagnostic)
329 pub(super) fn expected_one_of_not_found(
331 edible: &[TokenKind],
332 inedible: &[TokenKind],
333 ) -> PResult<'a, bool /* recovered */> {
334 debug!("expected_one_of_not_found(edible: {:?}, inedible: {:?})", edible, inedible);
335 fn tokens_to_string(tokens: &[TokenType]) -> String {
336 let mut i = tokens.iter();
337 // This might be a sign we need a connect method on `Iterator`.
338 let b = i.next().map_or_else(String::new, |t| t.to_string());
339 i.enumerate().fold(b, |mut b, (i, a)| {
340 if tokens.len() > 2 && i == tokens.len() - 2 {
342 } else if tokens.len() == 2 && i == tokens.len() - 2 {
347 b.push_str(&a.to_string());
352 let mut expected = edible
354 .map(|x| TokenType::Token(x.clone()))
355 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
356 .chain(self.expected_tokens.iter().cloned())
357 .filter_map(|token| {
358 // filter out suggestions which suggest the same token which was found and deemed incorrect
359 fn is_ident_eq_keyword(found: &TokenKind, expected: &TokenType) -> bool {
360 if let TokenKind::Ident(current_sym, _) = found {
361 if let TokenType::Keyword(suggested_sym) = expected {
362 return current_sym == suggested_sym;
367 if token != parser::TokenType::Token(self.token.kind.clone()) {
368 let eq = is_ident_eq_keyword(&self.token.kind, &token);
369 // if the suggestion is a keyword and the found token is an ident,
370 // the content of which are equal to the suggestion's content,
371 // we can remove that suggestion (see the return None statement below)
373 // if this isn't the case however, and the suggestion is a token the
374 // content of which is the same as the found token's, we remove it as well
376 if let TokenType::Token(kind) = &token {
377 if kind == &self.token.kind {
386 .collect::<Vec<_>>();
387 expected.sort_by_cached_key(|x| x.to_string());
390 let sm = self.sess.source_map();
392 // Special-case "expected `;`" errors
393 if expected.contains(&TokenType::Token(token::Semi)) {
394 if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
395 // Likely inside a macro, can't provide meaningful suggestions.
396 } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
397 // The current token is in the same line as the prior token, not recoverable.
398 } else if [token::Comma, token::Colon].contains(&self.token.kind)
399 && self.prev_token.kind == token::CloseDelim(Delimiter::Parenthesis)
401 // Likely typo: The current token is on a new line and is expected to be
402 // `.`, `;`, `?`, or an operator after a close delimiter token.
404 // let a = std::process::Command::new("echo")
408 // https://github.com/rust-lang/rust/issues/72253
409 } else if self.look_ahead(1, |t| {
410 t == &token::CloseDelim(Delimiter::Brace)
411 || t.can_begin_expr() && t.kind != token::Colon
412 }) && [token::Comma, token::Colon].contains(&self.token.kind)
414 // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is
415 // either `,` or `:`, and the next token could either start a new statement or is a
416 // block close. For example:
420 self.sess.emit_err(ExpectedSemi {
421 span: self.token.span,
422 token: self.token.clone(),
423 unexpected_token_label: None,
424 sugg: ExpectedSemiSugg::ChangeToSemi(self.token.span),
428 } else if self.look_ahead(0, |t| {
429 t == &token::CloseDelim(Delimiter::Brace)
430 || ((t.can_begin_expr() || t.can_begin_item())
432 && t != &token::Pound)
433 // Avoid triggering with too many trailing `#` in raw string.
435 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
436 ) && t == &token::Pound)
437 }) && !expected.contains(&TokenType::Token(token::Comma))
439 // Missing semicolon typo. This is triggered if the next token could either start a
440 // new statement or is a block close. For example:
444 let span = self.prev_token.span.shrink_to_hi();
445 self.sess.emit_err(ExpectedSemi {
447 token: self.token.clone(),
448 unexpected_token_label: Some(self.token.span),
449 sugg: ExpectedSemiSugg::AddSemi(span),
455 if self.token.kind == TokenKind::EqEq
456 && self.prev_token.is_ident()
457 && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Eq)))
459 // Likely typo: `=` → `==` in let expr or enum item
460 return Err(self.sess.create_err(UseEqInstead { span: self.token.span }));
463 let expect = tokens_to_string(&expected);
464 let actual = super::token_descr(&self.token);
465 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
466 let short_expect = if expected.len() > 6 {
467 format!("{} possible tokens", expected.len())
472 format!("expected one of {expect}, found {actual}"),
473 (self.prev_token.span.shrink_to_hi(), format!("expected one of {short_expect}")),
475 } else if expected.is_empty() {
477 format!("unexpected token: {actual}"),
478 (self.prev_token.span, "unexpected token after this".to_string()),
482 format!("expected {expect}, found {actual}"),
483 (self.prev_token.span.shrink_to_hi(), format!("expected {expect}")),
486 self.last_unexpected_token_span = Some(self.token.span);
487 // FIXME: translation requires list formatting (for `expect`)
488 let mut err = self.struct_span_err(self.token.span, &msg_exp);
490 if let TokenKind::Ident(symbol, _) = &self.prev_token.kind {
491 if ["def", "fun", "func", "function"].contains(&symbol.as_str()) {
492 err.span_suggestion_short(
493 self.prev_token.span,
494 &format!("write `fn` instead of `{symbol}` to declare a function"),
496 Applicability::MachineApplicable,
501 // `pub` may be used for an item or `pub(crate)`
502 if self.prev_token.is_ident_named(sym::public)
503 && (self.token.can_begin_item()
504 || self.token.kind == TokenKind::OpenDelim(Delimiter::Parenthesis))
506 err.span_suggestion_short(
507 self.prev_token.span,
508 "write `pub` instead of `public` to make the item public",
510 Applicability::MachineApplicable,
514 // Add suggestion for a missing closing angle bracket if '>' is included in expected_tokens
515 // there are unclosed angle brackets
516 if self.unmatched_angle_bracket_count > 0
517 && self.token.kind == TokenKind::Eq
518 && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Gt)))
520 err.span_label(self.prev_token.span, "maybe try to close unmatched angle bracket");
523 let sp = if self.token == token::Eof {
524 // This is EOF; don't want to point at the following char, but rather the last token.
529 match self.recover_closing_delimiter(
532 .filter_map(|tt| match tt {
533 TokenType::Token(t) => Some(t.clone()),
536 .collect::<Vec<_>>(),
541 return Ok(recovered);
545 if self.check_too_many_raw_str_terminators(&mut err) {
546 if expected.contains(&TokenType::Token(token::Semi)) && self.eat(&token::Semi) {
554 if self.prev_token.span == DUMMY_SP {
555 // Account for macro context where the previous span might not be
556 // available to avoid incorrect output (#54841).
557 err.span_label(self.token.span, label_exp);
558 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
559 // When the spans are in the same line, it means that the only content between
560 // them is whitespace, point at the found token in that case:
562 // X | () => { syntax error };
563 // | ^^^^^ expected one of 8 possible tokens here
565 // instead of having:
567 // X | () => { syntax error };
568 // | -^^^^^ unexpected token
570 // | expected one of 8 possible tokens here
571 err.span_label(self.token.span, label_exp);
573 err.span_label(sp, label_exp);
574 err.span_label(self.token.span, "unexpected token");
576 self.maybe_annotate_with_ascription(&mut err, false);
580 fn check_too_many_raw_str_terminators(&mut self, err: &mut Diagnostic) -> bool {
581 let sm = self.sess.source_map();
582 match (&self.prev_token.kind, &self.token.kind) {
584 TokenKind::Literal(Lit {
585 kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
589 ) if !sm.is_multiline(
590 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
593 let n_hashes: u8 = *n_hashes;
594 err.set_primary_message("too many `#` when terminating raw string");
595 let str_span = self.prev_token.span;
596 let mut span = self.token.span;
598 while self.token.kind == TokenKind::Pound
599 && !sm.is_multiline(span.shrink_to_hi().until(self.token.span.shrink_to_lo()))
601 span = span.with_hi(self.token.span.hi());
608 &format!("remove the extra `#`{}", pluralize!(count)),
610 Applicability::MachineApplicable,
614 &format!("this raw string started with {n_hashes} `#`{}", pluralize!(n_hashes)),
622 pub fn maybe_suggest_struct_literal(
626 ) -> Option<PResult<'a, P<Block>>> {
627 if self.token.is_ident() && self.look_ahead(1, |t| t == &token::Colon) {
628 // We might be having a struct literal where people forgot to include the path:
632 let mut snapshot = self.create_snapshot_for_diagnostic();
634 segments: ThinVec::new(),
635 span: self.prev_token.span.shrink_to_lo(),
638 let struct_expr = snapshot.parse_struct_expr(None, path, false);
639 let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No);
640 return Some(match (struct_expr, block_tail) {
641 (Ok(expr), Err(mut err)) => {
642 // We have encountered the following:
647 // fn foo() -> Foo { Path {
651 self.sess.emit_err(StructLiteralBodyWithoutPath {
653 sugg: StructLiteralBodyWithoutPathSugg {
654 before: expr.span.shrink_to_lo(),
655 after: expr.span.shrink_to_hi(),
658 self.restore_snapshot(snapshot);
659 let mut tail = self.mk_block(
660 vec![self.mk_stmt_err(expr.span)],
662 lo.to(self.prev_token.span),
664 tail.could_be_bare_literal = true;
667 (Err(err), Ok(tail)) => {
668 // We have a block tail that contains a somehow valid type ascription expr.
672 (Err(snapshot_err), Err(err)) => {
673 // We don't know what went wrong, emit the normal error.
674 snapshot_err.cancel();
675 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
678 (Ok(_), Ok(mut tail)) => {
679 tail.could_be_bare_literal = true;
687 pub fn maybe_annotate_with_ascription(
689 err: &mut Diagnostic,
690 maybe_expected_semicolon: bool,
692 if let Some((sp, likely_path)) = self.last_type_ascription.take() {
693 let sm = self.sess.source_map();
694 let next_pos = sm.lookup_char_pos(self.token.span.lo());
695 let op_pos = sm.lookup_char_pos(sp.hi());
697 let allow_unstable = self.sess.unstable_features.is_nightly_build();
702 "maybe write a path separator here",
705 Applicability::MaybeIncorrect
707 Applicability::MachineApplicable
710 self.sess.type_ascription_path_suggestions.borrow_mut().insert(sp);
711 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
714 "try using a semicolon",
716 Applicability::MaybeIncorrect,
718 } else if allow_unstable {
719 err.span_label(sp, "tried to parse a type due to this type ascription");
721 err.span_label(sp, "tried to parse a type due to this");
724 // Give extra information about type ascription only if it's a nightly compiler.
726 "`#![feature(type_ascription)]` lets you annotate an expression with a type: \
730 // Avoid giving too much info when it was likely an unrelated typo.
732 "see issue #23416 <https://github.com/rust-lang/rust/issues/23416> \
733 for more information",
740 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
741 /// passes through any errors encountered. Used for error recovery.
742 pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
744 self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
745 Ok(p.parse_token_tree())
752 /// This function checks if there are trailing angle brackets and produces
753 /// a diagnostic to suggest removing them.
755 /// ```ignore (diagnostic)
756 /// let _ = [1, 2, 3].into_iter().collect::<Vec<usize>>>>();
757 /// ^^ help: remove extra angle brackets
760 /// If `true` is returned, then trailing brackets were recovered, tokens were consumed
761 /// up until one of the tokens in 'end' was encountered, and an error was emitted.
762 pub(super) fn check_trailing_angle_brackets(
764 segment: &PathSegment,
767 if !self.may_recover() {
771 // This function is intended to be invoked after parsing a path segment where there are two
774 // 1. A specific token is expected after the path segment.
775 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
776 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
777 // 2. No specific token is expected after the path segment.
778 // eg. `x.foo` (field access)
780 // This function is called after parsing `.foo` and before parsing the token `end` (if
781 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
784 // We only care about trailing angle brackets if we previously parsed angle bracket
785 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
786 // removed in this case:
788 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
790 // This case is particularly tricky as we won't notice it just looking at the tokens -
791 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
792 // have already been parsed):
794 // `x.foo::<u32>>>(3)`
795 let parsed_angle_bracket_args =
796 segment.args.as_ref().map_or(false, |args| args.is_angle_bracketed());
799 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
800 parsed_angle_bracket_args,
802 if !parsed_angle_bracket_args {
806 // Keep the span at the start so we can highlight the sequence of `>` characters to be
808 let lo = self.token.span;
810 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
811 // (since we might have the field access case and the characters we're eating are
812 // actual operators and not trailing characters - ie `x.foo >> 3`).
813 let mut position = 0;
815 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
816 // many of each (so we can correctly pluralize our error messages) and continue to
818 let mut number_of_shr = 0;
819 let mut number_of_gt = 0;
820 while self.look_ahead(position, |t| {
821 trace!("check_trailing_angle_brackets: t={:?}", t);
822 if *t == token::BinOp(token::BinOpToken::Shr) {
825 } else if *t == token::Gt {
835 // If we didn't find any trailing `>` characters, then we have nothing to error about.
837 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
838 number_of_gt, number_of_shr,
840 if number_of_gt < 1 && number_of_shr < 1 {
844 // Finally, double check that we have our end token as otherwise this is the
846 if self.look_ahead(position, |t| {
847 trace!("check_trailing_angle_brackets: t={:?}", t);
848 end.contains(&&t.kind)
850 // Eat from where we started until the end token so that parsing can continue
851 // as if we didn't have those extra angle brackets.
852 self.eat_to_tokens(end);
853 let span = lo.until(self.token.span);
855 let num_extra_brackets = number_of_gt + number_of_shr * 2;
856 self.sess.emit_err(UnmatchedAngleBrackets { span, num_extra_brackets });
862 /// Check if a method call with an intended turbofish has been written without surrounding
864 pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
865 if !self.may_recover() {
869 if token::ModSep == self.token.kind && segment.args.is_none() {
870 let snapshot = self.create_snapshot_for_diagnostic();
872 let lo = self.token.span;
873 match self.parse_angle_args(None) {
875 let span = lo.to(self.prev_token.span);
876 // Detect trailing `>` like in `x.collect::Vec<_>>()`.
877 let mut trailing_span = self.prev_token.span.shrink_to_hi();
878 while self.token.kind == token::BinOp(token::Shr)
879 || self.token.kind == token::Gt
881 trailing_span = trailing_span.to(self.token.span);
884 if self.token.kind == token::OpenDelim(Delimiter::Parenthesis) {
885 // Recover from bad turbofish: `foo.collect::Vec<_>()`.
886 let args = AngleBracketedArgs { args, span }.into();
889 self.sess.emit_err(GenericParamsWithoutAngleBrackets {
891 sugg: GenericParamsWithoutAngleBracketsSugg {
892 left: span.shrink_to_lo(),
893 right: trailing_span,
897 // This doesn't look like an invalid turbofish, can't recover parse state.
898 self.restore_snapshot(snapshot);
902 // We couldn't parse generic parameters, unlikely to be a turbofish. Rely on
903 // generic parse error instead.
905 self.restore_snapshot(snapshot);
911 /// When writing a turbofish with multiple type parameters missing the leading `::`, we will
912 /// encounter a parse error when encountering the first `,`.
913 pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
915 mut e: DiagnosticBuilder<'a, ErrorGuaranteed>,
917 ) -> PResult<'a, ()> {
918 if let ExprKind::Binary(binop, _, _) = &expr.kind
919 && let ast::BinOpKind::Lt = binop.node
920 && self.eat(&token::Comma)
922 let x = self.parse_seq_to_before_end(
924 SeqSep::trailing_allowed(token::Comma),
925 |p| p.parse_generic_arg(None),
928 Ok((_, _, false)) => {
929 if self.eat(&token::Gt) {
930 e.span_suggestion_verbose(
931 binop.span.shrink_to_lo(),
932 fluent::parse_sugg_turbofish_syntax,
934 Applicability::MaybeIncorrect,
937 match self.parse_expr() {
940 self.mk_expr_err(expr.span.to(self.prev_token.span));
944 *expr = self.mk_expr_err(expr.span);
959 /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
960 /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
961 /// parenthesising the leftmost comparison.
962 fn attempt_chained_comparison_suggestion(
964 err: &mut ComparisonOperatorsCannotBeChained,
966 outer_op: &Spanned<AssocOp>,
967 ) -> bool /* advanced the cursor */ {
968 if let ExprKind::Binary(op, l1, r1) = &inner_op.kind {
969 if let ExprKind::Field(_, ident) = l1.kind
970 && ident.as_str().parse::<i32>().is_err()
971 && !matches!(r1.kind, ExprKind::Lit(_))
973 // The parser has encountered `foo.bar<baz`, the likelihood of the turbofish
974 // suggestion being the only one to apply is high.
977 return match (op.node, &outer_op.node) {
979 (BinOpKind::Eq, AssocOp::Equal) |
980 // `x < y < z` and friends.
981 (BinOpKind::Lt, AssocOp::Less | AssocOp::LessEqual) |
982 (BinOpKind::Le, AssocOp::LessEqual | AssocOp::Less) |
983 // `x > y > z` and friends.
984 (BinOpKind::Gt, AssocOp::Greater | AssocOp::GreaterEqual) |
985 (BinOpKind::Ge, AssocOp::GreaterEqual | AssocOp::Greater) => {
986 let expr_to_str = |e: &Expr| {
987 self.span_to_snippet(e.span)
988 .unwrap_or_else(|_| pprust::expr_to_string(&e))
990 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::SplitComparison {
991 span: inner_op.span.shrink_to_hi(),
992 middle_term: expr_to_str(&r1),
994 false // Keep the current parse behavior, where the AST is `(x < y) < z`.
997 (BinOpKind::Eq, AssocOp::Less | AssocOp::LessEqual | AssocOp::Greater | AssocOp::GreaterEqual) => {
998 // Consume `z`/outer-op-rhs.
999 let snapshot = self.create_snapshot_for_diagnostic();
1000 match self.parse_expr() {
1002 // We are sure that outer-op-rhs could be consumed, the suggestion is
1004 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1005 left: r1.span.shrink_to_lo(),
1006 right: r2.span.shrink_to_hi(),
1012 self.restore_snapshot(snapshot);
1018 (BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge, AssocOp::Equal) => {
1019 let snapshot = self.create_snapshot_for_diagnostic();
1020 // At this point it is always valid to enclose the lhs in parentheses, no
1021 // further checks are necessary.
1022 match self.parse_expr() {
1024 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1025 left: l1.span.shrink_to_lo(),
1026 right: r1.span.shrink_to_hi(),
1032 self.restore_snapshot(snapshot);
1043 /// Produces an error if comparison operators are chained (RFC #558).
1044 /// We only need to check the LHS, not the RHS, because all comparison ops have same
1045 /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
1047 /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
1048 /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
1051 /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
1052 /// associative we can infer that we have:
1061 pub(super) fn check_no_chained_comparison(
1064 outer_op: &Spanned<AssocOp>,
1065 ) -> PResult<'a, Option<P<Expr>>> {
1067 outer_op.node.is_comparison(),
1068 "check_no_chained_comparison: {:?} is not comparison",
1072 let mk_err_expr = |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err)));
1074 match &inner_op.kind {
1075 ExprKind::Binary(op, l1, r1) if op.node.is_comparison() => {
1076 let mut err = ComparisonOperatorsCannotBeChained {
1077 span: vec![op.span, self.prev_token.span],
1078 suggest_turbofish: None,
1079 help_turbofish: None,
1080 chaining_sugg: None,
1083 // Include `<` to provide this recommendation even in a case like
1084 // `Foo<Bar<Baz<Qux, ()>>>`
1085 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Less
1086 || outer_op.node == AssocOp::Greater
1088 if outer_op.node == AssocOp::Less {
1089 let snapshot = self.create_snapshot_for_diagnostic();
1091 // So far we have parsed `foo<bar<`, consume the rest of the type args.
1093 [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
1094 self.consume_tts(1, &modifiers);
1096 if !&[token::OpenDelim(Delimiter::Parenthesis), token::ModSep]
1097 .contains(&self.token.kind)
1099 // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
1100 // parser and bail out.
1101 self.restore_snapshot(snapshot);
1104 return if token::ModSep == self.token.kind {
1105 // We have some certainty that this was a bad turbofish at this point.
1107 err.suggest_turbofish = Some(op.span.shrink_to_lo());
1109 let snapshot = self.create_snapshot_for_diagnostic();
1110 self.bump(); // `::`
1112 // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
1113 match self.parse_expr() {
1115 // 99% certain that the suggestion is correct, continue parsing.
1116 self.sess.emit_err(err);
1117 // FIXME: actually check that the two expressions in the binop are
1118 // paths and resynthesize new fn call expression instead of using
1119 // `ExprKind::Err` placeholder.
1120 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1124 // Not entirely sure now, but we bubble the error up with the
1126 self.restore_snapshot(snapshot);
1127 Err(err.into_diagnostic(&self.sess.span_diagnostic))
1130 } else if token::OpenDelim(Delimiter::Parenthesis) == self.token.kind {
1131 // We have high certainty that this was a bad turbofish at this point.
1133 err.suggest_turbofish = Some(op.span.shrink_to_lo());
1134 // Consume the fn call arguments.
1135 match self.consume_fn_args() {
1136 Err(()) => Err(err.into_diagnostic(&self.sess.span_diagnostic)),
1138 self.sess.emit_err(err);
1139 // FIXME: actually check that the two expressions in the binop are
1140 // paths and resynthesize new fn call expression instead of using
1141 // `ExprKind::Err` placeholder.
1142 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1146 if !matches!(l1.kind, ExprKind::Lit(_))
1147 && !matches!(r1.kind, ExprKind::Lit(_))
1149 // All we know is that this is `foo < bar >` and *nothing* else. Try to
1150 // be helpful, but don't attempt to recover.
1151 err.help_turbofish = Some(());
1154 // If it looks like a genuine attempt to chain operators (as opposed to a
1155 // misformatted turbofish, for instance), suggest a correct form.
1156 if self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op)
1158 self.sess.emit_err(err);
1159 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1161 // These cases cause too many knock-down errors, bail out (#61329).
1162 Err(err.into_diagnostic(&self.sess.span_diagnostic))
1167 self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1168 self.sess.emit_err(err);
1170 return mk_err_expr(self, inner_op.span.to(self.prev_token.span));
1178 fn consume_fn_args(&mut self) -> Result<(), ()> {
1179 let snapshot = self.create_snapshot_for_diagnostic();
1182 // Consume the fn call arguments.
1184 (token::OpenDelim(Delimiter::Parenthesis), 1),
1185 (token::CloseDelim(Delimiter::Parenthesis), -1),
1187 self.consume_tts(1, &modifiers);
1189 if self.token.kind == token::Eof {
1190 // Not entirely sure that what we consumed were fn arguments, rollback.
1191 self.restore_snapshot(snapshot);
1194 // 99% certain that the suggestion is correct, continue parsing.
1199 pub(super) fn maybe_report_ambiguous_plus(&mut self, impl_dyn_multi: bool, ty: &Ty) {
1201 self.sess.emit_err(AmbiguousPlus { sum_ty: pprust::ty_to_string(&ty), span: ty.span });
1205 /// Swift lets users write `Ty?` to mean `Option<Ty>`. Parse the construct and recover from it.
1206 pub(super) fn maybe_recover_from_question_mark(&mut self, ty: P<Ty>) -> P<Ty> {
1207 if self.token == token::Question {
1209 self.sess.emit_err(QuestionMarkInType {
1210 span: self.prev_token.span,
1211 sugg: QuestionMarkInTypeSugg {
1212 left: ty.span.shrink_to_lo(),
1213 right: self.prev_token.span,
1216 self.mk_ty(ty.span.to(self.prev_token.span), TyKind::Err)
1222 pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> {
1223 // Do not add `+` to expected tokens.
1224 if !self.token.is_like_plus() {
1229 let bounds = self.parse_generic_bounds(None)?;
1230 let sum_span = ty.span.to(self.prev_token.span);
1232 let sub = match &ty.kind {
1233 TyKind::Ref(lifetime, mut_ty) => {
1234 let sum_with_parens = pprust::to_string(|s| {
1236 s.print_opt_lifetime(lifetime);
1237 s.print_mutability(mut_ty.mutbl, false);
1239 s.print_type(&mut_ty.ty);
1240 if !bounds.is_empty() {
1242 s.print_type_bounds(&bounds);
1247 BadTypePlusSub::AddParen { sum_with_parens, span: sum_span }
1249 TyKind::Ptr(..) | TyKind::BareFn(..) => BadTypePlusSub::ForgotParen { span: sum_span },
1250 _ => BadTypePlusSub::ExpectPath { span: sum_span },
1253 self.sess.emit_err(BadTypePlus { ty: pprust::ty_to_string(ty), span: sum_span, sub });
1258 pub(super) fn recover_from_prefix_increment(
1260 operand_expr: P<Expr>,
1263 ) -> PResult<'a, P<Expr>> {
1264 let standalone = if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr };
1265 let kind = IncDecRecovery { standalone, op: IncOrDec::Inc, fixity: UnaryFixity::Pre };
1266 self.recover_from_inc_dec(operand_expr, kind, op_span)
1269 pub(super) fn recover_from_postfix_increment(
1271 operand_expr: P<Expr>,
1274 ) -> PResult<'a, P<Expr>> {
1275 let kind = IncDecRecovery {
1276 standalone: if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr },
1278 fixity: UnaryFixity::Post,
1280 self.recover_from_inc_dec(operand_expr, kind, op_span)
1283 fn recover_from_inc_dec(
1286 kind: IncDecRecovery,
1288 ) -> PResult<'a, P<Expr>> {
1289 let mut err = self.struct_span_err(
1291 &format!("Rust has no {} {} operator", kind.fixity, kind.op.name()),
1293 err.span_label(op_span, &format!("not a valid {} operator", kind.fixity));
1295 let help_base_case = |mut err: DiagnosticBuilder<'_, _>, base| {
1296 err.help(&format!("use `{}= 1` instead", kind.op.chr()));
1302 let spans = match kind.fixity {
1303 UnaryFixity::Pre => (op_span, base.span.shrink_to_hi()),
1304 UnaryFixity::Post => (base.span.shrink_to_lo(), op_span),
1307 match kind.standalone {
1308 IsStandalone::Standalone => {
1309 self.inc_dec_standalone_suggest(kind, spans).emit_verbose(&mut err)
1311 IsStandalone::Subexpr => {
1312 let Ok(base_src) = self.span_to_snippet(base.span)
1313 else { return help_base_case(err, base) };
1315 UnaryFixity::Pre => {
1316 self.prefix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1318 UnaryFixity::Post => {
1319 // won't suggest since we can not handle the precedences
1320 // for example: `a + b++` has been parsed (a + b)++ and we can not suggest here
1321 if !matches!(base.kind, ExprKind::Binary(_, _, _)) {
1322 self.postfix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1331 fn prefix_inc_dec_suggest(
1334 kind: IncDecRecovery,
1335 (pre_span, post_span): (Span, Span),
1338 msg: format!("use `{}= 1` instead", kind.op.chr()),
1340 (pre_span, "{ ".to_string()),
1341 (post_span, format!(" {}= 1; {} }}", kind.op.chr(), base_src)),
1343 applicability: Applicability::MachineApplicable,
1347 fn postfix_inc_dec_suggest(
1350 kind: IncDecRecovery,
1351 (pre_span, post_span): (Span, Span),
1353 let tmp_var = if base_src.trim() == "tmp" { "tmp_" } else { "tmp" };
1355 msg: format!("use `{}= 1` instead", kind.op.chr()),
1357 (pre_span, format!("{{ let {tmp_var} = ")),
1358 (post_span, format!("; {} {}= 1; {} }}", base_src, kind.op.chr(), tmp_var)),
1360 applicability: Applicability::HasPlaceholders,
1364 fn inc_dec_standalone_suggest(
1366 kind: IncDecRecovery,
1367 (pre_span, post_span): (Span, Span),
1369 let mut patches = Vec::new();
1371 if !pre_span.is_empty() {
1372 patches.push((pre_span, String::new()));
1375 patches.push((post_span, format!(" {}= 1", kind.op.chr())));
1377 msg: format!("use `{}= 1` instead", kind.op.chr()),
1379 applicability: Applicability::MachineApplicable,
1383 /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
1384 /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
1385 /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
1386 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
1389 ) -> PResult<'a, P<T>> {
1390 if !self.may_recover() {
1394 // Do not add `::` to expected tokens.
1395 if self.token == token::ModSep {
1396 if let Some(ty) = base.to_ty() {
1397 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1403 /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
1404 /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
1405 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
1409 ) -> PResult<'a, P<T>> {
1410 self.expect(&token::ModSep)?;
1412 let mut path = ast::Path { segments: ThinVec::new(), span: DUMMY_SP, tokens: None };
1413 self.parse_path_segments(&mut path.segments, T::PATH_STYLE, None)?;
1414 path.span = ty_span.to(self.prev_token.span);
1416 let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
1417 self.sess.emit_err(BadQPathStage2 {
1419 ty: format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
1422 let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
1423 Ok(P(T::recovered(Some(P(QSelf { ty, path_span, position: 0 })), path)))
1426 pub fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
1427 if self.token.kind == TokenKind::Semi {
1431 IncorrectSemicolon { span: self.prev_token.span, opt_help: None, name: "" };
1433 if !items.is_empty() {
1434 let previous_item = &items[items.len() - 1];
1435 let previous_item_kind_name = match previous_item.kind {
1436 // Say "braced struct" because tuple-structs and
1437 // braceless-empty-struct declarations do take a semicolon.
1438 ItemKind::Struct(..) => Some("braced struct"),
1439 ItemKind::Enum(..) => Some("enum"),
1440 ItemKind::Trait(..) => Some("trait"),
1441 ItemKind::Union(..) => Some("union"),
1444 if let Some(name) = previous_item_kind_name {
1445 err.opt_help = Some(());
1449 self.sess.emit_err(err);
1456 /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
1457 /// closing delimiter.
1458 pub(super) fn unexpected_try_recover(
1461 ) -> PResult<'a, bool /* recovered */> {
1462 let token_str = pprust::token_kind_to_string(t);
1463 let this_token_str = super::token_descr(&self.token);
1464 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1465 // Point at the end of the macro call when reaching end of macro arguments.
1466 (token::Eof, Some(_)) => {
1467 let sp = self.prev_token.span.shrink_to_hi();
1470 // We don't want to point at the following span after DUMMY_SP.
1471 // This happens when the parser finds an empty TokenStream.
1472 _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
1473 // EOF, don't want to point at the following char, but rather the last token.
1474 (token::Eof, None) => (self.prev_token.span, self.token.span),
1475 _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
1478 "expected `{}`, found {}",
1480 match (&self.token.kind, self.subparser_name) {
1481 (token::Eof, Some(origin)) => format!("end of {origin}"),
1482 _ => this_token_str,
1485 let mut err = self.struct_span_err(sp, &msg);
1486 let label_exp = format!("expected `{token_str}`");
1487 match self.recover_closing_delimiter(&[t.clone()], err) {
1490 return Ok(recovered);
1493 let sm = self.sess.source_map();
1494 if !sm.is_multiline(prev_sp.until(sp)) {
1495 // When the spans are in the same line, it means that the only content
1496 // between them is whitespace, point only at the found token.
1497 err.span_label(sp, label_exp);
1499 err.span_label(prev_sp, label_exp);
1500 err.span_label(sp, "unexpected token");
1505 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1506 if self.eat(&token::Semi) {
1509 self.expect(&token::Semi).map(drop) // Error unconditionally
1512 /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
1513 /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
1514 pub(super) fn recover_incorrect_await_syntax(
1518 ) -> PResult<'a, P<Expr>> {
1519 let (hi, expr, is_question) = if self.token == token::Not {
1520 // Handle `await!(<expr>)`.
1521 self.recover_await_macro()?
1523 self.recover_await_prefix(await_sp)?
1525 let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
1526 let kind = match expr.kind {
1527 // Avoid knock-down errors as we don't know whether to interpret this as `foo().await?`
1528 // or `foo()?.await` (the very reason we went with postfix syntax 😅).
1529 ExprKind::Try(_) => ExprKind::Err,
1530 _ => ExprKind::Await(expr),
1532 let expr = self.mk_expr(lo.to(sp), kind);
1533 self.maybe_recover_from_bad_qpath(expr)
1536 fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1537 self.expect(&token::Not)?;
1538 self.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
1539 let expr = self.parse_expr()?;
1540 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
1541 Ok((self.prev_token.span, expr, false))
1544 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
1545 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
1546 let expr = if self.token == token::OpenDelim(Delimiter::Brace) {
1547 // Handle `await { <expr> }`.
1548 // This needs to be handled separately from the next arm to avoid
1549 // interpreting `await { <expr> }?` as `<expr>?.await`.
1550 self.parse_block_expr(None, self.token.span, BlockCheckMode::Default)
1554 .map_err(|mut err| {
1555 err.span_label(await_sp, "while parsing this incorrect await expression");
1558 Ok((expr.span, expr, is_question))
1561 fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
1562 let span = lo.to(hi);
1563 let applicability = match expr.kind {
1564 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
1565 _ => Applicability::MachineApplicable,
1568 self.sess.emit_err(IncorrectAwait {
1570 sugg_span: (span, applicability),
1571 expr: self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr)),
1572 question_mark: if is_question { "?" } else { "" },
1578 /// If encountering `future.await()`, consumes and emits an error.
1579 pub(super) fn recover_from_await_method_call(&mut self) {
1580 if self.token == token::OpenDelim(Delimiter::Parenthesis)
1581 && self.look_ahead(1, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
1584 let lo = self.token.span;
1586 let span = lo.to(self.token.span);
1589 self.sess.emit_err(IncorrectUseOfAwait { span });
1593 pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, P<Expr>> {
1594 let is_try = self.token.is_keyword(kw::Try);
1595 let is_questionmark = self.look_ahead(1, |t| t == &token::Not); //check for !
1596 let is_open = self.look_ahead(2, |t| t == &token::OpenDelim(Delimiter::Parenthesis)); //check for (
1598 if is_try && is_questionmark && is_open {
1599 let lo = self.token.span;
1600 self.bump(); //remove try
1601 self.bump(); //remove !
1602 let try_span = lo.to(self.token.span); //we take the try!( span
1603 self.bump(); //remove (
1604 let is_empty = self.token == token::CloseDelim(Delimiter::Parenthesis); //check if the block is empty
1605 self.consume_block(Delimiter::Parenthesis, ConsumeClosingDelim::No); //eat the block
1606 let hi = self.token.span;
1607 self.bump(); //remove )
1608 let mut err = self.struct_span_err(lo.to(hi), "use of deprecated `try` macro");
1609 err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
1610 let prefix = if is_empty { "" } else { "alternatively, " };
1612 err.multipart_suggestion(
1613 "you can use the `?` operator instead",
1614 vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
1615 Applicability::MachineApplicable,
1618 err.span_suggestion(lo.shrink_to_lo(), &format!("{prefix}you can still access the deprecated `try!()` macro using the \"raw identifier\" syntax"), "r#", Applicability::MachineApplicable);
1620 Ok(self.mk_expr_err(lo.to(hi)))
1622 Err(self.expected_expression_found()) // The user isn't trying to invoke the try! macro
1626 /// Recovers a situation like `for ( $pat in $expr )`
1627 /// and suggest writing `for $pat in $expr` instead.
1629 /// This should be called before parsing the `$block`.
1630 pub(super) fn recover_parens_around_for_head(
1633 begin_paren: Option<Span>,
1635 match (&self.token.kind, begin_paren) {
1636 (token::CloseDelim(Delimiter::Parenthesis), Some(begin_par_sp)) => {
1639 let sm = self.sess.source_map();
1640 let left = begin_par_sp;
1641 let right = self.prev_token.span;
1642 let left_snippet = if let Ok(snip) = sm.span_to_prev_source(left) &&
1643 !snip.ends_with(' ') {
1649 let right_snippet = if let Ok(snip) = sm.span_to_next_source(right) &&
1650 !snip.starts_with(' ') {
1656 self.sess.emit_err(ParenthesesInForHead {
1657 span: vec![left, right],
1658 // With e.g. `for (x) in y)` this would replace `(x) in y)`
1659 // with `x) in y)` which is syntactically invalid.
1660 // However, this is prevented before we get here.
1661 sugg: ParenthesesInForHeadSugg { left, right, left_snippet, right_snippet },
1664 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1665 pat.and_then(|pat| match pat.kind {
1666 PatKind::Paren(pat) => pat,
1674 pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1675 (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1676 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1677 || self.token.is_ident() &&
1678 matches!(node, ast::ExprKind::Path(..) | ast::ExprKind::Field(..)) &&
1679 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
1680 self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Parenthesis))
1681 || self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Brace)) // `foo:bar {`
1682 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar::<baz`
1683 self.look_ahead(2, |t| t == &token::Lt) &&
1684 self.look_ahead(3, |t| t.is_ident())
1685 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
1686 self.look_ahead(2, |t| t.is_ident())
1687 || self.look_ahead(1, |t| t == &token::ModSep)
1688 && (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
1689 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1692 pub(super) fn recover_seq_parse_error(
1696 result: PResult<'a, P<Expr>>,
1702 // Recover from parse error, callers expect the closing delim to be consumed.
1703 self.consume_block(delim, ConsumeClosingDelim::Yes);
1704 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err)
1709 pub(super) fn recover_closing_delimiter(
1711 tokens: &[TokenKind],
1712 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
1713 ) -> PResult<'a, bool> {
1715 // We want to use the last closing delim that would apply.
1716 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1717 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1718 && Some(self.token.span) > unmatched.unclosed_span
1725 // Recover and assume that the detected unclosed delimiter was meant for
1726 // this location. Emit the diagnostic and act as if the delimiter was
1727 // present for the parser's sake.
1729 // Don't attempt to recover from this unclosed delimiter more than once.
1730 let unmatched = self.unclosed_delims.remove(pos);
1731 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1732 if unmatched.found_delim.is_none() {
1733 // We encountered `Eof`, set this fact here to avoid complaining about missing
1734 // `fn main()` when we found place to suggest the closing brace.
1735 *self.sess.reached_eof.borrow_mut() = true;
1738 // We want to suggest the inclusion of the closing delimiter where it makes
1739 // the most sense, which is immediately after the last token:
1744 // | help: `)` may belong here
1746 // unclosed delimiter
1747 if let Some(sp) = unmatched.unclosed_span {
1748 let mut primary_span: Vec<Span> =
1749 err.span.primary_spans().iter().cloned().collect();
1750 primary_span.push(sp);
1751 let mut primary_span: MultiSpan = primary_span.into();
1752 for span_label in err.span.span_labels() {
1753 if let Some(label) = span_label.label {
1754 primary_span.push_span_label(span_label.span, label);
1757 err.set_span(primary_span);
1758 err.span_label(sp, "unclosed delimiter");
1760 // Backticks should be removed to apply suggestions.
1761 let mut delim = delim.to_string();
1762 delim.retain(|c| c != '`');
1763 err.span_suggestion_short(
1764 self.prev_token.span.shrink_to_hi(),
1765 &format!("`{delim}` may belong here"),
1767 Applicability::MaybeIncorrect,
1769 if unmatched.found_delim.is_none() {
1770 // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1771 // errors which would be emitted elsewhere in the parser and let other error
1772 // recovery consume the rest of the file.
1776 self.expected_tokens.clear(); // Reduce the number of errors.
1784 /// Eats tokens until we can be relatively sure we reached the end of the
1785 /// statement. This is something of a best-effort heuristic.
1787 /// We terminate when we find an unmatched `}` (without consuming it).
1788 pub(super) fn recover_stmt(&mut self) {
1789 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1792 /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1793 /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1794 /// approximate -- it can mean we break too early due to macros, but that
1795 /// should only lead to sub-optimal recovery, not inaccurate parsing).
1797 /// If `break_on_block` is `Break`, then we will stop consuming tokens
1798 /// after finding (and consuming) a brace-delimited block.
1799 pub(super) fn recover_stmt_(
1801 break_on_semi: SemiColonMode,
1802 break_on_block: BlockMode,
1804 let mut brace_depth = 0;
1805 let mut bracket_depth = 0;
1806 let mut in_block = false;
1807 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1809 debug!("recover_stmt_ loop {:?}", self.token);
1810 match self.token.kind {
1811 token::OpenDelim(Delimiter::Brace) => {
1814 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1819 token::OpenDelim(Delimiter::Bracket) => {
1823 token::CloseDelim(Delimiter::Brace) => {
1824 if brace_depth == 0 {
1825 debug!("recover_stmt_ return - close delim {:?}", self.token);
1830 if in_block && bracket_depth == 0 && brace_depth == 0 {
1831 debug!("recover_stmt_ return - block end {:?}", self.token);
1835 token::CloseDelim(Delimiter::Bracket) => {
1837 if bracket_depth < 0 {
1843 debug!("recover_stmt_ return - Eof");
1848 if break_on_semi == SemiColonMode::Break
1850 && bracket_depth == 0
1852 debug!("recover_stmt_ return - Semi");
1857 if break_on_semi == SemiColonMode::Comma
1859 && bracket_depth == 0 =>
1861 debug!("recover_stmt_ return - Semi");
1869 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1870 if self.eat_keyword(kw::In) {
1871 // a common typo: `for _ in in bar {}`
1872 self.sess.emit_err(InInTypo {
1873 span: self.prev_token.span,
1874 sugg_span: in_span.until(self.prev_token.span),
1879 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1880 if let token::DocComment(..) = self.token.kind {
1881 self.sess.emit_err(DocCommentOnParamType { span: self.token.span });
1883 } else if self.token == token::Pound
1884 && self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Bracket))
1886 let lo = self.token.span;
1887 // Skip every token until next possible arg.
1888 while self.token != token::CloseDelim(Delimiter::Bracket) {
1891 let sp = lo.to(self.token.span);
1893 self.sess.emit_err(AttributeOnParamType { span: sp });
1897 pub(super) fn parameter_without_type(
1899 err: &mut Diagnostic,
1903 ) -> Option<Ident> {
1904 // If we find a pattern followed by an identifier, it could be an (incorrect)
1905 // C-style parameter declaration.
1906 if self.check_ident()
1907 && self.look_ahead(1, |t| {
1908 *t == token::Comma || *t == token::CloseDelim(Delimiter::Parenthesis)
1911 // `fn foo(String s) {}`
1912 let ident = self.parse_ident().unwrap();
1913 let span = pat.span.with_hi(ident.span.hi());
1915 err.span_suggestion(
1917 "declare the type after the parameter binding",
1918 "<identifier>: <type>",
1919 Applicability::HasPlaceholders,
1922 } else if require_name
1923 && (self.token == token::Comma
1924 || self.token == token::Lt
1925 || self.token == token::CloseDelim(Delimiter::Parenthesis))
1927 let rfc_note = "anonymous parameters are removed in the 2018 edition (see RFC 1685)";
1929 let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
1931 PatKind::Ident(_, ident, _) => (
1934 ": TypeName".to_string(),
1936 pat.span.shrink_to_lo(),
1937 pat.span.shrink_to_hi(),
1938 pat.span.shrink_to_lo(),
1940 // Also catches `fn foo(&a)`.
1941 PatKind::Ref(ref inner_pat, mutab)
1942 if matches!(inner_pat.clone().into_inner().kind, PatKind::Ident(..)) =>
1944 match inner_pat.clone().into_inner().kind {
1945 PatKind::Ident(_, ident, _) => {
1946 let mutab = mutab.prefix_str();
1950 format!("{ident}: &{mutab}TypeName"),
1952 pat.span.shrink_to_lo(),
1954 pat.span.shrink_to_lo(),
1957 _ => unreachable!(),
1961 // Otherwise, try to get a type and emit a suggestion.
1962 if let Some(ty) = pat.to_ty() {
1963 err.span_suggestion_verbose(
1965 "explicitly ignore the parameter name",
1966 format!("_: {}", pprust::ty_to_string(&ty)),
1967 Applicability::MachineApplicable,
1976 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1978 err.span_suggestion(
1980 "if this is a `self` type, give it a parameter name",
1982 Applicability::MaybeIncorrect,
1985 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
1986 // `fn foo(HashMap: TypeName<u32>)`.
1987 if self.token != token::Lt {
1988 err.span_suggestion(
1990 "if this is a parameter name, give it a type",
1992 Applicability::HasPlaceholders,
1995 err.span_suggestion(
1997 "if this is a type, explicitly ignore the parameter name",
1999 Applicability::MachineApplicable,
2003 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
2004 return if self.token == token::Lt { None } else { Some(ident) };
2009 pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
2010 let pat = self.parse_pat_no_top_alt(Some("argument name"))?;
2011 self.expect(&token::Colon)?;
2012 let ty = self.parse_ty()?;
2014 self.sess.emit_err(PatternMethodParamWithoutBody { span: pat.span });
2016 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2018 P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID, tokens: None });
2022 pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
2023 let span = param.pat.span;
2024 param.ty.kind = TyKind::Err;
2025 self.sess.emit_err(SelfParamNotFirst { span });
2029 pub(super) fn consume_block(&mut self, delim: Delimiter, consume_close: ConsumeClosingDelim) {
2030 let mut brace_depth = 0;
2032 if self.eat(&token::OpenDelim(delim)) {
2034 } else if self.check(&token::CloseDelim(delim)) {
2035 if brace_depth == 0 {
2036 if let ConsumeClosingDelim::Yes = consume_close {
2037 // Some of the callers of this method expect to be able to parse the
2038 // closing delimiter themselves, so we leave it alone. Otherwise we advance
2048 } else if self.token == token::Eof {
2056 pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2057 let (span, msg) = match (&self.token.kind, self.subparser_name) {
2058 (&token::Eof, Some(origin)) => {
2059 let sp = self.prev_token.span.shrink_to_hi();
2060 (sp, format!("expected expression, found end of {origin}"))
2064 format!("expected expression, found {}", super::token_descr(&self.token),),
2067 let mut err = self.struct_span_err(span, &msg);
2068 let sp = self.sess.source_map().start_point(self.token.span);
2069 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
2070 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
2072 err.span_label(span, "expected expression");
2078 mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
2079 // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
2080 modifier: &[(token::TokenKind, i64)],
2083 if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
2086 if self.token.kind == token::Eof {
2093 /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
2095 /// This is necessary because at this point we don't know whether we parsed a function with
2096 /// anonymous parameters or a function with names but no types. In order to minimize
2097 /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
2098 /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
2099 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
2100 /// we deduplicate them to not complain about duplicated parameter names.
2101 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
2102 let mut seen_inputs = FxHashSet::default();
2103 for input in fn_inputs.iter_mut() {
2104 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
2105 (&input.pat.kind, &input.ty.kind)
2111 if let Some(ident) = opt_ident {
2112 if seen_inputs.contains(&ident) {
2113 input.pat.kind = PatKind::Wild;
2115 seen_inputs.insert(ident);
2120 /// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
2121 /// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
2122 /// like the user has forgotten them.
2123 pub fn handle_ambiguous_unbraced_const_arg(
2125 args: &mut Vec<AngleBracketedArg>,
2126 ) -> PResult<'a, bool> {
2127 // If we haven't encountered a closing `>`, then the argument is malformed.
2128 // It's likely that the user has written a const expression without enclosing it
2129 // in braces, so we try to recover here.
2130 let arg = args.pop().unwrap();
2131 // FIXME: for some reason using `unexpected` or `expected_one_of_not_found` has
2132 // adverse side-effects to subsequent errors and seems to advance the parser.
2133 // We are causing this error here exclusively in case that a `const` expression
2134 // could be recovered from the current parser state, even if followed by more
2135 // arguments after a comma.
2136 let mut err = self.struct_span_err(
2138 &format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
2140 err.span_label(self.token.span, "expected one of `,` or `>`");
2141 match self.recover_const_arg(arg.span(), err) {
2143 args.push(AngleBracketedArg::Arg(arg));
2144 if self.eat(&token::Comma) {
2145 return Ok(true); // Continue
2150 // We will emit a more generic error later.
2154 return Ok(false); // Don't continue.
2157 /// Attempt to parse a generic const argument that has not been enclosed in braces.
2158 /// There are a limited number of expressions that are permitted without being encoded
2161 /// - Single-segment paths (i.e. standalone generic const parameters).
2162 /// All other expressions that can be parsed will emit an error suggesting the expression be
2163 /// wrapped in braces.
2164 pub fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
2165 let start = self.token.span;
2166 let expr = self.parse_expr_res(Restrictions::CONST_EXPR, None).map_err(|mut err| {
2168 start.shrink_to_lo(),
2169 "while parsing a const generic argument starting here",
2173 if !self.expr_is_valid_const_arg(&expr) {
2174 self.sess.emit_err(ConstGenericWithoutBraces {
2176 sugg: ConstGenericWithoutBracesSugg {
2177 left: expr.span.shrink_to_lo(),
2178 right: expr.span.shrink_to_hi(),
2185 fn recover_const_param_decl(&mut self, ty_generics: Option<&Generics>) -> Option<GenericArg> {
2186 let snapshot = self.create_snapshot_for_diagnostic();
2187 let param = match self.parse_const_param(AttrVec::new()) {
2191 self.restore_snapshot(snapshot);
2196 let ident = param.ident.to_string();
2197 let sugg = match (ty_generics, self.sess.source_map().span_to_snippet(param.span())) {
2198 (Some(Generics { params, span: impl_generics, .. }), Ok(snippet)) => {
2199 Some(match ¶ms[..] {
2200 [] => UnexpectedConstParamDeclarationSugg::AddParam {
2201 impl_generics: *impl_generics,
2202 incorrect_decl: param.span(),
2206 [.., generic] => UnexpectedConstParamDeclarationSugg::AppendParam {
2207 impl_generics_end: generic.span().shrink_to_hi(),
2208 incorrect_decl: param.span(),
2216 self.sess.emit_err(UnexpectedConstParamDeclaration { span: param.span(), sugg });
2218 let value = self.mk_expr_err(param.span());
2219 Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }))
2222 pub fn recover_const_param_declaration(
2224 ty_generics: Option<&Generics>,
2225 ) -> PResult<'a, Option<GenericArg>> {
2226 // We have to check for a few different cases.
2227 if let Some(arg) = self.recover_const_param_decl(ty_generics) {
2228 return Ok(Some(arg));
2231 // We haven't consumed `const` yet.
2232 let start = self.token.span;
2233 self.bump(); // `const`
2235 // Detect and recover from the old, pre-RFC2000 syntax for const generics.
2236 let mut err = UnexpectedConstInGenericParam { span: start, to_remove: None };
2237 if self.check_const_arg() {
2238 err.to_remove = Some(start.until(self.token.span));
2239 self.sess.emit_err(err);
2240 Ok(Some(GenericArg::Const(self.parse_const_arg()?)))
2242 let after_kw_const = self.token.span;
2243 self.recover_const_arg(after_kw_const, err.into_diagnostic(&self.sess.span_diagnostic))
2248 /// Try to recover from possible generic const argument without `{` and `}`.
2250 /// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
2251 /// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
2252 /// if we think that the resulting expression would be well formed.
2253 pub fn recover_const_arg(
2256 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2257 ) -> PResult<'a, GenericArg> {
2258 let is_op_or_dot = AssocOp::from_token(&self.token)
2260 if let AssocOp::Greater
2262 | AssocOp::ShiftRight
2263 | AssocOp::GreaterEqual
2264 // Don't recover from `foo::<bar = baz>`, because this could be an attempt to
2265 // assign a value to a defaulted generic parameter.
2267 | AssocOp::AssignOp(_) = op
2275 || self.token.kind == TokenKind::Dot;
2276 // This will be true when a trait object type `Foo +` or a path which was a `const fn` with
2277 // type params has been parsed.
2279 matches!(self.prev_token.kind, token::BinOp(token::Plus | token::Shr) | token::Gt);
2280 if !is_op_or_dot && !was_op {
2281 // We perform these checks and early return to avoid taking a snapshot unnecessarily.
2284 let snapshot = self.create_snapshot_for_diagnostic();
2288 match self.parse_expr_res(Restrictions::CONST_EXPR, None) {
2290 // Find a mistake like `MyTrait<Assoc == S::Assoc>`.
2291 if token::EqEq == snapshot.token.kind {
2292 err.span_suggestion(
2293 snapshot.token.span,
2294 "if you meant to use an associated type binding, replace `==` with `=`",
2296 Applicability::MaybeIncorrect,
2298 let value = self.mk_expr_err(start.to(expr.span));
2300 return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
2301 } else if token::Colon == snapshot.token.kind
2302 && expr.span.lo() == snapshot.token.span.hi()
2303 && matches!(expr.kind, ExprKind::Path(..))
2305 // Find a mistake like "foo::var:A".
2306 err.span_suggestion(
2307 snapshot.token.span,
2308 "write a path separator here",
2310 Applicability::MaybeIncorrect,
2313 return Ok(GenericArg::Type(self.mk_ty(start.to(expr.span), TyKind::Err)));
2314 } else if token::Comma == self.token.kind || self.token.kind.should_end_const_arg()
2316 // Avoid the following output by checking that we consumed a full const arg:
2317 // help: expressions must be enclosed in braces to be used as const generic
2320 // LL | let sr: Vec<{ (u32, _, _) = vec![] };
2322 return Ok(self.dummy_const_arg_needs_braces(err, start.to(expr.span)));
2329 self.restore_snapshot(snapshot);
2333 /// Creates a dummy const argument, and reports that the expression must be enclosed in braces
2334 pub fn dummy_const_arg_needs_braces(
2336 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2339 err.multipart_suggestion(
2340 "expressions must be enclosed in braces to be used as const generic \
2342 vec![(span.shrink_to_lo(), "{ ".to_string()), (span.shrink_to_hi(), " }".to_string())],
2343 Applicability::MaybeIncorrect,
2345 let value = self.mk_expr_err(span);
2347 GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })
2350 /// Some special error handling for the "top-level" patterns in a match arm,
2351 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2352 pub(crate) fn maybe_recover_colon_colon_in_pat_typo(
2354 mut first_pat: P<Pat>,
2357 if token::Colon != self.token.kind {
2360 if !matches!(first_pat.kind, PatKind::Ident(_, _, None) | PatKind::Path(..))
2361 || !self.look_ahead(1, |token| token.is_ident() && !token.is_reserved_ident())
2365 // The pattern looks like it might be a path with a `::` -> `:` typo:
2366 // `match foo { bar:baz => {} }`
2367 let span = self.token.span;
2368 // We only emit "unexpected `:`" error here if we can successfully parse the
2369 // whole pattern correctly in that case.
2370 let snapshot = self.create_snapshot_for_diagnostic();
2372 // Create error for "unexpected `:`".
2373 match self.expected_one_of_not_found(&[], &[]) {
2375 self.bump(); // Skip the `:`.
2376 match self.parse_pat_no_top_alt(expected) {
2378 // Carry on as if we had not done anything, callers will emit a
2379 // reasonable error.
2382 self.restore_snapshot(snapshot);
2385 // We've parsed the rest of the pattern.
2386 let new_span = first_pat.span.to(pat.span);
2387 let mut show_sugg = false;
2388 // Try to construct a recovered pattern.
2389 match &mut pat.kind {
2390 PatKind::Struct(qself @ None, path, ..)
2391 | PatKind::TupleStruct(qself @ None, path, _)
2392 | PatKind::Path(qself @ None, path) => match &first_pat.kind {
2393 PatKind::Ident(_, ident, _) => {
2394 path.segments.insert(0, PathSegment::from_ident(*ident));
2395 path.span = new_span;
2399 PatKind::Path(old_qself, old_path) => {
2400 path.segments = old_path
2404 .chain(take(&mut path.segments))
2406 path.span = new_span;
2407 *qself = old_qself.clone();
2413 PatKind::Ident(BindingAnnotation::NONE, ident, None) => {
2414 match &first_pat.kind {
2415 PatKind::Ident(_, old_ident, _) => {
2416 let path = PatKind::Path(
2420 segments: thin_vec![
2421 PathSegment::from_ident(*old_ident),
2422 PathSegment::from_ident(*ident),
2427 first_pat = self.mk_pat(new_span, path);
2430 PatKind::Path(old_qself, old_path) => {
2431 let mut segments = old_path.segments.clone();
2432 segments.push(PathSegment::from_ident(*ident));
2433 let path = PatKind::Path(
2435 Path { span: new_span, segments, tokens: None },
2437 first_pat = self.mk_pat(new_span, path);
2446 err.span_suggestion(
2448 "maybe write a path separator here",
2450 Applicability::MaybeIncorrect,
2453 first_pat = self.mk_pat(new_span, PatKind::Wild);
2460 // Carry on as if we had not done anything. This should be unreachable.
2461 self.restore_snapshot(snapshot);
2467 pub(crate) fn maybe_recover_unexpected_block_label(&mut self) -> bool {
2468 // Check for `'a : {`
2469 if !(self.check_lifetime()
2470 && self.look_ahead(1, |tok| tok.kind == token::Colon)
2471 && self.look_ahead(2, |tok| tok.kind == token::OpenDelim(Delimiter::Brace)))
2475 let label = self.eat_label().expect("just checked if a label exists");
2476 self.bump(); // eat `:`
2477 let span = label.ident.span.to(self.prev_token.span);
2478 let mut err = self.struct_span_err(span, "block label not supported here");
2479 err.span_label(span, "not supported here");
2480 err.tool_only_span_suggestion(
2481 label.ident.span.until(self.token.span),
2482 "remove this block label",
2484 Applicability::MachineApplicable,
2490 /// Some special error handling for the "top-level" patterns in a match arm,
2491 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2492 pub(crate) fn maybe_recover_unexpected_comma(
2495 rt: CommaRecoveryMode,
2496 ) -> PResult<'a, ()> {
2497 if self.token != token::Comma {
2501 // An unexpected comma after a top-level pattern is a clue that the
2502 // user (perhaps more accustomed to some other language) forgot the
2503 // parentheses in what should have been a tuple pattern; return a
2504 // suggestion-enhanced error here rather than choking on the comma later.
2505 let comma_span = self.token.span;
2507 if let Err(err) = self.skip_pat_list() {
2508 // We didn't expect this to work anyway; we just wanted to advance to the
2509 // end of the comma-sequence so we know the span to suggest parenthesizing.
2512 let seq_span = lo.to(self.prev_token.span);
2513 let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
2514 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
2515 err.multipart_suggestion(
2517 "try adding parentheses to match on a tuple{}",
2518 if let CommaRecoveryMode::LikelyTuple = rt { "" } else { "..." },
2521 (seq_span.shrink_to_lo(), "(".to_string()),
2522 (seq_span.shrink_to_hi(), ")".to_string()),
2524 Applicability::MachineApplicable,
2526 if let CommaRecoveryMode::EitherTupleOrPipe = rt {
2527 err.span_suggestion(
2529 "...or a vertical bar to match on multiple alternatives",
2530 seq_snippet.replace(',', " |"),
2531 Applicability::MachineApplicable,
2538 pub(crate) fn maybe_recover_bounds_doubled_colon(&mut self, ty: &Ty) -> PResult<'a, ()> {
2539 let TyKind::Path(qself, path) = &ty.kind else { return Ok(()) };
2540 let qself_position = qself.as_ref().map(|qself| qself.position);
2541 for (i, segments) in path.segments.windows(2).enumerate() {
2542 if qself_position.map(|pos| i < pos).unwrap_or(false) {
2545 if let [a, b] = segments {
2546 let (a_span, b_span) = (a.span(), b.span());
2547 let between_span = a_span.shrink_to_hi().to(b_span.shrink_to_lo());
2548 if self.span_to_snippet(between_span).as_deref() == Ok(":: ") {
2549 return Err(DoubleColonInBound {
2550 span: path.span.shrink_to_hi(),
2551 between: between_span,
2553 .into_diagnostic(&self.sess.span_diagnostic));
2560 pub fn is_diff_marker(&mut self, long_kind: &TokenKind, short_kind: &TokenKind) -> bool {
2561 (0..3).all(|i| self.look_ahead(i, |tok| tok == long_kind))
2562 && self.look_ahead(3, |tok| tok == short_kind)
2565 fn diff_marker(&mut self, long_kind: &TokenKind, short_kind: &TokenKind) -> Option<Span> {
2566 if self.is_diff_marker(long_kind, short_kind) {
2567 let lo = self.token.span;
2571 return Some(lo.to(self.prev_token.span));
2576 pub fn recover_diff_marker(&mut self) {
2577 let Some(start) = self.diff_marker(&TokenKind::BinOp(token::Shl), &TokenKind::Lt) else {
2580 let mut spans = Vec::with_capacity(3);
2582 let mut middlediff3 = None;
2583 let mut middle = None;
2586 if self.token.kind == TokenKind::Eof {
2589 if let Some(span) = self.diff_marker(&TokenKind::OrOr, &TokenKind::BinOp(token::Or)) {
2590 middlediff3 = Some(span);
2592 if let Some(span) = self.diff_marker(&TokenKind::EqEq, &TokenKind::Eq) {
2593 middle = Some(span);
2595 if let Some(span) = self.diff_marker(&TokenKind::BinOp(token::Shr), &TokenKind::Gt) {
2602 let mut err = self.struct_span_err(spans, "encountered diff marker");
2603 err.span_label(start, "after this is the code before the merge");
2604 if let Some(middle) = middlediff3 {
2605 err.span_label(middle, "");
2607 if let Some(middle) = middle {
2608 err.span_label(middle, "");
2610 if let Some(end) = end {
2611 err.span_label(end, "above this are the incoming code changes");
2614 "if you're having merge conflicts after pulling new code, the top section is the code \
2615 you already had and the bottom section is the remote code",
2618 "if you're in the middle of a rebase, the top section is the code being rebased onto \
2619 and the bottom section is the code coming from the current commit being rebased",
2622 "for an explanation on these markers from the `git` documentation, visit \
2623 <https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging#_checking_out_conflicts>",
2629 /// Parse and throw away a parenthesized comma separated
2630 /// sequence of patterns until `)` is reached.
2631 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
2632 while !self.check(&token::CloseDelim(Delimiter::Parenthesis)) {
2633 self.parse_pat_no_top_alt(None)?;
2634 if !self.eat(&token::Comma) {