1 use super::pat::Expected;
3 BlockMode, CommaRecoveryMode, Parser, PathStyle, Restrictions, SemiColonMode, SeqSep,
4 TokenExpectType, TokenType,
7 use crate::lexer::UnmatchedBrace;
10 use rustc_ast::token::{self, Delimiter, Lit, LitKind, TokenKind};
11 use rustc_ast::util::parser::AssocOp;
13 AngleBracketedArg, AngleBracketedArgs, AnonConst, AttrVec, BinOpKind, BindingMode, Block,
14 BlockCheckMode, Expr, ExprKind, GenericArg, Generics, Item, ItemKind, Mutability, Param, Pat,
15 PatKind, Path, PathSegment, QSelf, Ty, TyKind,
17 use rustc_ast_pretty::pprust;
18 use rustc_data_structures::fx::FxHashSet;
20 fluent, Applicability, DiagnosticBuilder, DiagnosticMessage, Handler, MultiSpan, PResult,
22 use rustc_errors::{pluralize, struct_span_err, Diagnostic, EmissionGuarantee, ErrorGuaranteed};
23 use rustc_macros::{SessionDiagnostic, SessionSubdiagnostic};
24 use rustc_span::source_map::Spanned;
25 use rustc_span::symbol::{kw, Ident};
26 use rustc_span::{Span, SpanSnippetError, DUMMY_SP};
27 use std::ops::{Deref, DerefMut};
32 use tracing::{debug, trace};
34 const TURBOFISH_SUGGESTION_STR: &str =
35 "use `::<...>` instead of `<...>` to specify lifetime, type, or const arguments";
37 /// Creates a placeholder argument.
38 pub(super) fn dummy_arg(ident: Ident) -> Param {
40 id: ast::DUMMY_NODE_ID,
41 kind: PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None),
45 let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID, tokens: None };
47 attrs: AttrVec::default(),
48 id: ast::DUMMY_NODE_ID,
52 is_placeholder: false,
63 sp: impl Into<MultiSpan>,
65 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
67 Error::UselessDocComment => {
68 let mut err = struct_span_err!(
72 "found a documentation comment that doesn't document anything",
75 "doc comments must come before what they document, maybe a comment was \
84 pub(super) trait RecoverQPath: Sized + 'static {
85 const PATH_STYLE: PathStyle = PathStyle::Expr;
86 fn to_ty(&self) -> Option<P<Ty>>;
87 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
90 impl RecoverQPath for Ty {
91 const PATH_STYLE: PathStyle = PathStyle::Type;
92 fn to_ty(&self) -> Option<P<Ty>> {
95 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
98 kind: TyKind::Path(qself, path),
99 id: ast::DUMMY_NODE_ID,
105 impl RecoverQPath for Pat {
106 fn to_ty(&self) -> Option<P<Ty>> {
109 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
112 kind: PatKind::Path(qself, path),
113 id: ast::DUMMY_NODE_ID,
119 impl RecoverQPath for Expr {
120 fn to_ty(&self) -> Option<P<Ty>> {
123 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
126 kind: ExprKind::Path(qself, path),
127 attrs: AttrVec::new(),
128 id: ast::DUMMY_NODE_ID,
134 /// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
135 pub(crate) enum ConsumeClosingDelim {
140 #[derive(Clone, Copy)]
141 pub enum AttemptLocalParseRecovery {
146 impl AttemptLocalParseRecovery {
147 pub fn yes(&self) -> bool {
149 AttemptLocalParseRecovery::Yes => true,
150 AttemptLocalParseRecovery::No => false,
154 pub fn no(&self) -> bool {
156 AttemptLocalParseRecovery::Yes => false,
157 AttemptLocalParseRecovery::No => true,
162 /// Information for emitting suggestions and recovering from
163 /// C-style `i++`, `--i`, etc.
164 #[derive(Debug, Copy, Clone)]
165 struct IncDecRecovery {
166 /// Is this increment/decrement its own statement?
167 standalone: IsStandalone,
168 /// Is this an increment or decrement?
170 /// Is this pre- or postfix?
174 /// Is an increment or decrement expression its own statement?
175 #[derive(Debug, Copy, Clone)]
177 /// It's standalone, i.e., its own statement.
179 /// It's a subexpression, i.e., *not* standalone.
181 /// It's maybe standalone; we're not sure.
185 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
188 // FIXME: `i--` recovery isn't implemented yet
193 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
200 fn chr(&self) -> char {
207 fn name(&self) -> &'static str {
209 Self::Inc => "increment",
210 Self::Dec => "decrement",
215 impl std::fmt::Display for UnaryFixity {
216 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218 Self::Pre => write!(f, "prefix"),
219 Self::Post => write!(f, "postfix"),
226 patches: Vec<(Span, String)>,
227 applicability: Applicability,
231 fn emit<G: EmissionGuarantee>(self, err: &mut DiagnosticBuilder<'_, G>) {
232 err.multipart_suggestion(&self.msg, self.patches, self.applicability);
235 /// Overrides individual messages and applicabilities.
236 fn emit_many<G: EmissionGuarantee>(
237 err: &mut DiagnosticBuilder<'_, G>,
239 applicability: Applicability,
240 suggestions: impl Iterator<Item = Self>,
242 err.multipart_suggestions(msg, suggestions.map(|s| s.patches), applicability);
246 #[derive(SessionDiagnostic)]
247 #[error(slug = "parser-maybe-report-ambiguous-plus")]
248 struct AmbiguousPlus {
251 #[suggestion(code = "({sum_ty})")]
255 #[derive(SessionDiagnostic)]
256 #[error(code = "E0178", slug = "parser-maybe-recover-from-bad-type-plus")]
262 pub sub: BadTypePlusSub,
265 #[derive(SessionSubdiagnostic)]
266 pub enum BadTypePlusSub {
268 slug = "parser-add-paren",
269 code = "{sum_with_parens}",
270 applicability = "machine-applicable"
273 sum_with_parens: String,
277 #[label(slug = "parser-forgot-paren")]
282 #[label(slug = "parser-expect-path")]
289 #[derive(SessionDiagnostic)]
290 #[error(slug = "parser-maybe-recover-from-bad-qpath-stage-2")]
291 struct BadQPathStage2 {
293 #[suggestion(applicability = "maybe-incorrect")]
298 #[derive(SessionDiagnostic)]
299 #[error(slug = "parser-incorrect-semicolon")]
300 struct IncorrectSemicolon<'a> {
302 #[suggestion_short(applicability = "machine-applicable")]
305 opt_help: Option<()>,
309 #[derive(SessionDiagnostic)]
310 #[error(slug = "parser-incorrect-use-of-await")]
311 struct IncorrectUseOfAwait {
313 #[suggestion(message = "parentheses-suggestion", applicability = "machine-applicable")]
317 #[derive(SessionDiagnostic)]
318 #[error(slug = "parser-incorrect-use-of-await")]
319 struct IncorrectAwait {
322 #[suggestion(message = "postfix-suggestion", code = "{expr}.await{question_mark}")]
323 sugg_span: (Span, Applicability),
325 question_mark: &'static str,
328 #[derive(SessionDiagnostic)]
329 #[error(slug = "parser-in-in-typo")]
333 #[suggestion(applicability = "machine-applicable")]
337 // SnapshotParser is used to create a snapshot of the parser
338 // without causing duplicate errors being emitted when the `Parser`
340 pub struct SnapshotParser<'a> {
342 unclosed_delims: Vec<UnmatchedBrace>,
345 impl<'a> Deref for SnapshotParser<'a> {
346 type Target = Parser<'a>;
348 fn deref(&self) -> &Self::Target {
353 impl<'a> DerefMut for SnapshotParser<'a> {
354 fn deref_mut(&mut self) -> &mut Self::Target {
359 impl<'a> Parser<'a> {
360 pub(super) fn span_err<S: Into<MultiSpan>>(
364 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
365 err.span_err(sp, self.diagnostic())
368 pub fn struct_span_err<S: Into<MultiSpan>>(
371 m: impl Into<DiagnosticMessage>,
372 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
373 self.sess.span_diagnostic.struct_span_err(sp, m)
376 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: impl Into<DiagnosticMessage>) -> ! {
377 self.sess.span_diagnostic.span_bug(sp, m)
380 pub(super) fn diagnostic(&self) -> &'a Handler {
381 &self.sess.span_diagnostic
384 /// Replace `self` with `snapshot.parser` and extend `unclosed_delims` with `snapshot.unclosed_delims`.
385 /// This is to avoid losing unclosed delims errors `create_snapshot_for_diagnostic` clears.
386 pub(super) fn restore_snapshot(&mut self, snapshot: SnapshotParser<'a>) {
387 *self = snapshot.parser;
388 self.unclosed_delims.extend(snapshot.unclosed_delims.clone());
391 pub fn unclosed_delims(&self) -> &[UnmatchedBrace] {
392 &self.unclosed_delims
395 /// Create a snapshot of the `Parser`.
396 pub fn create_snapshot_for_diagnostic(&self) -> SnapshotParser<'a> {
397 let mut snapshot = self.clone();
398 let unclosed_delims = self.unclosed_delims.clone();
399 // Clear `unclosed_delims` in snapshot to avoid
400 // duplicate errors being emitted when the `Parser`
401 // is dropped (which may or may not happen, depending
402 // if the parsing the snapshot is created for is successful)
403 snapshot.unclosed_delims.clear();
404 SnapshotParser { parser: snapshot, unclosed_delims }
407 pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
408 self.sess.source_map().span_to_snippet(span)
411 pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
412 let mut err = self.struct_span_err(
414 &format!("expected identifier, found {}", super::token_descr(&self.token)),
416 let valid_follow = &[
422 TokenKind::OpenDelim(Delimiter::Brace),
423 TokenKind::OpenDelim(Delimiter::Parenthesis),
424 TokenKind::CloseDelim(Delimiter::Brace),
425 TokenKind::CloseDelim(Delimiter::Parenthesis),
427 match self.token.ident() {
429 if ident.is_raw_guess()
430 && self.look_ahead(1, |t| valid_follow.contains(&t.kind)) =>
432 err.span_suggestion_verbose(
433 ident.span.shrink_to_lo(),
434 &format!("escape `{}` to use it as an identifier", ident.name),
436 Applicability::MaybeIncorrect,
441 if let Some(token_descr) = super::token_descr_opt(&self.token) {
442 err.span_label(self.token.span, format!("expected identifier, found {}", token_descr));
444 err.span_label(self.token.span, "expected identifier");
445 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
450 Applicability::MachineApplicable,
457 pub(super) fn expected_one_of_not_found(
459 edible: &[TokenKind],
460 inedible: &[TokenKind],
461 ) -> PResult<'a, bool /* recovered */> {
462 debug!("expected_one_of_not_found(edible: {:?}, inedible: {:?})", edible, inedible);
463 fn tokens_to_string(tokens: &[TokenType]) -> String {
464 let mut i = tokens.iter();
465 // This might be a sign we need a connect method on `Iterator`.
466 let b = i.next().map_or_else(String::new, |t| t.to_string());
467 i.enumerate().fold(b, |mut b, (i, a)| {
468 if tokens.len() > 2 && i == tokens.len() - 2 {
470 } else if tokens.len() == 2 && i == tokens.len() - 2 {
475 b.push_str(&a.to_string());
480 let mut expected = edible
482 .map(|x| TokenType::Token(x.clone()))
483 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
484 .chain(self.expected_tokens.iter().cloned())
485 .filter_map(|token| {
486 // filter out suggestions which suggest the same token which was found and deemed incorrect
487 fn is_ident_eq_keyword(found: &TokenKind, expected: &TokenType) -> bool {
488 if let TokenKind::Ident(current_sym, _) = found {
489 if let TokenType::Keyword(suggested_sym) = expected {
490 return current_sym == suggested_sym;
495 if token != parser::TokenType::Token(self.token.kind.clone()) {
496 let eq = is_ident_eq_keyword(&self.token.kind, &token);
497 // if the suggestion is a keyword and the found token is an ident,
498 // the content of which are equal to the suggestion's content,
499 // we can remove that suggestion (see the return None statement below)
501 // if this isn't the case however, and the suggestion is a token the
502 // content of which is the same as the found token's, we remove it as well
504 if let TokenType::Token(kind) = &token {
505 if kind == &self.token.kind {
514 .collect::<Vec<_>>();
515 expected.sort_by_cached_key(|x| x.to_string());
518 let sm = self.sess.source_map();
519 let msg = format!("expected `;`, found {}", super::token_descr(&self.token));
520 let appl = Applicability::MachineApplicable;
521 if expected.contains(&TokenType::Token(token::Semi)) {
522 if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
523 // Likely inside a macro, can't provide meaningful suggestions.
524 } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
525 // The current token is in the same line as the prior token, not recoverable.
526 } else if [token::Comma, token::Colon].contains(&self.token.kind)
527 && self.prev_token.kind == token::CloseDelim(Delimiter::Parenthesis)
529 // Likely typo: The current token is on a new line and is expected to be
530 // `.`, `;`, `?`, or an operator after a close delimiter token.
532 // let a = std::process::Command::new("echo")
536 // https://github.com/rust-lang/rust/issues/72253
537 } else if self.look_ahead(1, |t| {
538 t == &token::CloseDelim(Delimiter::Brace)
539 || t.can_begin_expr() && t.kind != token::Colon
540 }) && [token::Comma, token::Colon].contains(&self.token.kind)
542 // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is
543 // either `,` or `:`, and the next token could either start a new statement or is a
544 // block close. For example:
549 let sp = self.prev_token.span;
550 self.struct_span_err(sp, &msg)
551 .span_suggestion_short(sp, "change this to `;`", ";", appl)
554 } else if self.look_ahead(0, |t| {
555 t == &token::CloseDelim(Delimiter::Brace)
556 || (t.can_begin_expr() && t != &token::Semi && t != &token::Pound)
557 // Avoid triggering with too many trailing `#` in raw string.
559 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo())
560 ) && t == &token::Pound)
562 // Missing semicolon typo. This is triggered if the next token could either start a
563 // new statement or is a block close. For example:
567 let sp = self.prev_token.span.shrink_to_hi();
568 self.struct_span_err(sp, &msg)
569 .span_label(self.token.span, "unexpected token")
570 .span_suggestion_short(sp, "add `;` here", ";", appl)
576 let expect = tokens_to_string(&expected);
577 let actual = super::token_descr(&self.token);
578 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
579 let short_expect = if expected.len() > 6 {
580 format!("{} possible tokens", expected.len())
585 format!("expected one of {expect}, found {actual}"),
586 (self.prev_token.span.shrink_to_hi(), format!("expected one of {short_expect}")),
588 } else if expected.is_empty() {
590 format!("unexpected token: {}", actual),
591 (self.prev_token.span, "unexpected token after this".to_string()),
595 format!("expected {expect}, found {actual}"),
596 (self.prev_token.span.shrink_to_hi(), format!("expected {expect}")),
599 self.last_unexpected_token_span = Some(self.token.span);
600 let mut err = self.struct_span_err(self.token.span, &msg_exp);
602 // Add suggestion for a missing closing angle bracket if '>' is included in expected_tokens
603 // there are unclosed angle brackets
604 if self.unmatched_angle_bracket_count > 0
605 && self.token.kind == TokenKind::Eq
606 && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Gt)))
608 err.span_label(self.prev_token.span, "maybe try to close unmatched angle bracket");
611 let sp = if self.token == token::Eof {
612 // This is EOF; don't want to point at the following char, but rather the last token.
617 match self.recover_closing_delimiter(
620 .filter_map(|tt| match tt {
621 TokenType::Token(t) => Some(t.clone()),
624 .collect::<Vec<_>>(),
629 return Ok(recovered);
633 if self.check_too_many_raw_str_terminators(&mut err) {
634 if expected.contains(&TokenType::Token(token::Semi)) && self.eat(&token::Semi) {
642 if self.prev_token.span == DUMMY_SP {
643 // Account for macro context where the previous span might not be
644 // available to avoid incorrect output (#54841).
645 err.span_label(self.token.span, label_exp);
646 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
647 // When the spans are in the same line, it means that the only content between
648 // them is whitespace, point at the found token in that case:
650 // X | () => { syntax error };
651 // | ^^^^^ expected one of 8 possible tokens here
653 // instead of having:
655 // X | () => { syntax error };
656 // | -^^^^^ unexpected token
658 // | expected one of 8 possible tokens here
659 err.span_label(self.token.span, label_exp);
661 err.span_label(sp, label_exp);
662 err.span_label(self.token.span, "unexpected token");
664 self.maybe_annotate_with_ascription(&mut err, false);
668 fn check_too_many_raw_str_terminators(&mut self, err: &mut Diagnostic) -> bool {
669 let sm = self.sess.source_map();
670 match (&self.prev_token.kind, &self.token.kind) {
672 TokenKind::Literal(Lit {
673 kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
677 ) if !sm.is_multiline(
678 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
681 let n_hashes: u8 = *n_hashes;
682 err.set_primary_message("too many `#` when terminating raw string");
683 let str_span = self.prev_token.span;
684 let mut span = self.token.span;
686 while self.token.kind == TokenKind::Pound
687 && !sm.is_multiline(span.shrink_to_hi().until(self.token.span.shrink_to_lo()))
689 span = span.with_hi(self.token.span.hi());
696 &format!("remove the extra `#`{}", pluralize!(count)),
698 Applicability::MachineApplicable,
702 &format!("this raw string started with {n_hashes} `#`{}", pluralize!(n_hashes)),
710 pub fn maybe_suggest_struct_literal(
714 ) -> Option<PResult<'a, P<Block>>> {
715 if self.token.is_ident() && self.look_ahead(1, |t| t == &token::Colon) {
716 // We might be having a struct literal where people forgot to include the path:
720 let mut snapshot = self.create_snapshot_for_diagnostic();
722 Path { segments: vec![], span: self.prev_token.span.shrink_to_lo(), tokens: None };
723 let struct_expr = snapshot.parse_struct_expr(None, path, AttrVec::new(), false);
724 let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No);
725 return Some(match (struct_expr, block_tail) {
726 (Ok(expr), Err(mut err)) => {
727 // We have encountered the following:
732 // fn foo() -> Foo { Path {
736 self.struct_span_err(
738 fluent::parser::struct_literal_body_without_path,
740 .multipart_suggestion(
741 fluent::parser::suggestion,
743 (expr.span.shrink_to_lo(), "{ SomeStruct ".to_string()),
744 (expr.span.shrink_to_hi(), " }".to_string()),
746 Applicability::MaybeIncorrect,
749 self.restore_snapshot(snapshot);
750 let mut tail = self.mk_block(
751 vec![self.mk_stmt_err(expr.span)],
753 lo.to(self.prev_token.span),
755 tail.could_be_bare_literal = true;
758 (Err(err), Ok(tail)) => {
759 // We have a block tail that contains a somehow valid type ascription expr.
763 (Err(snapshot_err), Err(err)) => {
764 // We don't know what went wrong, emit the normal error.
765 snapshot_err.cancel();
766 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
769 (Ok(_), Ok(mut tail)) => {
770 tail.could_be_bare_literal = true;
778 pub fn maybe_annotate_with_ascription(
780 err: &mut Diagnostic,
781 maybe_expected_semicolon: bool,
783 if let Some((sp, likely_path)) = self.last_type_ascription.take() {
784 let sm = self.sess.source_map();
785 let next_pos = sm.lookup_char_pos(self.token.span.lo());
786 let op_pos = sm.lookup_char_pos(sp.hi());
788 let allow_unstable = self.sess.unstable_features.is_nightly_build();
793 "maybe write a path separator here",
796 Applicability::MaybeIncorrect
798 Applicability::MachineApplicable
801 self.sess.type_ascription_path_suggestions.borrow_mut().insert(sp);
802 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
805 "try using a semicolon",
807 Applicability::MaybeIncorrect,
809 } else if allow_unstable {
810 err.span_label(sp, "tried to parse a type due to this type ascription");
812 err.span_label(sp, "tried to parse a type due to this");
815 // Give extra information about type ascription only if it's a nightly compiler.
817 "`#![feature(type_ascription)]` lets you annotate an expression with a type: \
821 // Avoid giving too much info when it was likely an unrelated typo.
823 "see issue #23416 <https://github.com/rust-lang/rust/issues/23416> \
824 for more information",
831 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
832 /// passes through any errors encountered. Used for error recovery.
833 pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
835 self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
836 Ok(p.parse_token_tree())
843 /// This function checks if there are trailing angle brackets and produces
844 /// a diagnostic to suggest removing them.
846 /// ```ignore (diagnostic)
847 /// let _ = [1, 2, 3].into_iter().collect::<Vec<usize>>>>();
848 /// ^^ help: remove extra angle brackets
851 /// If `true` is returned, then trailing brackets were recovered, tokens were consumed
852 /// up until one of the tokens in 'end' was encountered, and an error was emitted.
853 pub(super) fn check_trailing_angle_brackets(
855 segment: &PathSegment,
858 // This function is intended to be invoked after parsing a path segment where there are two
861 // 1. A specific token is expected after the path segment.
862 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
863 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
864 // 2. No specific token is expected after the path segment.
865 // eg. `x.foo` (field access)
867 // This function is called after parsing `.foo` and before parsing the token `end` (if
868 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
871 // We only care about trailing angle brackets if we previously parsed angle bracket
872 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
873 // removed in this case:
875 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
877 // This case is particularly tricky as we won't notice it just looking at the tokens -
878 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
879 // have already been parsed):
881 // `x.foo::<u32>>>(3)`
882 let parsed_angle_bracket_args =
883 segment.args.as_ref().map_or(false, |args| args.is_angle_bracketed());
886 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
887 parsed_angle_bracket_args,
889 if !parsed_angle_bracket_args {
893 // Keep the span at the start so we can highlight the sequence of `>` characters to be
895 let lo = self.token.span;
897 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
898 // (since we might have the field access case and the characters we're eating are
899 // actual operators and not trailing characters - ie `x.foo >> 3`).
900 let mut position = 0;
902 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
903 // many of each (so we can correctly pluralize our error messages) and continue to
905 let mut number_of_shr = 0;
906 let mut number_of_gt = 0;
907 while self.look_ahead(position, |t| {
908 trace!("check_trailing_angle_brackets: t={:?}", t);
909 if *t == token::BinOp(token::BinOpToken::Shr) {
912 } else if *t == token::Gt {
922 // If we didn't find any trailing `>` characters, then we have nothing to error about.
924 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
925 number_of_gt, number_of_shr,
927 if number_of_gt < 1 && number_of_shr < 1 {
931 // Finally, double check that we have our end token as otherwise this is the
933 if self.look_ahead(position, |t| {
934 trace!("check_trailing_angle_brackets: t={:?}", t);
935 end.contains(&&t.kind)
937 // Eat from where we started until the end token so that parsing can continue
938 // as if we didn't have those extra angle brackets.
939 self.eat_to_tokens(end);
940 let span = lo.until(self.token.span);
942 let total_num_of_gt = number_of_gt + number_of_shr * 2;
943 self.struct_span_err(
945 &format!("unmatched angle bracket{}", pluralize!(total_num_of_gt)),
949 &format!("remove extra angle bracket{}", pluralize!(total_num_of_gt)),
951 Applicability::MachineApplicable,
959 /// Check if a method call with an intended turbofish has been written without surrounding
961 pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
962 if token::ModSep == self.token.kind && segment.args.is_none() {
963 let snapshot = self.create_snapshot_for_diagnostic();
965 let lo = self.token.span;
966 match self.parse_angle_args(None) {
968 let span = lo.to(self.prev_token.span);
969 // Detect trailing `>` like in `x.collect::Vec<_>>()`.
970 let mut trailing_span = self.prev_token.span.shrink_to_hi();
971 while self.token.kind == token::BinOp(token::Shr)
972 || self.token.kind == token::Gt
974 trailing_span = trailing_span.to(self.token.span);
977 if self.token.kind == token::OpenDelim(Delimiter::Parenthesis) {
978 // Recover from bad turbofish: `foo.collect::Vec<_>()`.
979 let args = AngleBracketedArgs { args, span }.into();
982 self.struct_span_err(
984 "generic parameters without surrounding angle brackets",
986 .multipart_suggestion(
987 "surround the type parameters with angle brackets",
989 (span.shrink_to_lo(), "<".to_string()),
990 (trailing_span, ">".to_string()),
992 Applicability::MachineApplicable,
996 // This doesn't look like an invalid turbofish, can't recover parse state.
997 self.restore_snapshot(snapshot);
1001 // We couldn't parse generic parameters, unlikely to be a turbofish. Rely on
1002 // generic parse error instead.
1004 self.restore_snapshot(snapshot);
1010 /// When writing a turbofish with multiple type parameters missing the leading `::`, we will
1011 /// encounter a parse error when encountering the first `,`.
1012 pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
1014 mut e: DiagnosticBuilder<'a, ErrorGuaranteed>,
1016 ) -> PResult<'a, ()> {
1017 if let ExprKind::Binary(binop, _, _) = &expr.kind
1018 && let ast::BinOpKind::Lt = binop.node
1019 && self.eat(&token::Comma)
1021 let x = self.parse_seq_to_before_end(
1023 SeqSep::trailing_allowed(token::Comma),
1024 |p| p.parse_generic_arg(None),
1027 Ok((_, _, false)) => {
1028 if self.eat(&token::Gt) {
1029 e.span_suggestion_verbose(
1030 binop.span.shrink_to_lo(),
1031 TURBOFISH_SUGGESTION_STR,
1033 Applicability::MaybeIncorrect,
1036 match self.parse_expr() {
1039 self.mk_expr_err(expr.span.to(self.prev_token.span));
1043 *expr = self.mk_expr_err(expr.span);
1058 /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
1059 /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
1060 /// parenthesising the leftmost comparison.
1061 fn attempt_chained_comparison_suggestion(
1063 err: &mut Diagnostic,
1065 outer_op: &Spanned<AssocOp>,
1066 ) -> bool /* advanced the cursor */ {
1067 if let ExprKind::Binary(op, ref l1, ref r1) = inner_op.kind {
1068 if let ExprKind::Field(_, ident) = l1.kind
1069 && ident.as_str().parse::<i32>().is_err()
1070 && !matches!(r1.kind, ExprKind::Lit(_))
1072 // The parser has encountered `foo.bar<baz`, the likelihood of the turbofish
1073 // suggestion being the only one to apply is high.
1076 let mut enclose = |left: Span, right: Span| {
1077 err.multipart_suggestion(
1078 "parenthesize the comparison",
1080 (left.shrink_to_lo(), "(".to_string()),
1081 (right.shrink_to_hi(), ")".to_string()),
1083 Applicability::MaybeIncorrect,
1086 return match (op.node, &outer_op.node) {
1088 (BinOpKind::Eq, AssocOp::Equal) |
1089 // `x < y < z` and friends.
1090 (BinOpKind::Lt, AssocOp::Less | AssocOp::LessEqual) |
1091 (BinOpKind::Le, AssocOp::LessEqual | AssocOp::Less) |
1092 // `x > y > z` and friends.
1093 (BinOpKind::Gt, AssocOp::Greater | AssocOp::GreaterEqual) |
1094 (BinOpKind::Ge, AssocOp::GreaterEqual | AssocOp::Greater) => {
1095 let expr_to_str = |e: &Expr| {
1096 self.span_to_snippet(e.span)
1097 .unwrap_or_else(|_| pprust::expr_to_string(&e))
1099 err.span_suggestion_verbose(
1100 inner_op.span.shrink_to_hi(),
1101 "split the comparison into two",
1102 format!(" && {}", expr_to_str(&r1)),
1103 Applicability::MaybeIncorrect,
1105 false // Keep the current parse behavior, where the AST is `(x < y) < z`.
1108 (BinOpKind::Eq, AssocOp::Less | AssocOp::LessEqual | AssocOp::Greater | AssocOp::GreaterEqual) => {
1109 // Consume `z`/outer-op-rhs.
1110 let snapshot = self.create_snapshot_for_diagnostic();
1111 match self.parse_expr() {
1113 // We are sure that outer-op-rhs could be consumed, the suggestion is
1115 enclose(r1.span, r2.span);
1120 self.restore_snapshot(snapshot);
1126 (BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge, AssocOp::Equal) => {
1127 let snapshot = self.create_snapshot_for_diagnostic();
1128 // At this point it is always valid to enclose the lhs in parentheses, no
1129 // further checks are necessary.
1130 match self.parse_expr() {
1132 enclose(l1.span, r1.span);
1137 self.restore_snapshot(snapshot);
1148 /// Produces an error if comparison operators are chained (RFC #558).
1149 /// We only need to check the LHS, not the RHS, because all comparison ops have same
1150 /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
1152 /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
1153 /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
1156 /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
1157 /// associative we can infer that we have:
1166 pub(super) fn check_no_chained_comparison(
1169 outer_op: &Spanned<AssocOp>,
1170 ) -> PResult<'a, Option<P<Expr>>> {
1172 outer_op.node.is_comparison(),
1173 "check_no_chained_comparison: {:?} is not comparison",
1178 |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err, AttrVec::new())));
1180 match inner_op.kind {
1181 ExprKind::Binary(op, ref l1, ref r1) if op.node.is_comparison() => {
1182 let mut err = self.struct_span_err(
1183 vec![op.span, self.prev_token.span],
1184 "comparison operators cannot be chained",
1187 let suggest = |err: &mut Diagnostic| {
1188 err.span_suggestion_verbose(
1189 op.span.shrink_to_lo(),
1190 TURBOFISH_SUGGESTION_STR,
1192 Applicability::MaybeIncorrect,
1196 // Include `<` to provide this recommendation even in a case like
1197 // `Foo<Bar<Baz<Qux, ()>>>`
1198 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Less
1199 || outer_op.node == AssocOp::Greater
1201 if outer_op.node == AssocOp::Less {
1202 let snapshot = self.create_snapshot_for_diagnostic();
1204 // So far we have parsed `foo<bar<`, consume the rest of the type args.
1206 [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
1207 self.consume_tts(1, &modifiers);
1209 if !&[token::OpenDelim(Delimiter::Parenthesis), token::ModSep]
1210 .contains(&self.token.kind)
1212 // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
1213 // parser and bail out.
1214 self.restore_snapshot(snapshot);
1217 return if token::ModSep == self.token.kind {
1218 // We have some certainty that this was a bad turbofish at this point.
1222 let snapshot = self.create_snapshot_for_diagnostic();
1223 self.bump(); // `::`
1225 // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
1226 match self.parse_expr() {
1228 // 99% certain that the suggestion is correct, continue parsing.
1230 // FIXME: actually check that the two expressions in the binop are
1231 // paths and resynthesize new fn call expression instead of using
1232 // `ExprKind::Err` placeholder.
1233 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1237 // Not entirely sure now, but we bubble the error up with the
1239 self.restore_snapshot(snapshot);
1243 } else if token::OpenDelim(Delimiter::Parenthesis) == self.token.kind {
1244 // We have high certainty that this was a bad turbofish at this point.
1247 // Consume the fn call arguments.
1248 match self.consume_fn_args() {
1249 Err(()) => Err(err),
1252 // FIXME: actually check that the two expressions in the binop are
1253 // paths and resynthesize new fn call expression instead of using
1254 // `ExprKind::Err` placeholder.
1255 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1259 if !matches!(l1.kind, ExprKind::Lit(_))
1260 && !matches!(r1.kind, ExprKind::Lit(_))
1262 // All we know is that this is `foo < bar >` and *nothing* else. Try to
1263 // be helpful, but don't attempt to recover.
1264 err.help(TURBOFISH_SUGGESTION_STR);
1265 err.help("or use `(...)` if you meant to specify fn arguments");
1268 // If it looks like a genuine attempt to chain operators (as opposed to a
1269 // misformatted turbofish, for instance), suggest a correct form.
1270 if self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op)
1273 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1275 // These cases cause too many knock-down errors, bail out (#61329).
1281 self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1284 return mk_err_expr(self, inner_op.span.to(self.prev_token.span));
1292 fn consume_fn_args(&mut self) -> Result<(), ()> {
1293 let snapshot = self.create_snapshot_for_diagnostic();
1296 // Consume the fn call arguments.
1298 (token::OpenDelim(Delimiter::Parenthesis), 1),
1299 (token::CloseDelim(Delimiter::Parenthesis), -1),
1301 self.consume_tts(1, &modifiers);
1303 if self.token.kind == token::Eof {
1304 // Not entirely sure that what we consumed were fn arguments, rollback.
1305 self.restore_snapshot(snapshot);
1308 // 99% certain that the suggestion is correct, continue parsing.
1313 pub(super) fn maybe_report_ambiguous_plus(&mut self, impl_dyn_multi: bool, ty: &Ty) {
1315 self.sess.emit_err(AmbiguousPlus { sum_ty: pprust::ty_to_string(&ty), span: ty.span });
1319 /// Swift lets users write `Ty?` to mean `Option<Ty>`. Parse the construct and recover from it.
1320 pub(super) fn maybe_recover_from_question_mark(&mut self, ty: P<Ty>) -> P<Ty> {
1321 if self.token == token::Question {
1323 self.struct_span_err(self.prev_token.span, "invalid `?` in type")
1324 .span_label(self.prev_token.span, "`?` is only allowed on expressions, not types")
1325 .multipart_suggestion(
1326 "if you meant to express that the type might not contain a value, use the `Option` wrapper type",
1328 (ty.span.shrink_to_lo(), "Option<".to_string()),
1329 (self.prev_token.span, ">".to_string()),
1331 Applicability::MachineApplicable,
1334 self.mk_ty(ty.span.to(self.prev_token.span), TyKind::Err)
1340 pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> {
1341 // Do not add `+` to expected tokens.
1342 if !self.token.is_like_plus() {
1347 let bounds = self.parse_generic_bounds(None)?;
1348 let sum_span = ty.span.to(self.prev_token.span);
1350 let sub = match ty.kind {
1351 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1352 let sum_with_parens = pprust::to_string(|s| {
1354 s.print_opt_lifetime(lifetime);
1355 s.print_mutability(mut_ty.mutbl, false);
1357 s.print_type(&mut_ty.ty);
1358 s.print_type_bounds(" +", &bounds);
1362 BadTypePlusSub::AddParen { sum_with_parens, span: sum_span }
1364 TyKind::Ptr(..) | TyKind::BareFn(..) => BadTypePlusSub::ForgotParen { span: sum_span },
1365 _ => BadTypePlusSub::ExpectPath { span: sum_span },
1368 self.sess.emit_err(BadTypePlus { ty: pprust::ty_to_string(ty), span: sum_span, sub });
1373 pub(super) fn recover_from_prefix_increment(
1375 operand_expr: P<Expr>,
1378 ) -> PResult<'a, P<Expr>> {
1380 if prev_is_semi { IsStandalone::Standalone } else { IsStandalone::Subexpr };
1381 let kind = IncDecRecovery { standalone, op: IncOrDec::Inc, fixity: UnaryFixity::Pre };
1383 self.recover_from_inc_dec(operand_expr, kind, op_span)
1386 pub(super) fn recover_from_postfix_increment(
1388 operand_expr: P<Expr>,
1390 ) -> PResult<'a, P<Expr>> {
1391 let kind = IncDecRecovery {
1392 standalone: IsStandalone::Maybe,
1394 fixity: UnaryFixity::Post,
1397 self.recover_from_inc_dec(operand_expr, kind, op_span)
1400 fn recover_from_inc_dec(
1403 kind: IncDecRecovery,
1405 ) -> PResult<'a, P<Expr>> {
1406 let mut err = self.struct_span_err(
1408 &format!("Rust has no {} {} operator", kind.fixity, kind.op.name()),
1410 err.span_label(op_span, &format!("not a valid {} operator", kind.fixity));
1412 let help_base_case = |mut err: DiagnosticBuilder<'_, _>, base| {
1413 err.help(&format!("use `{}= 1` instead", kind.op.chr()));
1419 let spans = match kind.fixity {
1420 UnaryFixity::Pre => (op_span, base.span.shrink_to_hi()),
1421 UnaryFixity::Post => (base.span.shrink_to_lo(), op_span),
1424 match kind.standalone {
1425 IsStandalone::Standalone => self.inc_dec_standalone_suggest(kind, spans).emit(&mut err),
1426 IsStandalone::Subexpr => {
1427 let Ok(base_src) = self.span_to_snippet(base.span)
1428 else { return help_base_case(err, base) };
1430 UnaryFixity::Pre => {
1431 self.prefix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1433 UnaryFixity::Post => {
1434 self.postfix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1438 IsStandalone::Maybe => {
1439 let Ok(base_src) = self.span_to_snippet(base.span)
1440 else { return help_base_case(err, base) };
1441 let sugg1 = match kind.fixity {
1442 UnaryFixity::Pre => self.prefix_inc_dec_suggest(base_src, kind, spans),
1443 UnaryFixity::Post => self.postfix_inc_dec_suggest(base_src, kind, spans),
1445 let sugg2 = self.inc_dec_standalone_suggest(kind, spans);
1446 MultiSugg::emit_many(
1448 "use `+= 1` instead",
1449 Applicability::Unspecified,
1450 [sugg1, sugg2].into_iter(),
1457 fn prefix_inc_dec_suggest(
1460 kind: IncDecRecovery,
1461 (pre_span, post_span): (Span, Span),
1464 msg: format!("use `{}= 1` instead", kind.op.chr()),
1466 (pre_span, "{ ".to_string()),
1467 (post_span, format!(" {}= 1; {} }}", kind.op.chr(), base_src)),
1469 applicability: Applicability::MachineApplicable,
1473 fn postfix_inc_dec_suggest(
1476 kind: IncDecRecovery,
1477 (pre_span, post_span): (Span, Span),
1479 let tmp_var = if base_src.trim() == "tmp" { "tmp_" } else { "tmp" };
1481 msg: format!("use `{}= 1` instead", kind.op.chr()),
1483 (pre_span, format!("{{ let {} = ", tmp_var)),
1484 (post_span, format!("; {} {}= 1; {} }}", base_src, kind.op.chr(), tmp_var)),
1486 applicability: Applicability::HasPlaceholders,
1490 fn inc_dec_standalone_suggest(
1492 kind: IncDecRecovery,
1493 (pre_span, post_span): (Span, Span),
1496 msg: format!("use `{}= 1` instead", kind.op.chr()),
1497 patches: vec![(pre_span, String::new()), (post_span, format!(" {}= 1", kind.op.chr()))],
1498 applicability: Applicability::MachineApplicable,
1502 /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
1503 /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
1504 /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
1505 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
1508 ) -> PResult<'a, P<T>> {
1509 // Do not add `::` to expected tokens.
1510 if self.token == token::ModSep {
1511 if let Some(ty) = base.to_ty() {
1512 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1518 /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
1519 /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
1520 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
1524 ) -> PResult<'a, P<T>> {
1525 self.expect(&token::ModSep)?;
1527 let mut path = ast::Path { segments: Vec::new(), span: DUMMY_SP, tokens: None };
1528 self.parse_path_segments(&mut path.segments, T::PATH_STYLE, None)?;
1529 path.span = ty_span.to(self.prev_token.span);
1531 let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
1532 self.sess.emit_err(BadQPathStage2 {
1534 ty: format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
1537 let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
1538 Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path)))
1541 pub fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
1542 if self.token.kind == TokenKind::Semi {
1546 IncorrectSemicolon { span: self.prev_token.span, opt_help: None, name: "" };
1548 if !items.is_empty() {
1549 let previous_item = &items[items.len() - 1];
1550 let previous_item_kind_name = match previous_item.kind {
1551 // Say "braced struct" because tuple-structs and
1552 // braceless-empty-struct declarations do take a semicolon.
1553 ItemKind::Struct(..) => Some("braced struct"),
1554 ItemKind::Enum(..) => Some("enum"),
1555 ItemKind::Trait(..) => Some("trait"),
1556 ItemKind::Union(..) => Some("union"),
1559 if let Some(name) = previous_item_kind_name {
1560 err.opt_help = Some(());
1564 self.sess.emit_err(err);
1571 /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
1572 /// closing delimiter.
1573 pub(super) fn unexpected_try_recover(
1576 ) -> PResult<'a, bool /* recovered */> {
1577 let token_str = pprust::token_kind_to_string(t);
1578 let this_token_str = super::token_descr(&self.token);
1579 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1580 // Point at the end of the macro call when reaching end of macro arguments.
1581 (token::Eof, Some(_)) => {
1582 let sp = self.sess.source_map().next_point(self.prev_token.span);
1585 // We don't want to point at the following span after DUMMY_SP.
1586 // This happens when the parser finds an empty TokenStream.
1587 _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
1588 // EOF, don't want to point at the following char, but rather the last token.
1589 (token::Eof, None) => (self.prev_token.span, self.token.span),
1590 _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
1593 "expected `{}`, found {}",
1595 match (&self.token.kind, self.subparser_name) {
1596 (token::Eof, Some(origin)) => format!("end of {origin}"),
1597 _ => this_token_str,
1600 let mut err = self.struct_span_err(sp, &msg);
1601 let label_exp = format!("expected `{token_str}`");
1602 match self.recover_closing_delimiter(&[t.clone()], err) {
1605 return Ok(recovered);
1608 let sm = self.sess.source_map();
1609 if !sm.is_multiline(prev_sp.until(sp)) {
1610 // When the spans are in the same line, it means that the only content
1611 // between them is whitespace, point only at the found token.
1612 err.span_label(sp, label_exp);
1614 err.span_label(prev_sp, label_exp);
1615 err.span_label(sp, "unexpected token");
1620 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1621 if self.eat(&token::Semi) {
1624 self.expect(&token::Semi).map(drop) // Error unconditionally
1627 /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
1628 /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
1629 pub(super) fn recover_incorrect_await_syntax(
1634 ) -> PResult<'a, P<Expr>> {
1635 let (hi, expr, is_question) = if self.token == token::Not {
1636 // Handle `await!(<expr>)`.
1637 self.recover_await_macro()?
1639 self.recover_await_prefix(await_sp)?
1641 let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
1642 let kind = match expr.kind {
1643 // Avoid knock-down errors as we don't know whether to interpret this as `foo().await?`
1644 // or `foo()?.await` (the very reason we went with postfix syntax 😅).
1645 ExprKind::Try(_) => ExprKind::Err,
1646 _ => ExprKind::Await(expr),
1648 let expr = self.mk_expr(lo.to(sp), kind, attrs);
1649 self.maybe_recover_from_bad_qpath(expr)
1652 fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1653 self.expect(&token::Not)?;
1654 self.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
1655 let expr = self.parse_expr()?;
1656 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
1657 Ok((self.prev_token.span, expr, false))
1660 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
1661 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
1662 let expr = if self.token == token::OpenDelim(Delimiter::Brace) {
1663 // Handle `await { <expr> }`.
1664 // This needs to be handled separately from the next arm to avoid
1665 // interpreting `await { <expr> }?` as `<expr>?.await`.
1666 self.parse_block_expr(None, self.token.span, BlockCheckMode::Default, AttrVec::new())
1670 .map_err(|mut err| {
1671 err.span_label(await_sp, "while parsing this incorrect await expression");
1674 Ok((expr.span, expr, is_question))
1677 fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
1678 let span = lo.to(hi);
1679 let applicability = match expr.kind {
1680 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
1681 _ => Applicability::MachineApplicable,
1684 self.sess.emit_err(IncorrectAwait {
1686 sugg_span: (span, applicability),
1687 expr: self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr)),
1688 question_mark: if is_question { "?" } else { "" },
1694 /// If encountering `future.await()`, consumes and emits an error.
1695 pub(super) fn recover_from_await_method_call(&mut self) {
1696 if self.token == token::OpenDelim(Delimiter::Parenthesis)
1697 && self.look_ahead(1, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
1700 let lo = self.token.span;
1702 let span = lo.to(self.token.span);
1705 self.sess.emit_err(IncorrectUseOfAwait { span });
1709 pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, P<Expr>> {
1710 let is_try = self.token.is_keyword(kw::Try);
1711 let is_questionmark = self.look_ahead(1, |t| t == &token::Not); //check for !
1712 let is_open = self.look_ahead(2, |t| t == &token::OpenDelim(Delimiter::Parenthesis)); //check for (
1714 if is_try && is_questionmark && is_open {
1715 let lo = self.token.span;
1716 self.bump(); //remove try
1717 self.bump(); //remove !
1718 let try_span = lo.to(self.token.span); //we take the try!( span
1719 self.bump(); //remove (
1720 let is_empty = self.token == token::CloseDelim(Delimiter::Parenthesis); //check if the block is empty
1721 self.consume_block(Delimiter::Parenthesis, ConsumeClosingDelim::No); //eat the block
1722 let hi = self.token.span;
1723 self.bump(); //remove )
1724 let mut err = self.struct_span_err(lo.to(hi), "use of deprecated `try` macro");
1725 err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
1726 let prefix = if is_empty { "" } else { "alternatively, " };
1728 err.multipart_suggestion(
1729 "you can use the `?` operator instead",
1730 vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
1731 Applicability::MachineApplicable,
1734 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);
1736 Ok(self.mk_expr_err(lo.to(hi)))
1738 Err(self.expected_expression_found()) // The user isn't trying to invoke the try! macro
1742 /// Recovers a situation like `for ( $pat in $expr )`
1743 /// and suggest writing `for $pat in $expr` instead.
1745 /// This should be called before parsing the `$block`.
1746 pub(super) fn recover_parens_around_for_head(
1749 begin_paren: Option<Span>,
1751 match (&self.token.kind, begin_paren) {
1752 (token::CloseDelim(Delimiter::Parenthesis), Some(begin_par_sp)) => {
1755 self.struct_span_err(
1756 MultiSpan::from_spans(vec![begin_par_sp, self.prev_token.span]),
1757 "unexpected parentheses surrounding `for` loop head",
1759 .multipart_suggestion(
1760 "remove parentheses in `for` loop",
1761 vec![(begin_par_sp, String::new()), (self.prev_token.span, String::new())],
1762 // With e.g. `for (x) in y)` this would replace `(x) in y)`
1763 // with `x) in y)` which is syntactically invalid.
1764 // However, this is prevented before we get here.
1765 Applicability::MachineApplicable,
1769 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1770 pat.and_then(|pat| match pat.kind {
1771 PatKind::Paren(pat) => pat,
1779 pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1780 (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1781 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1782 || self.token.is_ident() &&
1783 matches!(node, ast::ExprKind::Path(..) | ast::ExprKind::Field(..)) &&
1784 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
1785 self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Parenthesis))
1786 || self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Brace)) // `foo:bar {`
1787 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar::<baz`
1788 self.look_ahead(2, |t| t == &token::Lt) &&
1789 self.look_ahead(3, |t| t.is_ident())
1790 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
1791 self.look_ahead(2, |t| t.is_ident())
1792 || self.look_ahead(1, |t| t == &token::ModSep)
1793 && (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
1794 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1797 pub(super) fn recover_seq_parse_error(
1801 result: PResult<'a, P<Expr>>,
1807 // Recover from parse error, callers expect the closing delim to be consumed.
1808 self.consume_block(delim, ConsumeClosingDelim::Yes);
1809 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err, AttrVec::new())
1814 pub(super) fn recover_closing_delimiter(
1816 tokens: &[TokenKind],
1817 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
1818 ) -> PResult<'a, bool> {
1820 // We want to use the last closing delim that would apply.
1821 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1822 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1823 && Some(self.token.span) > unmatched.unclosed_span
1830 // Recover and assume that the detected unclosed delimiter was meant for
1831 // this location. Emit the diagnostic and act as if the delimiter was
1832 // present for the parser's sake.
1834 // Don't attempt to recover from this unclosed delimiter more than once.
1835 let unmatched = self.unclosed_delims.remove(pos);
1836 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1837 if unmatched.found_delim.is_none() {
1838 // We encountered `Eof`, set this fact here to avoid complaining about missing
1839 // `fn main()` when we found place to suggest the closing brace.
1840 *self.sess.reached_eof.borrow_mut() = true;
1843 // We want to suggest the inclusion of the closing delimiter where it makes
1844 // the most sense, which is immediately after the last token:
1849 // | help: `)` may belong here
1851 // unclosed delimiter
1852 if let Some(sp) = unmatched.unclosed_span {
1853 let mut primary_span: Vec<Span> =
1854 err.span.primary_spans().iter().cloned().collect();
1855 primary_span.push(sp);
1856 let mut primary_span: MultiSpan = primary_span.into();
1857 for span_label in err.span.span_labels() {
1858 if let Some(label) = span_label.label {
1859 primary_span.push_span_label(span_label.span, label);
1862 err.set_span(primary_span);
1863 err.span_label(sp, "unclosed delimiter");
1865 // Backticks should be removed to apply suggestions.
1866 let mut delim = delim.to_string();
1867 delim.retain(|c| c != '`');
1868 err.span_suggestion_short(
1869 self.prev_token.span.shrink_to_hi(),
1870 &format!("`{delim}` may belong here"),
1872 Applicability::MaybeIncorrect,
1874 if unmatched.found_delim.is_none() {
1875 // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1876 // errors which would be emitted elsewhere in the parser and let other error
1877 // recovery consume the rest of the file.
1881 self.expected_tokens.clear(); // Reduce the number of errors.
1889 /// Eats tokens until we can be relatively sure we reached the end of the
1890 /// statement. This is something of a best-effort heuristic.
1892 /// We terminate when we find an unmatched `}` (without consuming it).
1893 pub(super) fn recover_stmt(&mut self) {
1894 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1897 /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1898 /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1899 /// approximate -- it can mean we break too early due to macros, but that
1900 /// should only lead to sub-optimal recovery, not inaccurate parsing).
1902 /// If `break_on_block` is `Break`, then we will stop consuming tokens
1903 /// after finding (and consuming) a brace-delimited block.
1904 pub(super) fn recover_stmt_(
1906 break_on_semi: SemiColonMode,
1907 break_on_block: BlockMode,
1909 let mut brace_depth = 0;
1910 let mut bracket_depth = 0;
1911 let mut in_block = false;
1912 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1914 debug!("recover_stmt_ loop {:?}", self.token);
1915 match self.token.kind {
1916 token::OpenDelim(Delimiter::Brace) => {
1919 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1924 token::OpenDelim(Delimiter::Bracket) => {
1928 token::CloseDelim(Delimiter::Brace) => {
1929 if brace_depth == 0 {
1930 debug!("recover_stmt_ return - close delim {:?}", self.token);
1935 if in_block && bracket_depth == 0 && brace_depth == 0 {
1936 debug!("recover_stmt_ return - block end {:?}", self.token);
1940 token::CloseDelim(Delimiter::Bracket) => {
1942 if bracket_depth < 0 {
1948 debug!("recover_stmt_ return - Eof");
1953 if break_on_semi == SemiColonMode::Break
1955 && bracket_depth == 0
1957 debug!("recover_stmt_ return - Semi");
1962 if break_on_semi == SemiColonMode::Comma
1964 && bracket_depth == 0 =>
1966 debug!("recover_stmt_ return - Semi");
1974 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1975 if self.eat_keyword(kw::In) {
1976 // a common typo: `for _ in in bar {}`
1977 self.sess.emit_err(InInTypo {
1978 span: self.prev_token.span,
1979 sugg_span: in_span.until(self.prev_token.span),
1984 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1985 if let token::DocComment(..) = self.token.kind {
1986 self.struct_span_err(
1988 "documentation comments cannot be applied to a function parameter's type",
1990 .span_label(self.token.span, "doc comments are not allowed here")
1993 } else if self.token == token::Pound
1994 && self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Bracket))
1996 let lo = self.token.span;
1997 // Skip every token until next possible arg.
1998 while self.token != token::CloseDelim(Delimiter::Bracket) {
2001 let sp = lo.to(self.token.span);
2003 self.struct_span_err(sp, "attributes cannot be applied to a function parameter's type")
2004 .span_label(sp, "attributes are not allowed here")
2009 pub(super) fn parameter_without_type(
2011 err: &mut Diagnostic,
2015 ) -> Option<Ident> {
2016 // If we find a pattern followed by an identifier, it could be an (incorrect)
2017 // C-style parameter declaration.
2018 if self.check_ident()
2019 && self.look_ahead(1, |t| {
2020 *t == token::Comma || *t == token::CloseDelim(Delimiter::Parenthesis)
2023 // `fn foo(String s) {}`
2024 let ident = self.parse_ident().unwrap();
2025 let span = pat.span.with_hi(ident.span.hi());
2027 err.span_suggestion(
2029 "declare the type after the parameter binding",
2030 "<identifier>: <type>",
2031 Applicability::HasPlaceholders,
2034 } else if require_name
2035 && (self.token == token::Comma
2036 || self.token == token::Lt
2037 || self.token == token::CloseDelim(Delimiter::Parenthesis))
2039 let rfc_note = "anonymous parameters are removed in the 2018 edition (see RFC 1685)";
2041 let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
2043 PatKind::Ident(_, ident, _) => (
2046 ": TypeName".to_string(),
2048 pat.span.shrink_to_lo(),
2049 pat.span.shrink_to_hi(),
2050 pat.span.shrink_to_lo(),
2052 // Also catches `fn foo(&a)`.
2053 PatKind::Ref(ref inner_pat, mutab)
2054 if matches!(inner_pat.clone().into_inner().kind, PatKind::Ident(..)) =>
2056 match inner_pat.clone().into_inner().kind {
2057 PatKind::Ident(_, ident, _) => {
2058 let mutab = mutab.prefix_str();
2062 format!("{ident}: &{mutab}TypeName"),
2064 pat.span.shrink_to_lo(),
2066 pat.span.shrink_to_lo(),
2069 _ => unreachable!(),
2073 // Otherwise, try to get a type and emit a suggestion.
2074 if let Some(ty) = pat.to_ty() {
2075 err.span_suggestion_verbose(
2077 "explicitly ignore the parameter name",
2078 format!("_: {}", pprust::ty_to_string(&ty)),
2079 Applicability::MachineApplicable,
2088 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
2090 err.span_suggestion(
2092 "if this is a `self` type, give it a parameter name",
2094 Applicability::MaybeIncorrect,
2097 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
2098 // `fn foo(HashMap: TypeName<u32>)`.
2099 if self.token != token::Lt {
2100 err.span_suggestion(
2102 "if this is a parameter name, give it a type",
2104 Applicability::HasPlaceholders,
2107 err.span_suggestion(
2109 "if this is a type, explicitly ignore the parameter name",
2111 Applicability::MachineApplicable,
2115 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
2116 return if self.token == token::Lt { None } else { Some(ident) };
2121 pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
2122 let pat = self.parse_pat_no_top_alt(Some("argument name"))?;
2123 self.expect(&token::Colon)?;
2124 let ty = self.parse_ty()?;
2130 "patterns aren't allowed in methods without bodies",
2132 .span_suggestion_short(
2134 "give this argument a name or use an underscore to ignore it",
2136 Applicability::MachineApplicable,
2140 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2142 P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID, tokens: None });
2146 pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
2147 let sp = param.pat.span;
2148 param.ty.kind = TyKind::Err;
2149 self.struct_span_err(sp, "unexpected `self` parameter in function")
2150 .span_label(sp, "must be the first parameter of an associated function")
2155 pub(super) fn consume_block(&mut self, delim: Delimiter, consume_close: ConsumeClosingDelim) {
2156 let mut brace_depth = 0;
2158 if self.eat(&token::OpenDelim(delim)) {
2160 } else if self.check(&token::CloseDelim(delim)) {
2161 if brace_depth == 0 {
2162 if let ConsumeClosingDelim::Yes = consume_close {
2163 // Some of the callers of this method expect to be able to parse the
2164 // closing delimiter themselves, so we leave it alone. Otherwise we advance
2174 } else if self.token == token::Eof {
2182 pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2183 let (span, msg) = match (&self.token.kind, self.subparser_name) {
2184 (&token::Eof, Some(origin)) => {
2185 let sp = self.sess.source_map().next_point(self.prev_token.span);
2186 (sp, format!("expected expression, found end of {origin}"))
2190 format!("expected expression, found {}", super::token_descr(&self.token),),
2193 let mut err = self.struct_span_err(span, &msg);
2194 let sp = self.sess.source_map().start_point(self.token.span);
2195 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
2196 self.sess.expr_parentheses_needed(&mut err, *sp);
2198 err.span_label(span, "expected expression");
2204 mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
2205 // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
2206 modifier: &[(token::TokenKind, i64)],
2209 if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
2212 if self.token.kind == token::Eof {
2219 /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
2221 /// This is necessary because at this point we don't know whether we parsed a function with
2222 /// anonymous parameters or a function with names but no types. In order to minimize
2223 /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
2224 /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
2225 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
2226 /// we deduplicate them to not complain about duplicated parameter names.
2227 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
2228 let mut seen_inputs = FxHashSet::default();
2229 for input in fn_inputs.iter_mut() {
2230 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
2231 (&input.pat.kind, &input.ty.kind)
2237 if let Some(ident) = opt_ident {
2238 if seen_inputs.contains(&ident) {
2239 input.pat.kind = PatKind::Wild;
2241 seen_inputs.insert(ident);
2246 /// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
2247 /// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
2248 /// like the user has forgotten them.
2249 pub fn handle_ambiguous_unbraced_const_arg(
2251 args: &mut Vec<AngleBracketedArg>,
2252 ) -> PResult<'a, bool> {
2253 // If we haven't encountered a closing `>`, then the argument is malformed.
2254 // It's likely that the user has written a const expression without enclosing it
2255 // in braces, so we try to recover here.
2256 let arg = args.pop().unwrap();
2257 // FIXME: for some reason using `unexpected` or `expected_one_of_not_found` has
2258 // adverse side-effects to subsequent errors and seems to advance the parser.
2259 // We are causing this error here exclusively in case that a `const` expression
2260 // could be recovered from the current parser state, even if followed by more
2261 // arguments after a comma.
2262 let mut err = self.struct_span_err(
2264 &format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
2266 err.span_label(self.token.span, "expected one of `,` or `>`");
2267 match self.recover_const_arg(arg.span(), err) {
2269 args.push(AngleBracketedArg::Arg(arg));
2270 if self.eat(&token::Comma) {
2271 return Ok(true); // Continue
2276 // We will emit a more generic error later.
2280 return Ok(false); // Don't continue.
2283 /// Attempt to parse a generic const argument that has not been enclosed in braces.
2284 /// There are a limited number of expressions that are permitted without being encoded
2287 /// - Single-segment paths (i.e. standalone generic const parameters).
2288 /// All other expressions that can be parsed will emit an error suggesting the expression be
2289 /// wrapped in braces.
2290 pub fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
2291 let start = self.token.span;
2292 let expr = self.parse_expr_res(Restrictions::CONST_EXPR, None).map_err(|mut err| {
2294 start.shrink_to_lo(),
2295 "while parsing a const generic argument starting here",
2299 if !self.expr_is_valid_const_arg(&expr) {
2300 self.struct_span_err(
2302 "expressions must be enclosed in braces to be used as const generic \
2305 .multipart_suggestion(
2306 "enclose the `const` expression in braces",
2308 (expr.span.shrink_to_lo(), "{ ".to_string()),
2309 (expr.span.shrink_to_hi(), " }".to_string()),
2311 Applicability::MachineApplicable,
2318 fn recover_const_param_decl(&mut self, ty_generics: Option<&Generics>) -> Option<GenericArg> {
2319 let snapshot = self.create_snapshot_for_diagnostic();
2320 let param = match self.parse_const_param(vec![]) {
2324 self.restore_snapshot(snapshot);
2329 self.struct_span_err(param.span(), "unexpected `const` parameter declaration");
2330 err.span_label(param.span(), "expected a `const` expression, not a parameter declaration");
2331 if let (Some(generics), Ok(snippet)) =
2332 (ty_generics, self.sess.source_map().span_to_snippet(param.span()))
2334 let (span, sugg) = match &generics.params[..] {
2335 [] => (generics.span, format!("<{snippet}>")),
2336 [.., generic] => (generic.span().shrink_to_hi(), format!(", {snippet}")),
2338 err.multipart_suggestion(
2339 "`const` parameters must be declared for the `impl`",
2340 vec![(span, sugg), (param.span(), param.ident.to_string())],
2341 Applicability::MachineApplicable,
2344 let value = self.mk_expr_err(param.span());
2346 Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }))
2349 pub fn recover_const_param_declaration(
2351 ty_generics: Option<&Generics>,
2352 ) -> PResult<'a, Option<GenericArg>> {
2353 // We have to check for a few different cases.
2354 if let Some(arg) = self.recover_const_param_decl(ty_generics) {
2355 return Ok(Some(arg));
2358 // We haven't consumed `const` yet.
2359 let start = self.token.span;
2360 self.bump(); // `const`
2362 // Detect and recover from the old, pre-RFC2000 syntax for const generics.
2364 .struct_span_err(start, "expected lifetime, type, or constant, found keyword `const`");
2365 if self.check_const_arg() {
2366 err.span_suggestion_verbose(
2367 start.until(self.token.span),
2368 "the `const` keyword is only needed in the definition of the type",
2370 Applicability::MaybeIncorrect,
2373 Ok(Some(GenericArg::Const(self.parse_const_arg()?)))
2375 let after_kw_const = self.token.span;
2376 self.recover_const_arg(after_kw_const, err).map(Some)
2380 /// Try to recover from possible generic const argument without `{` and `}`.
2382 /// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
2383 /// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
2384 /// if we think that that the resulting expression would be well formed.
2385 pub fn recover_const_arg(
2388 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2389 ) -> PResult<'a, GenericArg> {
2390 let is_op_or_dot = AssocOp::from_token(&self.token)
2392 if let AssocOp::Greater
2394 | AssocOp::ShiftRight
2395 | AssocOp::GreaterEqual
2396 // Don't recover from `foo::<bar = baz>`, because this could be an attempt to
2397 // assign a value to a defaulted generic parameter.
2399 | AssocOp::AssignOp(_) = op
2407 || self.token.kind == TokenKind::Dot;
2408 // This will be true when a trait object type `Foo +` or a path which was a `const fn` with
2409 // type params has been parsed.
2411 matches!(self.prev_token.kind, token::BinOp(token::Plus | token::Shr) | token::Gt);
2412 if !is_op_or_dot && !was_op {
2413 // We perform these checks and early return to avoid taking a snapshot unnecessarily.
2416 let snapshot = self.create_snapshot_for_diagnostic();
2420 match self.parse_expr_res(Restrictions::CONST_EXPR, None) {
2422 // Find a mistake like `MyTrait<Assoc == S::Assoc>`.
2423 if token::EqEq == snapshot.token.kind {
2424 err.span_suggestion(
2425 snapshot.token.span,
2426 "if you meant to use an associated type binding, replace `==` with `=`",
2428 Applicability::MaybeIncorrect,
2430 let value = self.mk_expr_err(start.to(expr.span));
2432 return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
2433 } else if token::Colon == snapshot.token.kind
2434 && expr.span.lo() == snapshot.token.span.hi()
2435 && matches!(expr.kind, ExprKind::Path(..))
2437 // Find a mistake like "foo::var:A".
2438 err.span_suggestion(
2439 snapshot.token.span,
2440 "write a path separator here",
2442 Applicability::MaybeIncorrect,
2445 return Ok(GenericArg::Type(self.mk_ty(start.to(expr.span), TyKind::Err)));
2446 } else if token::Comma == self.token.kind || self.token.kind.should_end_const_arg()
2448 // Avoid the following output by checking that we consumed a full const arg:
2449 // help: expressions must be enclosed in braces to be used as const generic
2452 // LL | let sr: Vec<{ (u32, _, _) = vec![] };
2454 return Ok(self.dummy_const_arg_needs_braces(err, start.to(expr.span)));
2461 self.restore_snapshot(snapshot);
2465 /// Creates a dummy const argument, and reports that the expression must be enclosed in braces
2466 pub fn dummy_const_arg_needs_braces(
2468 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2471 err.multipart_suggestion(
2472 "expressions must be enclosed in braces to be used as const generic \
2474 vec![(span.shrink_to_lo(), "{ ".to_string()), (span.shrink_to_hi(), " }".to_string())],
2475 Applicability::MaybeIncorrect,
2477 let value = self.mk_expr_err(span);
2479 GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })
2482 /// Get the diagnostics for the cases where `move async` is found.
2484 /// `move_async_span` starts at the 'm' of the move keyword and ends with the 'c' of the async keyword
2485 pub(super) fn incorrect_move_async_order_found(
2487 move_async_span: Span,
2488 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2490 self.struct_span_err(move_async_span, "the order of `move` and `async` is incorrect");
2491 err.span_suggestion_verbose(
2493 "try switching the order",
2495 Applicability::MaybeIncorrect,
2500 /// Some special error handling for the "top-level" patterns in a match arm,
2501 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2502 pub(crate) fn maybe_recover_colon_colon_in_pat_typo(
2504 mut first_pat: P<Pat>,
2507 if token::Colon != self.token.kind {
2510 if !matches!(first_pat.kind, PatKind::Ident(_, _, None) | PatKind::Path(..))
2511 || !self.look_ahead(1, |token| token.is_ident() && !token.is_reserved_ident())
2515 // The pattern looks like it might be a path with a `::` -> `:` typo:
2516 // `match foo { bar:baz => {} }`
2517 let span = self.token.span;
2518 // We only emit "unexpected `:`" error here if we can successfully parse the
2519 // whole pattern correctly in that case.
2520 let snapshot = self.create_snapshot_for_diagnostic();
2522 // Create error for "unexpected `:`".
2523 match self.expected_one_of_not_found(&[], &[]) {
2525 self.bump(); // Skip the `:`.
2526 match self.parse_pat_no_top_alt(expected) {
2528 // Carry on as if we had not done anything, callers will emit a
2529 // reasonable error.
2532 self.restore_snapshot(snapshot);
2535 // We've parsed the rest of the pattern.
2536 let new_span = first_pat.span.to(pat.span);
2537 let mut show_sugg = false;
2538 // Try to construct a recovered pattern.
2539 match &mut pat.kind {
2540 PatKind::Struct(qself @ None, path, ..)
2541 | PatKind::TupleStruct(qself @ None, path, _)
2542 | PatKind::Path(qself @ None, path) => match &first_pat.kind {
2543 PatKind::Ident(_, ident, _) => {
2544 path.segments.insert(0, PathSegment::from_ident(*ident));
2545 path.span = new_span;
2549 PatKind::Path(old_qself, old_path) => {
2550 path.segments = old_path
2554 .chain(take(&mut path.segments))
2556 path.span = new_span;
2557 *qself = old_qself.clone();
2563 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
2564 match &first_pat.kind {
2565 PatKind::Ident(_, old_ident, _) => {
2566 let path = PatKind::Path(
2571 PathSegment::from_ident(*old_ident),
2572 PathSegment::from_ident(*ident),
2577 first_pat = self.mk_pat(new_span, path);
2580 PatKind::Path(old_qself, old_path) => {
2581 let mut segments = old_path.segments.clone();
2582 segments.push(PathSegment::from_ident(*ident));
2583 let path = PatKind::Path(
2585 Path { span: new_span, segments, tokens: None },
2587 first_pat = self.mk_pat(new_span, path);
2596 err.span_suggestion(
2598 "maybe write a path separator here",
2600 Applicability::MaybeIncorrect,
2603 first_pat = self.mk_pat(new_span, PatKind::Wild);
2610 // Carry on as if we had not done anything. This should be unreachable.
2611 self.restore_snapshot(snapshot);
2617 pub(crate) fn maybe_recover_unexpected_block_label(&mut self) -> bool {
2618 let Some(label) = self.eat_label().filter(|_| {
2619 self.eat(&token::Colon) && self.token.kind == token::OpenDelim(Delimiter::Brace)
2623 let span = label.ident.span.to(self.prev_token.span);
2624 let mut err = self.struct_span_err(span, "block label not supported here");
2625 err.span_label(span, "not supported here");
2626 err.tool_only_span_suggestion(
2627 label.ident.span.until(self.token.span),
2628 "remove this block label",
2630 Applicability::MachineApplicable,
2636 /// Some special error handling for the "top-level" patterns in a match arm,
2637 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2638 pub(crate) fn maybe_recover_unexpected_comma(
2641 rt: CommaRecoveryMode,
2642 ) -> PResult<'a, ()> {
2643 if self.token != token::Comma {
2647 // An unexpected comma after a top-level pattern is a clue that the
2648 // user (perhaps more accustomed to some other language) forgot the
2649 // parentheses in what should have been a tuple pattern; return a
2650 // suggestion-enhanced error here rather than choking on the comma later.
2651 let comma_span = self.token.span;
2653 if let Err(err) = self.skip_pat_list() {
2654 // We didn't expect this to work anyway; we just wanted to advance to the
2655 // end of the comma-sequence so we know the span to suggest parenthesizing.
2658 let seq_span = lo.to(self.prev_token.span);
2659 let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
2660 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
2661 err.multipart_suggestion(
2663 "try adding parentheses to match on a tuple{}",
2664 if let CommaRecoveryMode::LikelyTuple = rt { "" } else { "..." },
2667 (seq_span.shrink_to_lo(), "(".to_string()),
2668 (seq_span.shrink_to_hi(), ")".to_string()),
2670 Applicability::MachineApplicable,
2672 if let CommaRecoveryMode::EitherTupleOrPipe = rt {
2673 err.span_suggestion(
2675 "...or a vertical bar to match on multiple alternatives",
2676 seq_snippet.replace(',', " |"),
2677 Applicability::MachineApplicable,
2684 pub(crate) fn maybe_recover_bounds_doubled_colon(&mut self, ty: &Ty) -> PResult<'a, ()> {
2685 let TyKind::Path(qself, path) = &ty.kind else { return Ok(()) };
2686 let qself_position = qself.as_ref().map(|qself| qself.position);
2687 for (i, segments) in path.segments.windows(2).enumerate() {
2688 if qself_position.map(|pos| i < pos).unwrap_or(false) {
2691 if let [a, b] = segments {
2692 let (a_span, b_span) = (a.span(), b.span());
2693 let between_span = a_span.shrink_to_hi().to(b_span.shrink_to_lo());
2694 if self.span_to_snippet(between_span).as_ref().map(|a| &a[..]) == Ok(":: ") {
2695 let mut err = self.struct_span_err(
2696 path.span.shrink_to_hi(),
2697 "expected `:` followed by trait or lifetime",
2699 err.span_suggestion(
2703 Applicability::MachineApplicable,
2712 /// Parse and throw away a parenthesized comma separated
2713 /// sequence of patterns until `)` is reached.
2714 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
2715 while !self.check(&token::CloseDelim(Delimiter::Parenthesis)) {
2716 self.parse_pat_no_top_alt(None)?;
2717 if !self.eat(&token::Comma) {