1 use super::pat::Expected;
2 use super::ty::{AllowPlus, RecoverQuestionMark};
4 BlockMode, CommaRecoveryMode, Parser, PathStyle, RecoverColon, RecoverComma, Restrictions,
5 SemiColonMode, SeqSep, TokenExpectType, TokenType,
8 use crate::lexer::UnmatchedBrace;
10 use rustc_ast::ptr::P;
11 use rustc_ast::token::{self, Lit, LitKind, TokenKind};
12 use rustc_ast::util::parser::AssocOp;
14 AngleBracketedArg, AngleBracketedArgs, AnonConst, AttrVec, BinOpKind, BindingMode, Block,
15 BlockCheckMode, Expr, ExprKind, GenericArg, Generics, Item, ItemKind, Mutability, Param, Pat,
16 PatKind, Path, PathSegment, QSelf, Ty, TyKind,
18 use rustc_ast_pretty::pprust;
19 use rustc_data_structures::fx::FxHashSet;
20 use rustc_errors::{pluralize, struct_span_err, Diagnostic, EmissionGuarantee, ErrorGuaranteed};
22 Applicability, DiagnosticBuilder, DiagnosticMessage, Handler, MultiSpan, PResult,
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};
31 use tracing::{debug, trace};
33 const TURBOFISH_SUGGESTION_STR: &str =
34 "use `::<...>` instead of `<...>` to specify lifetime, type, or const arguments";
36 /// Creates a placeholder argument.
37 pub(super) fn dummy_arg(ident: Ident) -> Param {
39 id: ast::DUMMY_NODE_ID,
40 kind: PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None),
44 let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID, tokens: None };
46 attrs: AttrVec::default(),
47 id: ast::DUMMY_NODE_ID,
51 is_placeholder: false,
62 sp: impl Into<MultiSpan>,
64 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
66 Error::UselessDocComment => {
67 let mut err = struct_span_err!(
71 "found a documentation comment that doesn't document anything",
74 "doc comments must come before what they document, maybe a comment was \
83 pub(super) trait RecoverQPath: Sized + 'static {
84 const PATH_STYLE: PathStyle = PathStyle::Expr;
85 fn to_ty(&self) -> Option<P<Ty>>;
86 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
89 impl RecoverQPath for Ty {
90 const PATH_STYLE: PathStyle = PathStyle::Type;
91 fn to_ty(&self) -> Option<P<Ty>> {
94 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
97 kind: TyKind::Path(qself, path),
98 id: ast::DUMMY_NODE_ID,
104 impl RecoverQPath for Pat {
105 fn to_ty(&self) -> Option<P<Ty>> {
108 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
111 kind: PatKind::Path(qself, path),
112 id: ast::DUMMY_NODE_ID,
118 impl RecoverQPath for Expr {
119 fn to_ty(&self) -> Option<P<Ty>> {
122 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
125 kind: ExprKind::Path(qself, path),
126 attrs: AttrVec::new(),
127 id: ast::DUMMY_NODE_ID,
133 /// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
134 crate enum ConsumeClosingDelim {
139 #[derive(Clone, Copy)]
140 pub enum AttemptLocalParseRecovery {
145 impl AttemptLocalParseRecovery {
146 pub fn yes(&self) -> bool {
148 AttemptLocalParseRecovery::Yes => true,
149 AttemptLocalParseRecovery::No => false,
153 pub fn no(&self) -> bool {
155 AttemptLocalParseRecovery::Yes => false,
156 AttemptLocalParseRecovery::No => true,
161 /// Information for emitting suggestions and recovering from
162 /// C-style `i++`, `--i`, etc.
163 #[derive(Debug, Copy, Clone)]
164 struct IncDecRecovery {
165 /// Is this increment/decrement its own statement?
166 standalone: IsStandalone,
167 /// Is this an increment or decrement?
169 /// Is this pre- or postfix?
173 /// Is an increment or decrement expression its own statement?
174 #[derive(Debug, Copy, Clone)]
176 /// It's standalone, i.e., its own statement.
178 /// It's a subexpression, i.e., *not* standalone.
180 /// It's maybe standalone; we're not sure.
184 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
187 // FIXME: `i--` recovery isn't implemented yet
192 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
199 fn chr(&self) -> char {
206 fn name(&self) -> &'static str {
208 Self::Inc => "increment",
209 Self::Dec => "decrement",
214 impl std::fmt::Display for UnaryFixity {
215 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
217 Self::Pre => write!(f, "prefix"),
218 Self::Post => write!(f, "postfix"),
225 patches: Vec<(Span, String)>,
226 applicability: Applicability,
230 fn emit<G: EmissionGuarantee>(self, err: &mut DiagnosticBuilder<'_, G>) {
231 err.multipart_suggestion(&self.msg, self.patches, self.applicability);
234 /// Overrides individual messages and applicabilities.
235 fn emit_many<G: EmissionGuarantee>(
236 err: &mut DiagnosticBuilder<'_, G>,
238 applicability: Applicability,
239 suggestions: impl Iterator<Item = Self>,
241 err.multipart_suggestions(msg, suggestions.map(|s| s.patches), applicability);
244 // SnapshotParser is used to create a snapshot of the parser
245 // without causing duplicate errors being emitted when the `Parser`
247 pub(super) struct SnapshotParser<'a> {
249 unclosed_delims: Vec<UnmatchedBrace>,
252 impl<'a> Deref for SnapshotParser<'a> {
253 type Target = Parser<'a>;
255 fn deref(&self) -> &Self::Target {
260 impl<'a> DerefMut for SnapshotParser<'a> {
261 fn deref_mut(&mut self) -> &mut Self::Target {
266 impl<'a> Parser<'a> {
267 pub(super) fn span_err<S: Into<MultiSpan>>(
271 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
272 err.span_err(sp, self.diagnostic())
275 pub fn struct_span_err<S: Into<MultiSpan>>(
278 m: impl Into<DiagnosticMessage>,
279 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
280 self.sess.span_diagnostic.struct_span_err(sp, m)
283 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: impl Into<DiagnosticMessage>) -> ! {
284 self.sess.span_diagnostic.span_bug(sp, m)
287 pub(super) fn diagnostic(&self) -> &'a Handler {
288 &self.sess.span_diagnostic
291 /// Replace `self` with `snapshot.parser` and extend `unclosed_delims` with `snapshot.unclosed_delims`.
292 /// This is to avoid losing unclosed delims errors `create_snapshot_for_diagnostic` clears.
293 pub(super) fn restore_snapshot(&mut self, snapshot: SnapshotParser<'a>) {
294 *self = snapshot.parser;
295 self.unclosed_delims.extend(snapshot.unclosed_delims.clone());
298 pub fn unclosed_delims(&self) -> &[UnmatchedBrace] {
299 &self.unclosed_delims
302 /// Create a snapshot of the `Parser`.
303 pub(super) fn create_snapshot_for_diagnostic(&self) -> SnapshotParser<'a> {
304 let mut snapshot = self.clone();
305 let unclosed_delims = self.unclosed_delims.clone();
306 // Clear `unclosed_delims` in snapshot to avoid
307 // duplicate errors being emitted when the `Parser`
308 // is dropped (which may or may not happen, depending
309 // if the parsing the snapshot is created for is successful)
310 snapshot.unclosed_delims.clear();
311 SnapshotParser { parser: snapshot, unclosed_delims }
314 pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
315 self.sess.source_map().span_to_snippet(span)
318 pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
319 let mut err = self.struct_span_err(
321 &format!("expected identifier, found {}", super::token_descr(&self.token)),
323 let valid_follow = &[
329 TokenKind::OpenDelim(token::DelimToken::Brace),
330 TokenKind::OpenDelim(token::DelimToken::Paren),
331 TokenKind::CloseDelim(token::DelimToken::Brace),
332 TokenKind::CloseDelim(token::DelimToken::Paren),
334 match self.token.ident() {
336 if ident.is_raw_guess()
337 && self.look_ahead(1, |t| valid_follow.contains(&t.kind)) =>
339 err.span_suggestion_verbose(
340 ident.span.shrink_to_lo(),
341 &format!("escape `{}` to use it as an identifier", ident.name),
343 Applicability::MaybeIncorrect,
348 if let Some(token_descr) = super::token_descr_opt(&self.token) {
349 err.span_label(self.token.span, format!("expected identifier, found {}", token_descr));
351 err.span_label(self.token.span, "expected identifier");
352 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
357 Applicability::MachineApplicable,
364 pub(super) fn expected_one_of_not_found(
366 edible: &[TokenKind],
367 inedible: &[TokenKind],
368 ) -> PResult<'a, bool /* recovered */> {
369 debug!("expected_one_of_not_found(edible: {:?}, inedible: {:?})", edible, inedible);
370 fn tokens_to_string(tokens: &[TokenType]) -> String {
371 let mut i = tokens.iter();
372 // This might be a sign we need a connect method on `Iterator`.
373 let b = i.next().map_or_else(String::new, |t| t.to_string());
374 i.enumerate().fold(b, |mut b, (i, a)| {
375 if tokens.len() > 2 && i == tokens.len() - 2 {
377 } else if tokens.len() == 2 && i == tokens.len() - 2 {
382 b.push_str(&a.to_string());
387 let mut expected = edible
389 .map(|x| TokenType::Token(x.clone()))
390 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
391 .chain(self.expected_tokens.iter().cloned())
392 .collect::<Vec<_>>();
393 expected.sort_by_cached_key(|x| x.to_string());
396 let sm = self.sess.source_map();
397 let msg = format!("expected `;`, found {}", super::token_descr(&self.token));
398 let appl = Applicability::MachineApplicable;
399 if expected.contains(&TokenType::Token(token::Semi)) {
400 if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
401 // Likely inside a macro, can't provide meaningful suggestions.
402 } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
403 // The current token is in the same line as the prior token, not recoverable.
404 } else if [token::Comma, token::Colon].contains(&self.token.kind)
405 && self.prev_token.kind == token::CloseDelim(token::Paren)
407 // Likely typo: The current token is on a new line and is expected to be
408 // `.`, `;`, `?`, or an operator after a close delimiter token.
410 // let a = std::process::Command::new("echo")
414 // https://github.com/rust-lang/rust/issues/72253
415 } else if self.look_ahead(1, |t| {
416 t == &token::CloseDelim(token::Brace)
417 || t.can_begin_expr() && t.kind != token::Colon
418 }) && [token::Comma, token::Colon].contains(&self.token.kind)
420 // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is
421 // either `,` or `:`, and the next token could either start a new statement or is a
422 // block close. For example:
427 let sp = self.prev_token.span;
428 self.struct_span_err(sp, &msg)
429 .span_suggestion_short(sp, "change this to `;`", ";".to_string(), appl)
432 } else if self.look_ahead(0, |t| {
433 t == &token::CloseDelim(token::Brace)
435 t.can_begin_expr() && t != &token::Semi && t != &token::Pound
436 // Avoid triggering with too many trailing `#` in raw string.
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 sp = self.prev_token.span.shrink_to_hi();
445 self.struct_span_err(sp, &msg)
446 .span_label(self.token.span, "unexpected token")
447 .span_suggestion_short(sp, "add `;` here", ";".to_string(), appl)
453 let expect = tokens_to_string(&expected);
454 let actual = super::token_descr(&self.token);
455 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
456 let short_expect = if expected.len() > 6 {
457 format!("{} possible tokens", expected.len())
462 format!("expected one of {expect}, found {actual}"),
463 (self.prev_token.span.shrink_to_hi(), format!("expected one of {short_expect}")),
465 } else if expected.is_empty() {
467 format!("unexpected token: {}", actual),
468 (self.prev_token.span, "unexpected token after this".to_string()),
472 format!("expected {expect}, found {actual}"),
473 (self.prev_token.span.shrink_to_hi(), format!("expected {expect}")),
476 self.last_unexpected_token_span = Some(self.token.span);
477 let mut err = self.struct_span_err(self.token.span, &msg_exp);
479 // Add suggestion for a missing closing angle bracket if '>' is included in expected_tokens
480 // there are unclosed angle brackets
481 if self.unmatched_angle_bracket_count > 0
482 && self.token.kind == TokenKind::Eq
483 && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Gt)))
485 err.span_label(self.prev_token.span, "maybe try to close unmatched angle bracket");
488 let sp = if self.token == token::Eof {
489 // This is EOF; don't want to point at the following char, but rather the last token.
494 match self.recover_closing_delimiter(
497 .filter_map(|tt| match tt {
498 TokenType::Token(t) => Some(t.clone()),
501 .collect::<Vec<_>>(),
506 return Ok(recovered);
510 if self.check_too_many_raw_str_terminators(&mut err) {
514 if self.prev_token.span == DUMMY_SP {
515 // Account for macro context where the previous span might not be
516 // available to avoid incorrect output (#54841).
517 err.span_label(self.token.span, label_exp);
518 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
519 // When the spans are in the same line, it means that the only content between
520 // them is whitespace, point at the found token in that case:
522 // X | () => { syntax error };
523 // | ^^^^^ expected one of 8 possible tokens here
525 // instead of having:
527 // X | () => { syntax error };
528 // | -^^^^^ unexpected token
530 // | expected one of 8 possible tokens here
531 err.span_label(self.token.span, label_exp);
533 err.span_label(sp, label_exp);
534 err.span_label(self.token.span, "unexpected token");
536 self.maybe_annotate_with_ascription(&mut err, false);
540 fn check_too_many_raw_str_terminators(&mut self, err: &mut Diagnostic) -> bool {
541 match (&self.prev_token.kind, &self.token.kind) {
543 TokenKind::Literal(Lit {
544 kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
549 err.set_primary_message("too many `#` when terminating raw string");
552 "remove the extra `#`",
554 Applicability::MachineApplicable,
556 err.note(&format!("the raw string started with {n_hashes} `#`s"));
563 pub fn maybe_suggest_struct_literal(
567 ) -> Option<PResult<'a, P<Block>>> {
568 if self.token.is_ident() && self.look_ahead(1, |t| t == &token::Colon) {
569 // We might be having a struct literal where people forgot to include the path:
573 let mut snapshot = self.create_snapshot_for_diagnostic();
575 Path { segments: vec![], span: self.prev_token.span.shrink_to_lo(), tokens: None };
576 let struct_expr = snapshot.parse_struct_expr(None, path, AttrVec::new(), false);
577 let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No);
578 return Some(match (struct_expr, block_tail) {
579 (Ok(expr), Err(mut err)) => {
580 // We have encountered the following:
585 // fn foo() -> Foo { Path {
589 self.struct_span_err(
591 DiagnosticMessage::fluent("parser-struct-literal-body-without-path"),
593 .multipart_suggestion(
594 DiagnosticMessage::fluent_attr(
595 "parser-struct-literal-body-without-path",
599 (expr.span.shrink_to_lo(), "{ SomeStruct ".to_string()),
600 (expr.span.shrink_to_hi(), " }".to_string()),
602 Applicability::MaybeIncorrect,
605 self.restore_snapshot(snapshot);
606 let mut tail = self.mk_block(
607 vec![self.mk_stmt_err(expr.span)],
609 lo.to(self.prev_token.span),
611 tail.could_be_bare_literal = true;
614 (Err(err), Ok(tail)) => {
615 // We have a block tail that contains a somehow valid type ascription expr.
619 (Err(snapshot_err), Err(err)) => {
620 // We don't know what went wrong, emit the normal error.
621 snapshot_err.cancel();
622 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
625 (Ok(_), Ok(mut tail)) => {
626 tail.could_be_bare_literal = true;
634 pub fn maybe_annotate_with_ascription(
636 err: &mut Diagnostic,
637 maybe_expected_semicolon: bool,
639 if let Some((sp, likely_path)) = self.last_type_ascription.take() {
640 let sm = self.sess.source_map();
641 let next_pos = sm.lookup_char_pos(self.token.span.lo());
642 let op_pos = sm.lookup_char_pos(sp.hi());
644 let allow_unstable = self.sess.unstable_features.is_nightly_build();
649 "maybe write a path separator here",
652 Applicability::MaybeIncorrect
654 Applicability::MachineApplicable
657 self.sess.type_ascription_path_suggestions.borrow_mut().insert(sp);
658 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
661 "try using a semicolon",
663 Applicability::MaybeIncorrect,
665 } else if allow_unstable {
666 err.span_label(sp, "tried to parse a type due to this type ascription");
668 err.span_label(sp, "tried to parse a type due to this");
671 // Give extra information about type ascription only if it's a nightly compiler.
673 "`#![feature(type_ascription)]` lets you annotate an expression with a type: \
677 // Avoid giving too much info when it was likely an unrelated typo.
679 "see issue #23416 <https://github.com/rust-lang/rust/issues/23416> \
680 for more information",
687 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
688 /// passes through any errors encountered. Used for error recovery.
689 pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
691 self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
692 Ok(p.parse_token_tree())
699 /// This function checks if there are trailing angle brackets and produces
700 /// a diagnostic to suggest removing them.
702 /// ```ignore (diagnostic)
703 /// let _ = [1, 2, 3].into_iter().collect::<Vec<usize>>>>();
704 /// ^^ help: remove extra angle brackets
707 /// If `true` is returned, then trailing brackets were recovered, tokens were consumed
708 /// up until one of the tokens in 'end' was encountered, and an error was emitted.
709 pub(super) fn check_trailing_angle_brackets(
711 segment: &PathSegment,
714 // This function is intended to be invoked after parsing a path segment where there are two
717 // 1. A specific token is expected after the path segment.
718 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
719 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
720 // 2. No specific token is expected after the path segment.
721 // eg. `x.foo` (field access)
723 // This function is called after parsing `.foo` and before parsing the token `end` (if
724 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
727 // We only care about trailing angle brackets if we previously parsed angle bracket
728 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
729 // removed in this case:
731 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
733 // This case is particularly tricky as we won't notice it just looking at the tokens -
734 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
735 // have already been parsed):
737 // `x.foo::<u32>>>(3)`
738 let parsed_angle_bracket_args =
739 segment.args.as_ref().map_or(false, |args| args.is_angle_bracketed());
742 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
743 parsed_angle_bracket_args,
745 if !parsed_angle_bracket_args {
749 // Keep the span at the start so we can highlight the sequence of `>` characters to be
751 let lo = self.token.span;
753 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
754 // (since we might have the field access case and the characters we're eating are
755 // actual operators and not trailing characters - ie `x.foo >> 3`).
756 let mut position = 0;
758 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
759 // many of each (so we can correctly pluralize our error messages) and continue to
761 let mut number_of_shr = 0;
762 let mut number_of_gt = 0;
763 while self.look_ahead(position, |t| {
764 trace!("check_trailing_angle_brackets: t={:?}", t);
765 if *t == token::BinOp(token::BinOpToken::Shr) {
768 } else if *t == token::Gt {
778 // If we didn't find any trailing `>` characters, then we have nothing to error about.
780 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
781 number_of_gt, number_of_shr,
783 if number_of_gt < 1 && number_of_shr < 1 {
787 // Finally, double check that we have our end token as otherwise this is the
789 if self.look_ahead(position, |t| {
790 trace!("check_trailing_angle_brackets: t={:?}", t);
791 end.contains(&&t.kind)
793 // Eat from where we started until the end token so that parsing can continue
794 // as if we didn't have those extra angle brackets.
795 self.eat_to_tokens(end);
796 let span = lo.until(self.token.span);
798 let total_num_of_gt = number_of_gt + number_of_shr * 2;
799 self.struct_span_err(
801 &format!("unmatched angle bracket{}", pluralize!(total_num_of_gt)),
805 &format!("remove extra angle bracket{}", pluralize!(total_num_of_gt)),
807 Applicability::MachineApplicable,
815 /// Check if a method call with an intended turbofish has been written without surrounding
817 pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
818 if token::ModSep == self.token.kind && segment.args.is_none() {
819 let snapshot = self.create_snapshot_for_diagnostic();
821 let lo = self.token.span;
822 match self.parse_angle_args(None) {
824 let span = lo.to(self.prev_token.span);
825 // Detect trailing `>` like in `x.collect::Vec<_>>()`.
826 let mut trailing_span = self.prev_token.span.shrink_to_hi();
827 while self.token.kind == token::BinOp(token::Shr)
828 || self.token.kind == token::Gt
830 trailing_span = trailing_span.to(self.token.span);
833 if self.token.kind == token::OpenDelim(token::Paren) {
834 // Recover from bad turbofish: `foo.collect::Vec<_>()`.
835 let args = AngleBracketedArgs { args, span }.into();
838 self.struct_span_err(
840 "generic parameters without surrounding angle brackets",
842 .multipart_suggestion(
843 "surround the type parameters with angle brackets",
845 (span.shrink_to_lo(), "<".to_string()),
846 (trailing_span, ">".to_string()),
848 Applicability::MachineApplicable,
852 // This doesn't look like an invalid turbofish, can't recover parse state.
853 self.restore_snapshot(snapshot);
857 // We couldn't parse generic parameters, unlikely to be a turbofish. Rely on
858 // generic parse error instead.
860 self.restore_snapshot(snapshot);
866 /// When writing a turbofish with multiple type parameters missing the leading `::`, we will
867 /// encounter a parse error when encountering the first `,`.
868 pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
870 mut e: DiagnosticBuilder<'a, ErrorGuaranteed>,
872 ) -> PResult<'a, ()> {
873 if let ExprKind::Binary(binop, _, _) = &expr.kind
874 && let ast::BinOpKind::Lt = binop.node
875 && self.eat(&token::Comma)
877 let x = self.parse_seq_to_before_end(
879 SeqSep::trailing_allowed(token::Comma),
880 |p| p.parse_generic_arg(None),
883 Ok((_, _, false)) => {
884 if self.eat(&token::Gt) {
885 e.span_suggestion_verbose(
886 binop.span.shrink_to_lo(),
887 TURBOFISH_SUGGESTION_STR,
889 Applicability::MaybeIncorrect,
892 match self.parse_expr() {
895 self.mk_expr_err(expr.span.to(self.prev_token.span));
899 *expr = self.mk_expr_err(expr.span);
914 /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
915 /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
916 /// parenthesising the leftmost comparison.
917 fn attempt_chained_comparison_suggestion(
919 err: &mut Diagnostic,
921 outer_op: &Spanned<AssocOp>,
922 ) -> bool /* advanced the cursor */ {
923 if let ExprKind::Binary(op, ref l1, ref r1) = inner_op.kind {
924 if let ExprKind::Field(_, ident) = l1.kind
925 && ident.as_str().parse::<i32>().is_err()
926 && !matches!(r1.kind, ExprKind::Lit(_))
928 // The parser has encountered `foo.bar<baz`, the likelihood of the turbofish
929 // suggestion being the only one to apply is high.
932 let mut enclose = |left: Span, right: Span| {
933 err.multipart_suggestion(
934 "parenthesize the comparison",
936 (left.shrink_to_lo(), "(".to_string()),
937 (right.shrink_to_hi(), ")".to_string()),
939 Applicability::MaybeIncorrect,
942 return match (op.node, &outer_op.node) {
944 (BinOpKind::Eq, AssocOp::Equal) |
945 // `x < y < z` and friends.
946 (BinOpKind::Lt, AssocOp::Less | AssocOp::LessEqual) |
947 (BinOpKind::Le, AssocOp::LessEqual | AssocOp::Less) |
948 // `x > y > z` and friends.
949 (BinOpKind::Gt, AssocOp::Greater | AssocOp::GreaterEqual) |
950 (BinOpKind::Ge, AssocOp::GreaterEqual | AssocOp::Greater) => {
951 let expr_to_str = |e: &Expr| {
952 self.span_to_snippet(e.span)
953 .unwrap_or_else(|_| pprust::expr_to_string(&e))
955 err.span_suggestion_verbose(
956 inner_op.span.shrink_to_hi(),
957 "split the comparison into two",
958 format!(" && {}", expr_to_str(&r1)),
959 Applicability::MaybeIncorrect,
961 false // Keep the current parse behavior, where the AST is `(x < y) < z`.
964 (BinOpKind::Eq, AssocOp::Less | AssocOp::LessEqual | AssocOp::Greater | AssocOp::GreaterEqual) => {
965 // Consume `z`/outer-op-rhs.
966 let snapshot = self.create_snapshot_for_diagnostic();
967 match self.parse_expr() {
969 // We are sure that outer-op-rhs could be consumed, the suggestion is
971 enclose(r1.span, r2.span);
976 self.restore_snapshot(snapshot);
982 (BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge, AssocOp::Equal) => {
983 let snapshot = self.create_snapshot_for_diagnostic();
984 // At this point it is always valid to enclose the lhs in parentheses, no
985 // further checks are necessary.
986 match self.parse_expr() {
988 enclose(l1.span, r1.span);
993 self.restore_snapshot(snapshot);
1004 /// Produces an error if comparison operators are chained (RFC #558).
1005 /// We only need to check the LHS, not the RHS, because all comparison ops have same
1006 /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
1008 /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
1009 /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
1012 /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
1013 /// associative we can infer that we have:
1022 pub(super) fn check_no_chained_comparison(
1025 outer_op: &Spanned<AssocOp>,
1026 ) -> PResult<'a, Option<P<Expr>>> {
1028 outer_op.node.is_comparison(),
1029 "check_no_chained_comparison: {:?} is not comparison",
1034 |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err, AttrVec::new())));
1036 match inner_op.kind {
1037 ExprKind::Binary(op, ref l1, ref r1) if op.node.is_comparison() => {
1038 let mut err = self.struct_span_err(
1039 vec![op.span, self.prev_token.span],
1040 "comparison operators cannot be chained",
1043 let suggest = |err: &mut Diagnostic| {
1044 err.span_suggestion_verbose(
1045 op.span.shrink_to_lo(),
1046 TURBOFISH_SUGGESTION_STR,
1048 Applicability::MaybeIncorrect,
1052 // Include `<` to provide this recommendation even in a case like
1053 // `Foo<Bar<Baz<Qux, ()>>>`
1054 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Less
1055 || outer_op.node == AssocOp::Greater
1057 if outer_op.node == AssocOp::Less {
1058 let snapshot = self.create_snapshot_for_diagnostic();
1060 // So far we have parsed `foo<bar<`, consume the rest of the type args.
1062 [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
1063 self.consume_tts(1, &modifiers);
1065 if !&[token::OpenDelim(token::Paren), token::ModSep]
1066 .contains(&self.token.kind)
1068 // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
1069 // parser and bail out.
1070 self.restore_snapshot(snapshot);
1073 return if token::ModSep == self.token.kind {
1074 // We have some certainty that this was a bad turbofish at this point.
1078 let snapshot = self.create_snapshot_for_diagnostic();
1079 self.bump(); // `::`
1081 // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
1082 match self.parse_expr() {
1084 // 99% certain that the suggestion is correct, continue parsing.
1086 // FIXME: actually check that the two expressions in the binop are
1087 // paths and resynthesize new fn call expression instead of using
1088 // `ExprKind::Err` placeholder.
1089 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1093 // Not entirely sure now, but we bubble the error up with the
1095 self.restore_snapshot(snapshot);
1099 } else if token::OpenDelim(token::Paren) == self.token.kind {
1100 // We have high certainty that this was a bad turbofish at this point.
1103 // Consume the fn call arguments.
1104 match self.consume_fn_args() {
1105 Err(()) => Err(err),
1108 // FIXME: actually check that the two expressions in the binop are
1109 // paths and resynthesize new fn call expression instead of using
1110 // `ExprKind::Err` placeholder.
1111 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1115 if !matches!(l1.kind, ExprKind::Lit(_))
1116 && !matches!(r1.kind, ExprKind::Lit(_))
1118 // All we know is that this is `foo < bar >` and *nothing* else. Try to
1119 // be helpful, but don't attempt to recover.
1120 err.help(TURBOFISH_SUGGESTION_STR);
1121 err.help("or use `(...)` if you meant to specify fn arguments");
1124 // If it looks like a genuine attempt to chain operators (as opposed to a
1125 // misformatted turbofish, for instance), suggest a correct form.
1126 if self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op)
1129 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1131 // These cases cause too many knock-down errors, bail out (#61329).
1137 self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1140 return mk_err_expr(self, inner_op.span.to(self.prev_token.span));
1148 fn consume_fn_args(&mut self) -> Result<(), ()> {
1149 let snapshot = self.create_snapshot_for_diagnostic();
1152 // Consume the fn call arguments.
1154 [(token::OpenDelim(token::Paren), 1), (token::CloseDelim(token::Paren), -1)];
1155 self.consume_tts(1, &modifiers);
1157 if self.token.kind == token::Eof {
1158 // Not entirely sure that what we consumed were fn arguments, rollback.
1159 self.restore_snapshot(snapshot);
1162 // 99% certain that the suggestion is correct, continue parsing.
1167 pub(super) fn maybe_report_ambiguous_plus(
1169 allow_plus: AllowPlus,
1170 impl_dyn_multi: bool,
1173 if matches!(allow_plus, AllowPlus::No) && impl_dyn_multi {
1174 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1175 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1178 "use parentheses to disambiguate",
1180 Applicability::MachineApplicable,
1186 /// Swift lets users write `Ty?` to mean `Option<Ty>`. Parse the construct and recover from it.
1187 pub(super) fn maybe_recover_from_question_mark(
1190 recover_question_mark: RecoverQuestionMark,
1192 if let RecoverQuestionMark::No = recover_question_mark {
1195 if self.token == token::Question {
1197 self.struct_span_err(self.prev_token.span, "invalid `?` in type")
1198 .span_label(self.prev_token.span, "`?` is only allowed on expressions, not types")
1199 .multipart_suggestion(
1200 "if you meant to express that the type might not contain a value, use the `Option` wrapper type",
1202 (ty.span.shrink_to_lo(), "Option<".to_string()),
1203 (self.prev_token.span, ">".to_string()),
1205 Applicability::MachineApplicable,
1208 self.mk_ty(ty.span.to(self.prev_token.span), TyKind::Err)
1214 pub(super) fn maybe_recover_from_bad_type_plus(
1216 allow_plus: AllowPlus,
1218 ) -> PResult<'a, ()> {
1219 // Do not add `+` to expected tokens.
1220 if matches!(allow_plus, AllowPlus::No) || !self.token.is_like_plus() {
1225 let bounds = self.parse_generic_bounds(None)?;
1226 let sum_span = ty.span.to(self.prev_token.span);
1228 let mut err = struct_span_err!(
1229 self.sess.span_diagnostic,
1232 "expected a path on the left-hand side of `+`, not `{}`",
1233 pprust::ty_to_string(ty)
1237 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1238 let sum_with_parens = pprust::to_string(|s| {
1240 s.print_opt_lifetime(lifetime);
1241 s.print_mutability(mut_ty.mutbl, false);
1243 s.print_type(&mut_ty.ty);
1244 s.print_type_bounds(" +", &bounds);
1247 err.span_suggestion(
1249 "try adding parentheses",
1251 Applicability::MachineApplicable,
1254 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1255 err.span_label(sum_span, "perhaps you forgot parentheses?");
1258 err.span_label(sum_span, "expected a path");
1265 pub(super) fn recover_from_prefix_increment(
1267 operand_expr: P<Expr>,
1270 ) -> PResult<'a, P<Expr>> {
1272 if prev_is_semi { IsStandalone::Standalone } else { IsStandalone::Subexpr };
1273 let kind = IncDecRecovery { standalone, op: IncOrDec::Inc, fixity: UnaryFixity::Pre };
1275 self.recover_from_inc_dec(operand_expr, kind, op_span)
1278 pub(super) fn recover_from_postfix_increment(
1280 operand_expr: P<Expr>,
1282 ) -> PResult<'a, P<Expr>> {
1283 let kind = IncDecRecovery {
1284 standalone: IsStandalone::Maybe,
1286 fixity: UnaryFixity::Post,
1289 self.recover_from_inc_dec(operand_expr, kind, op_span)
1292 fn recover_from_inc_dec(
1295 kind: IncDecRecovery,
1297 ) -> PResult<'a, P<Expr>> {
1298 let mut err = self.struct_span_err(
1300 &format!("Rust has no {} {} operator", kind.fixity, kind.op.name()),
1302 err.span_label(op_span, &format!("not a valid {} operator", kind.fixity));
1304 let help_base_case = |mut err: DiagnosticBuilder<'_, _>, base| {
1305 err.help(&format!("use `{}= 1` instead", kind.op.chr()));
1311 let spans = match kind.fixity {
1312 UnaryFixity::Pre => (op_span, base.span.shrink_to_hi()),
1313 UnaryFixity::Post => (base.span.shrink_to_lo(), op_span),
1316 match kind.standalone {
1317 IsStandalone::Standalone => self.inc_dec_standalone_suggest(kind, spans).emit(&mut err),
1318 IsStandalone::Subexpr => {
1319 let Ok(base_src) = self.span_to_snippet(base.span)
1320 else { return help_base_case(err, base) };
1322 UnaryFixity::Pre => {
1323 self.prefix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1325 UnaryFixity::Post => {
1326 self.postfix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1330 IsStandalone::Maybe => {
1331 let Ok(base_src) = self.span_to_snippet(base.span)
1332 else { return help_base_case(err, base) };
1333 let sugg1 = match kind.fixity {
1334 UnaryFixity::Pre => self.prefix_inc_dec_suggest(base_src, kind, spans),
1335 UnaryFixity::Post => self.postfix_inc_dec_suggest(base_src, kind, spans),
1337 let sugg2 = self.inc_dec_standalone_suggest(kind, spans);
1338 MultiSugg::emit_many(
1340 "use `+= 1` instead",
1341 Applicability::Unspecified,
1342 [sugg1, sugg2].into_iter(),
1349 fn prefix_inc_dec_suggest(
1352 kind: IncDecRecovery,
1353 (pre_span, post_span): (Span, Span),
1356 msg: format!("use `{}= 1` instead", kind.op.chr()),
1358 (pre_span, "{ ".to_string()),
1359 (post_span, format!(" {}= 1; {} }}", kind.op.chr(), base_src)),
1361 applicability: Applicability::MachineApplicable,
1365 fn postfix_inc_dec_suggest(
1368 kind: IncDecRecovery,
1369 (pre_span, post_span): (Span, Span),
1371 let tmp_var = if base_src.trim() == "tmp" { "tmp_" } else { "tmp" };
1373 msg: format!("use `{}= 1` instead", kind.op.chr()),
1375 (pre_span, format!("{{ let {} = ", tmp_var)),
1376 (post_span, format!("; {} {}= 1; {} }}", base_src, kind.op.chr(), tmp_var)),
1378 applicability: Applicability::HasPlaceholders,
1382 fn inc_dec_standalone_suggest(
1384 kind: IncDecRecovery,
1385 (pre_span, post_span): (Span, Span),
1388 msg: format!("use `{}= 1` instead", kind.op.chr()),
1389 patches: vec![(pre_span, String::new()), (post_span, format!(" {}= 1", kind.op.chr()))],
1390 applicability: Applicability::MachineApplicable,
1394 /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
1395 /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
1396 /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
1397 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
1400 allow_recovery: bool,
1401 ) -> PResult<'a, P<T>> {
1402 // Do not add `::` to expected tokens.
1403 if allow_recovery && self.token == token::ModSep {
1404 if let Some(ty) = base.to_ty() {
1405 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1411 /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
1412 /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
1413 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
1417 ) -> PResult<'a, P<T>> {
1418 self.expect(&token::ModSep)?;
1420 let mut path = ast::Path { segments: Vec::new(), span: DUMMY_SP, tokens: None };
1421 self.parse_path_segments(&mut path.segments, T::PATH_STYLE, None)?;
1422 path.span = ty_span.to(self.prev_token.span);
1424 let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
1425 self.struct_span_err(path.span, "missing angle brackets in associated item path")
1427 // This is a best-effort recovery.
1430 format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
1431 Applicability::MaybeIncorrect,
1435 let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
1436 Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path)))
1439 pub fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
1440 if self.token.kind == TokenKind::Semi {
1442 let mut err = self.struct_span_err(self.prev_token.span, "expected item, found `;`");
1443 err.span_suggestion_short(
1444 self.prev_token.span,
1445 "remove this semicolon",
1447 Applicability::MachineApplicable,
1449 if !items.is_empty() {
1450 let previous_item = &items[items.len() - 1];
1451 let previous_item_kind_name = match previous_item.kind {
1452 // Say "braced struct" because tuple-structs and
1453 // braceless-empty-struct declarations do take a semicolon.
1454 ItemKind::Struct(..) => Some("braced struct"),
1455 ItemKind::Enum(..) => Some("enum"),
1456 ItemKind::Trait(..) => Some("trait"),
1457 ItemKind::Union(..) => Some("union"),
1460 if let Some(name) = previous_item_kind_name {
1461 err.help(&format!("{name} declarations are not followed by a semicolon"));
1471 /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
1472 /// closing delimiter.
1473 pub(super) fn unexpected_try_recover(
1476 ) -> PResult<'a, bool /* recovered */> {
1477 let token_str = pprust::token_kind_to_string(t);
1478 let this_token_str = super::token_descr(&self.token);
1479 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1480 // Point at the end of the macro call when reaching end of macro arguments.
1481 (token::Eof, Some(_)) => {
1482 let sp = self.sess.source_map().next_point(self.prev_token.span);
1485 // We don't want to point at the following span after DUMMY_SP.
1486 // This happens when the parser finds an empty TokenStream.
1487 _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
1488 // EOF, don't want to point at the following char, but rather the last token.
1489 (token::Eof, None) => (self.prev_token.span, self.token.span),
1490 _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
1493 "expected `{}`, found {}",
1495 match (&self.token.kind, self.subparser_name) {
1496 (token::Eof, Some(origin)) => format!("end of {origin}"),
1497 _ => this_token_str,
1500 let mut err = self.struct_span_err(sp, &msg);
1501 let label_exp = format!("expected `{token_str}`");
1502 match self.recover_closing_delimiter(&[t.clone()], err) {
1505 return Ok(recovered);
1508 let sm = self.sess.source_map();
1509 if !sm.is_multiline(prev_sp.until(sp)) {
1510 // When the spans are in the same line, it means that the only content
1511 // between them is whitespace, point only at the found token.
1512 err.span_label(sp, label_exp);
1514 err.span_label(prev_sp, label_exp);
1515 err.span_label(sp, "unexpected token");
1520 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1521 if self.eat(&token::Semi) {
1524 self.expect(&token::Semi).map(drop) // Error unconditionally
1527 /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
1528 /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
1529 pub(super) fn recover_incorrect_await_syntax(
1534 ) -> PResult<'a, P<Expr>> {
1535 let (hi, expr, is_question) = if self.token == token::Not {
1536 // Handle `await!(<expr>)`.
1537 self.recover_await_macro()?
1539 self.recover_await_prefix(await_sp)?
1541 let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
1542 let kind = match expr.kind {
1543 // Avoid knock-down errors as we don't know whether to interpret this as `foo().await?`
1544 // or `foo()?.await` (the very reason we went with postfix syntax 😅).
1545 ExprKind::Try(_) => ExprKind::Err,
1546 _ => ExprKind::Await(expr),
1548 let expr = self.mk_expr(lo.to(sp), kind, attrs);
1549 self.maybe_recover_from_bad_qpath(expr, true)
1552 fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1553 self.expect(&token::Not)?;
1554 self.expect(&token::OpenDelim(token::Paren))?;
1555 let expr = self.parse_expr()?;
1556 self.expect(&token::CloseDelim(token::Paren))?;
1557 Ok((self.prev_token.span, expr, false))
1560 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
1561 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
1562 let expr = if self.token == token::OpenDelim(token::Brace) {
1563 // Handle `await { <expr> }`.
1564 // This needs to be handled separately from the next arm to avoid
1565 // interpreting `await { <expr> }?` as `<expr>?.await`.
1566 self.parse_block_expr(None, self.token.span, BlockCheckMode::Default, AttrVec::new())
1570 .map_err(|mut err| {
1571 err.span_label(await_sp, "while parsing this incorrect await expression");
1574 Ok((expr.span, expr, is_question))
1577 fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
1579 self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr));
1580 let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" });
1582 let app = match expr.kind {
1583 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
1584 _ => Applicability::MachineApplicable,
1586 self.struct_span_err(sp, "incorrect use of `await`")
1587 .span_suggestion(sp, "`await` is a postfix operation", suggestion, app)
1592 /// If encountering `future.await()`, consumes and emits an error.
1593 pub(super) fn recover_from_await_method_call(&mut self) {
1594 if self.token == token::OpenDelim(token::Paren)
1595 && self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren))
1598 let lo = self.token.span;
1600 let sp = lo.to(self.token.span);
1602 self.struct_span_err(sp, "incorrect use of `await`")
1605 "`await` is not a method call, remove the parentheses",
1607 Applicability::MachineApplicable,
1613 pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, P<Expr>> {
1614 let is_try = self.token.is_keyword(kw::Try);
1615 let is_questionmark = self.look_ahead(1, |t| t == &token::Not); //check for !
1616 let is_open = self.look_ahead(2, |t| t == &token::OpenDelim(token::Paren)); //check for (
1618 if is_try && is_questionmark && is_open {
1619 let lo = self.token.span;
1620 self.bump(); //remove try
1621 self.bump(); //remove !
1622 let try_span = lo.to(self.token.span); //we take the try!( span
1623 self.bump(); //remove (
1624 let is_empty = self.token == token::CloseDelim(token::Paren); //check if the block is empty
1625 self.consume_block(token::Paren, ConsumeClosingDelim::No); //eat the block
1626 let hi = self.token.span;
1627 self.bump(); //remove )
1628 let mut err = self.struct_span_err(lo.to(hi), "use of deprecated `try` macro");
1629 err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
1630 let prefix = if is_empty { "" } else { "alternatively, " };
1632 err.multipart_suggestion(
1633 "you can use the `?` operator instead",
1634 vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
1635 Applicability::MachineApplicable,
1638 err.span_suggestion(lo.shrink_to_lo(), &format!("{prefix}you can still access the deprecated `try!()` macro using the \"raw identifier\" syntax"), "r#".to_string(), Applicability::MachineApplicable);
1640 Ok(self.mk_expr_err(lo.to(hi)))
1642 Err(self.expected_expression_found()) // The user isn't trying to invoke the try! macro
1646 /// Recovers a situation like `for ( $pat in $expr )`
1647 /// and suggest writing `for $pat in $expr` instead.
1649 /// This should be called before parsing the `$block`.
1650 pub(super) fn recover_parens_around_for_head(
1653 begin_paren: Option<Span>,
1655 match (&self.token.kind, begin_paren) {
1656 (token::CloseDelim(token::Paren), Some(begin_par_sp)) => {
1659 self.struct_span_err(
1660 MultiSpan::from_spans(vec![begin_par_sp, self.prev_token.span]),
1661 "unexpected parentheses surrounding `for` loop head",
1663 .multipart_suggestion(
1664 "remove parentheses in `for` loop",
1665 vec![(begin_par_sp, String::new()), (self.prev_token.span, String::new())],
1666 // With e.g. `for (x) in y)` this would replace `(x) in y)`
1667 // with `x) in y)` which is syntactically invalid.
1668 // However, this is prevented before we get here.
1669 Applicability::MachineApplicable,
1673 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1674 pat.and_then(|pat| match pat.kind {
1675 PatKind::Paren(pat) => pat,
1683 pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1684 (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1685 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1686 || self.token.is_ident() &&
1687 matches!(node, ast::ExprKind::Path(..) | ast::ExprKind::Field(..)) &&
1688 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
1689 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren))
1690 || self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) // `foo:bar {`
1691 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar::<baz`
1692 self.look_ahead(2, |t| t == &token::Lt) &&
1693 self.look_ahead(3, |t| t.is_ident())
1694 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
1695 self.look_ahead(2, |t| t.is_ident())
1696 || self.look_ahead(1, |t| t == &token::ModSep)
1697 && (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
1698 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1701 pub(super) fn recover_seq_parse_error(
1703 delim: token::DelimToken,
1705 result: PResult<'a, P<Expr>>,
1711 // Recover from parse error, callers expect the closing delim to be consumed.
1712 self.consume_block(delim, ConsumeClosingDelim::Yes);
1713 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err, AttrVec::new())
1718 pub(super) fn recover_closing_delimiter(
1720 tokens: &[TokenKind],
1721 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
1722 ) -> PResult<'a, bool> {
1724 // We want to use the last closing delim that would apply.
1725 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1726 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1727 && Some(self.token.span) > unmatched.unclosed_span
1734 // Recover and assume that the detected unclosed delimiter was meant for
1735 // this location. Emit the diagnostic and act as if the delimiter was
1736 // present for the parser's sake.
1738 // Don't attempt to recover from this unclosed delimiter more than once.
1739 let unmatched = self.unclosed_delims.remove(pos);
1740 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1741 if unmatched.found_delim.is_none() {
1742 // We encountered `Eof`, set this fact here to avoid complaining about missing
1743 // `fn main()` when we found place to suggest the closing brace.
1744 *self.sess.reached_eof.borrow_mut() = true;
1747 // We want to suggest the inclusion of the closing delimiter where it makes
1748 // the most sense, which is immediately after the last token:
1753 // | help: `)` may belong here
1755 // unclosed delimiter
1756 if let Some(sp) = unmatched.unclosed_span {
1757 let mut primary_span: Vec<Span> =
1758 err.span.primary_spans().iter().cloned().collect();
1759 primary_span.push(sp);
1760 let mut primary_span: MultiSpan = primary_span.into();
1761 for span_label in err.span.span_labels() {
1762 if let Some(label) = span_label.label {
1763 primary_span.push_span_label(span_label.span, label);
1766 err.set_span(primary_span);
1767 err.span_label(sp, "unclosed delimiter");
1769 // Backticks should be removed to apply suggestions.
1770 let mut delim = delim.to_string();
1771 delim.retain(|c| c != '`');
1772 err.span_suggestion_short(
1773 self.prev_token.span.shrink_to_hi(),
1774 &format!("`{delim}` may belong here"),
1776 Applicability::MaybeIncorrect,
1778 if unmatched.found_delim.is_none() {
1779 // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1780 // errors which would be emitted elsewhere in the parser and let other error
1781 // recovery consume the rest of the file.
1785 self.expected_tokens.clear(); // Reduce the number of errors.
1793 /// Eats tokens until we can be relatively sure we reached the end of the
1794 /// statement. This is something of a best-effort heuristic.
1796 /// We terminate when we find an unmatched `}` (without consuming it).
1797 pub(super) fn recover_stmt(&mut self) {
1798 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1801 /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1802 /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1803 /// approximate -- it can mean we break too early due to macros, but that
1804 /// should only lead to sub-optimal recovery, not inaccurate parsing).
1806 /// If `break_on_block` is `Break`, then we will stop consuming tokens
1807 /// after finding (and consuming) a brace-delimited block.
1808 pub(super) fn recover_stmt_(
1810 break_on_semi: SemiColonMode,
1811 break_on_block: BlockMode,
1813 let mut brace_depth = 0;
1814 let mut bracket_depth = 0;
1815 let mut in_block = false;
1816 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1818 debug!("recover_stmt_ loop {:?}", self.token);
1819 match self.token.kind {
1820 token::OpenDelim(token::DelimToken::Brace) => {
1823 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1828 token::OpenDelim(token::DelimToken::Bracket) => {
1832 token::CloseDelim(token::DelimToken::Brace) => {
1833 if brace_depth == 0 {
1834 debug!("recover_stmt_ return - close delim {:?}", self.token);
1839 if in_block && bracket_depth == 0 && brace_depth == 0 {
1840 debug!("recover_stmt_ return - block end {:?}", self.token);
1844 token::CloseDelim(token::DelimToken::Bracket) => {
1846 if bracket_depth < 0 {
1852 debug!("recover_stmt_ return - Eof");
1857 if break_on_semi == SemiColonMode::Break
1859 && bracket_depth == 0
1861 debug!("recover_stmt_ return - Semi");
1866 if break_on_semi == SemiColonMode::Comma
1868 && bracket_depth == 0 =>
1870 debug!("recover_stmt_ return - Semi");
1878 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1879 if self.eat_keyword(kw::In) {
1880 // a common typo: `for _ in in bar {}`
1881 self.struct_span_err(self.prev_token.span, "expected iterable, found keyword `in`")
1882 .span_suggestion_short(
1883 in_span.until(self.prev_token.span),
1884 "remove the duplicated `in`",
1886 Applicability::MachineApplicable,
1892 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1893 if let token::DocComment(..) = self.token.kind {
1894 self.struct_span_err(
1896 "documentation comments cannot be applied to a function parameter's type",
1898 .span_label(self.token.span, "doc comments are not allowed here")
1901 } else if self.token == token::Pound
1902 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Bracket))
1904 let lo = self.token.span;
1905 // Skip every token until next possible arg.
1906 while self.token != token::CloseDelim(token::Bracket) {
1909 let sp = lo.to(self.token.span);
1911 self.struct_span_err(sp, "attributes cannot be applied to a function parameter's type")
1912 .span_label(sp, "attributes are not allowed here")
1917 pub(super) fn parameter_without_type(
1919 err: &mut Diagnostic,
1923 ) -> Option<Ident> {
1924 // If we find a pattern followed by an identifier, it could be an (incorrect)
1925 // C-style parameter declaration.
1926 if self.check_ident()
1927 && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseDelim(token::Paren))
1929 // `fn foo(String s) {}`
1930 let ident = self.parse_ident().unwrap();
1931 let span = pat.span.with_hi(ident.span.hi());
1933 err.span_suggestion(
1935 "declare the type after the parameter binding",
1936 String::from("<identifier>: <type>"),
1937 Applicability::HasPlaceholders,
1940 } else if require_name
1941 && (self.token == token::Comma
1942 || self.token == token::Lt
1943 || self.token == token::CloseDelim(token::Paren))
1945 let rfc_note = "anonymous parameters are removed in the 2018 edition (see RFC 1685)";
1947 let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
1949 PatKind::Ident(_, ident, _) => (
1951 "self: ".to_string(),
1952 ": TypeName".to_string(),
1954 pat.span.shrink_to_lo(),
1955 pat.span.shrink_to_hi(),
1956 pat.span.shrink_to_lo(),
1958 // Also catches `fn foo(&a)`.
1959 PatKind::Ref(ref inner_pat, mutab)
1960 if matches!(inner_pat.clone().into_inner().kind, PatKind::Ident(..)) =>
1962 match inner_pat.clone().into_inner().kind {
1963 PatKind::Ident(_, ident, _) => {
1964 let mutab = mutab.prefix_str();
1967 "self: ".to_string(),
1968 format!("{ident}: &{mutab}TypeName"),
1970 pat.span.shrink_to_lo(),
1972 pat.span.shrink_to_lo(),
1975 _ => unreachable!(),
1979 // Otherwise, try to get a type and emit a suggestion.
1980 if let Some(ty) = pat.to_ty() {
1981 err.span_suggestion_verbose(
1983 "explicitly ignore the parameter name",
1984 format!("_: {}", pprust::ty_to_string(&ty)),
1985 Applicability::MachineApplicable,
1994 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1996 err.span_suggestion(
1998 "if this is a `self` type, give it a parameter name",
2000 Applicability::MaybeIncorrect,
2003 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
2004 // `fn foo(HashMap: TypeName<u32>)`.
2005 if self.token != token::Lt {
2006 err.span_suggestion(
2008 "if this is a parameter name, give it a type",
2010 Applicability::HasPlaceholders,
2013 err.span_suggestion(
2015 "if this is a type, explicitly ignore the parameter name",
2017 Applicability::MachineApplicable,
2021 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
2022 return if self.token == token::Lt { None } else { Some(ident) };
2027 pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
2028 let pat = self.parse_pat_no_top_alt(Some("argument name"))?;
2029 self.expect(&token::Colon)?;
2030 let ty = self.parse_ty()?;
2036 "patterns aren't allowed in methods without bodies",
2038 .span_suggestion_short(
2040 "give this argument a name or use an underscore to ignore it",
2042 Applicability::MachineApplicable,
2046 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2048 P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID, tokens: None });
2052 pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
2053 let sp = param.pat.span;
2054 param.ty.kind = TyKind::Err;
2055 self.struct_span_err(sp, "unexpected `self` parameter in function")
2056 .span_label(sp, "must be the first parameter of an associated function")
2061 pub(super) fn consume_block(
2063 delim: token::DelimToken,
2064 consume_close: ConsumeClosingDelim,
2066 let mut brace_depth = 0;
2068 if self.eat(&token::OpenDelim(delim)) {
2070 } else if self.check(&token::CloseDelim(delim)) {
2071 if brace_depth == 0 {
2072 if let ConsumeClosingDelim::Yes = consume_close {
2073 // Some of the callers of this method expect to be able to parse the
2074 // closing delimiter themselves, so we leave it alone. Otherwise we advance
2084 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
2092 pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2093 let (span, msg) = match (&self.token.kind, self.subparser_name) {
2094 (&token::Eof, Some(origin)) => {
2095 let sp = self.sess.source_map().next_point(self.prev_token.span);
2096 (sp, format!("expected expression, found end of {origin}"))
2100 format!("expected expression, found {}", super::token_descr(&self.token),),
2103 let mut err = self.struct_span_err(span, &msg);
2104 let sp = self.sess.source_map().start_point(self.token.span);
2105 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
2106 self.sess.expr_parentheses_needed(&mut err, *sp);
2108 err.span_label(span, "expected expression");
2114 mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
2115 // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
2116 modifier: &[(token::TokenKind, i64)],
2119 if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
2122 if self.token.kind == token::Eof {
2129 /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
2131 /// This is necessary because at this point we don't know whether we parsed a function with
2132 /// anonymous parameters or a function with names but no types. In order to minimize
2133 /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
2134 /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
2135 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
2136 /// we deduplicate them to not complain about duplicated parameter names.
2137 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
2138 let mut seen_inputs = FxHashSet::default();
2139 for input in fn_inputs.iter_mut() {
2140 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
2141 (&input.pat.kind, &input.ty.kind)
2147 if let Some(ident) = opt_ident {
2148 if seen_inputs.contains(&ident) {
2149 input.pat.kind = PatKind::Wild;
2151 seen_inputs.insert(ident);
2156 /// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
2157 /// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
2158 /// like the user has forgotten them.
2159 pub fn handle_ambiguous_unbraced_const_arg(
2161 args: &mut Vec<AngleBracketedArg>,
2162 ) -> PResult<'a, bool> {
2163 // If we haven't encountered a closing `>`, then the argument is malformed.
2164 // It's likely that the user has written a const expression without enclosing it
2165 // in braces, so we try to recover here.
2166 let arg = args.pop().unwrap();
2167 // FIXME: for some reason using `unexpected` or `expected_one_of_not_found` has
2168 // adverse side-effects to subsequent errors and seems to advance the parser.
2169 // We are causing this error here exclusively in case that a `const` expression
2170 // could be recovered from the current parser state, even if followed by more
2171 // arguments after a comma.
2172 let mut err = self.struct_span_err(
2174 &format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
2176 err.span_label(self.token.span, "expected one of `,` or `>`");
2177 match self.recover_const_arg(arg.span(), err) {
2179 args.push(AngleBracketedArg::Arg(arg));
2180 if self.eat(&token::Comma) {
2181 return Ok(true); // Continue
2186 // We will emit a more generic error later.
2190 return Ok(false); // Don't continue.
2193 /// Attempt to parse a generic const argument that has not been enclosed in braces.
2194 /// There are a limited number of expressions that are permitted without being encoded
2197 /// - Single-segment paths (i.e. standalone generic const parameters).
2198 /// All other expressions that can be parsed will emit an error suggesting the expression be
2199 /// wrapped in braces.
2200 pub fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
2201 let start = self.token.span;
2202 let expr = self.parse_expr_res(Restrictions::CONST_EXPR, None).map_err(|mut err| {
2204 start.shrink_to_lo(),
2205 "while parsing a const generic argument starting here",
2209 if !self.expr_is_valid_const_arg(&expr) {
2210 self.struct_span_err(
2212 "expressions must be enclosed in braces to be used as const generic \
2215 .multipart_suggestion(
2216 "enclose the `const` expression in braces",
2218 (expr.span.shrink_to_lo(), "{ ".to_string()),
2219 (expr.span.shrink_to_hi(), " }".to_string()),
2221 Applicability::MachineApplicable,
2228 fn recover_const_param_decl(&mut self, ty_generics: Option<&Generics>) -> Option<GenericArg> {
2229 let snapshot = self.create_snapshot_for_diagnostic();
2230 let param = match self.parse_const_param(vec![]) {
2234 self.restore_snapshot(snapshot);
2239 self.struct_span_err(param.span(), "unexpected `const` parameter declaration");
2240 err.span_label(param.span(), "expected a `const` expression, not a parameter declaration");
2241 if let (Some(generics), Ok(snippet)) =
2242 (ty_generics, self.sess.source_map().span_to_snippet(param.span()))
2244 let (span, sugg) = match &generics.params[..] {
2245 [] => (generics.span, format!("<{snippet}>")),
2246 [.., generic] => (generic.span().shrink_to_hi(), format!(", {snippet}")),
2248 err.multipart_suggestion(
2249 "`const` parameters must be declared for the `impl`",
2250 vec![(span, sugg), (param.span(), param.ident.to_string())],
2251 Applicability::MachineApplicable,
2254 let value = self.mk_expr_err(param.span());
2256 Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }))
2259 pub fn recover_const_param_declaration(
2261 ty_generics: Option<&Generics>,
2262 ) -> PResult<'a, Option<GenericArg>> {
2263 // We have to check for a few different cases.
2264 if let Some(arg) = self.recover_const_param_decl(ty_generics) {
2265 return Ok(Some(arg));
2268 // We haven't consumed `const` yet.
2269 let start = self.token.span;
2270 self.bump(); // `const`
2272 // Detect and recover from the old, pre-RFC2000 syntax for const generics.
2274 .struct_span_err(start, "expected lifetime, type, or constant, found keyword `const`");
2275 if self.check_const_arg() {
2276 err.span_suggestion_verbose(
2277 start.until(self.token.span),
2278 "the `const` keyword is only needed in the definition of the type",
2280 Applicability::MaybeIncorrect,
2283 Ok(Some(GenericArg::Const(self.parse_const_arg()?)))
2285 let after_kw_const = self.token.span;
2286 self.recover_const_arg(after_kw_const, err).map(Some)
2290 /// Try to recover from possible generic const argument without `{` and `}`.
2292 /// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
2293 /// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
2294 /// if we think that that the resulting expression would be well formed.
2295 pub fn recover_const_arg(
2298 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2299 ) -> PResult<'a, GenericArg> {
2300 let is_op_or_dot = AssocOp::from_token(&self.token)
2302 if let AssocOp::Greater
2304 | AssocOp::ShiftRight
2305 | AssocOp::GreaterEqual
2306 // Don't recover from `foo::<bar = baz>`, because this could be an attempt to
2307 // assign a value to a defaulted generic parameter.
2309 | AssocOp::AssignOp(_) = op
2317 || self.token.kind == TokenKind::Dot;
2318 // This will be true when a trait object type `Foo +` or a path which was a `const fn` with
2319 // type params has been parsed.
2321 matches!(self.prev_token.kind, token::BinOp(token::Plus | token::Shr) | token::Gt);
2322 if !is_op_or_dot && !was_op {
2323 // We perform these checks and early return to avoid taking a snapshot unnecessarily.
2326 let snapshot = self.create_snapshot_for_diagnostic();
2330 match self.parse_expr_res(Restrictions::CONST_EXPR, None) {
2332 // Find a mistake like `MyTrait<Assoc == S::Assoc>`.
2333 if token::EqEq == snapshot.token.kind {
2334 err.span_suggestion(
2335 snapshot.token.span,
2336 "if you meant to use an associated type binding, replace `==` with `=`",
2338 Applicability::MaybeIncorrect,
2340 let value = self.mk_expr_err(start.to(expr.span));
2342 return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
2343 } else if token::Colon == snapshot.token.kind
2344 && expr.span.lo() == snapshot.token.span.hi()
2345 && matches!(expr.kind, ExprKind::Path(..))
2347 // Find a mistake like "foo::var:A".
2348 err.span_suggestion(
2349 snapshot.token.span,
2350 "write a path separator here",
2352 Applicability::MaybeIncorrect,
2355 return Ok(GenericArg::Type(self.mk_ty(start.to(expr.span), TyKind::Err)));
2356 } else if token::Comma == self.token.kind || self.token.kind.should_end_const_arg()
2358 // Avoid the following output by checking that we consumed a full const arg:
2359 // help: expressions must be enclosed in braces to be used as const generic
2362 // LL | let sr: Vec<{ (u32, _, _) = vec![] };
2364 return Ok(self.dummy_const_arg_needs_braces(err, start.to(expr.span)));
2371 self.restore_snapshot(snapshot);
2375 /// Creates a dummy const argument, and reports that the expression must be enclosed in braces
2376 pub fn dummy_const_arg_needs_braces(
2378 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2381 err.multipart_suggestion(
2382 "expressions must be enclosed in braces to be used as const generic \
2384 vec![(span.shrink_to_lo(), "{ ".to_string()), (span.shrink_to_hi(), " }".to_string())],
2385 Applicability::MaybeIncorrect,
2387 let value = self.mk_expr_err(span);
2389 GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })
2392 /// Get the diagnostics for the cases where `move async` is found.
2394 /// `move_async_span` starts at the 'm' of the move keyword and ends with the 'c' of the async keyword
2395 pub(super) fn incorrect_move_async_order_found(
2397 move_async_span: Span,
2398 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2400 self.struct_span_err(move_async_span, "the order of `move` and `async` is incorrect");
2401 err.span_suggestion_verbose(
2403 "try switching the order",
2404 "async move".to_owned(),
2405 Applicability::MaybeIncorrect,
2410 /// Some special error handling for the "top-level" patterns in a match arm,
2411 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2412 crate fn maybe_recover_colon_colon_in_pat_typo(
2414 mut first_pat: P<Pat>,
2418 if RecoverColon::Yes != ra || token::Colon != self.token.kind {
2421 if !matches!(first_pat.kind, PatKind::Ident(_, _, None) | PatKind::Path(..))
2422 || !self.look_ahead(1, |token| token.is_ident() && !token.is_reserved_ident())
2426 // The pattern looks like it might be a path with a `::` -> `:` typo:
2427 // `match foo { bar:baz => {} }`
2428 let span = self.token.span;
2429 // We only emit "unexpected `:`" error here if we can successfully parse the
2430 // whole pattern correctly in that case.
2431 let snapshot = self.create_snapshot_for_diagnostic();
2433 // Create error for "unexpected `:`".
2434 match self.expected_one_of_not_found(&[], &[]) {
2436 self.bump(); // Skip the `:`.
2437 match self.parse_pat_no_top_alt(expected) {
2439 // Carry on as if we had not done anything, callers will emit a
2440 // reasonable error.
2443 self.restore_snapshot(snapshot);
2446 // We've parsed the rest of the pattern.
2447 let new_span = first_pat.span.to(pat.span);
2448 let mut show_sugg = false;
2449 // Try to construct a recovered pattern.
2450 match &mut pat.kind {
2451 PatKind::Struct(qself @ None, path, ..)
2452 | PatKind::TupleStruct(qself @ None, path, _)
2453 | PatKind::Path(qself @ None, path) => match &first_pat.kind {
2454 PatKind::Ident(_, ident, _) => {
2455 path.segments.insert(0, PathSegment::from_ident(*ident));
2456 path.span = new_span;
2460 PatKind::Path(old_qself, old_path) => {
2461 path.segments = old_path
2465 .chain(take(&mut path.segments))
2467 path.span = new_span;
2468 *qself = old_qself.clone();
2474 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
2475 match &first_pat.kind {
2476 PatKind::Ident(_, old_ident, _) => {
2477 let path = PatKind::Path(
2482 PathSegment::from_ident(*old_ident),
2483 PathSegment::from_ident(*ident),
2488 first_pat = self.mk_pat(new_span, path);
2491 PatKind::Path(old_qself, old_path) => {
2492 let mut segments = old_path.segments.clone();
2493 segments.push(PathSegment::from_ident(*ident));
2494 let path = PatKind::Path(
2496 Path { span: new_span, segments, tokens: None },
2498 first_pat = self.mk_pat(new_span, path);
2507 err.span_suggestion(
2509 "maybe write a path separator here",
2511 Applicability::MaybeIncorrect,
2514 first_pat = self.mk_pat(new_span, PatKind::Wild);
2521 // Carry on as if we had not done anything. This should be unreachable.
2522 self.restore_snapshot(snapshot);
2528 crate fn maybe_recover_unexpected_block_label(&mut self) -> bool {
2529 let Some(label) = self.eat_label().filter(|_| {
2530 self.eat(&token::Colon) && self.token.kind == token::OpenDelim(token::Brace)
2534 let span = label.ident.span.to(self.prev_token.span);
2535 let mut err = self.struct_span_err(span, "block label not supported here");
2536 err.span_label(span, "not supported here");
2537 err.tool_only_span_suggestion(
2538 label.ident.span.until(self.token.span),
2539 "remove this block label",
2541 Applicability::MachineApplicable,
2547 /// Some special error handling for the "top-level" patterns in a match arm,
2548 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2549 crate fn maybe_recover_unexpected_comma(
2553 rt: CommaRecoveryMode,
2554 ) -> PResult<'a, ()> {
2555 if rc == RecoverComma::No || self.token != token::Comma {
2559 // An unexpected comma after a top-level pattern is a clue that the
2560 // user (perhaps more accustomed to some other language) forgot the
2561 // parentheses in what should have been a tuple pattern; return a
2562 // suggestion-enhanced error here rather than choking on the comma later.
2563 let comma_span = self.token.span;
2565 if let Err(err) = self.skip_pat_list() {
2566 // We didn't expect this to work anyway; we just wanted to advance to the
2567 // end of the comma-sequence so we know the span to suggest parenthesizing.
2570 let seq_span = lo.to(self.prev_token.span);
2571 let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
2572 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
2573 err.multipart_suggestion(
2575 "try adding parentheses to match on a tuple{}",
2576 if let CommaRecoveryMode::LikelyTuple = rt { "" } else { "..." },
2579 (seq_span.shrink_to_lo(), "(".to_string()),
2580 (seq_span.shrink_to_hi(), ")".to_string()),
2582 Applicability::MachineApplicable,
2584 if let CommaRecoveryMode::EitherTupleOrPipe = rt {
2585 err.span_suggestion(
2587 "...or a vertical bar to match on multiple alternatives",
2588 seq_snippet.replace(',', " |"),
2589 Applicability::MachineApplicable,
2596 crate fn maybe_recover_bounds_doubled_colon(&mut self, ty: &Ty) -> PResult<'a, ()> {
2597 let TyKind::Path(qself, path) = &ty.kind else { return Ok(()) };
2598 let qself_position = qself.as_ref().map(|qself| qself.position);
2599 for (i, segments) in path.segments.windows(2).enumerate() {
2600 if qself_position.map(|pos| i < pos).unwrap_or(false) {
2603 if let [a, b] = segments {
2604 let (a_span, b_span) = (a.span(), b.span());
2605 let between_span = a_span.shrink_to_hi().to(b_span.shrink_to_lo());
2606 if self.span_to_snippet(between_span).as_ref().map(|a| &a[..]) == Ok(":: ") {
2607 let mut err = self.struct_span_err(
2608 path.span.shrink_to_hi(),
2609 "expected `:` followed by trait or lifetime",
2611 err.span_suggestion(
2615 Applicability::MachineApplicable,
2624 /// Parse and throw away a parenthesized comma separated
2625 /// sequence of patterns until `)` is reached.
2626 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
2627 while !self.check(&token::CloseDelim(token::Paren)) {
2628 self.parse_pat_no_top_alt(None)?;
2629 if !self.eat(&token::Comma) {