1 use super::pat::Expected;
3 BlockMode, CommaRecoveryMode, Parser, PathStyle, Restrictions, SemiColonMode, SeqSep,
4 TokenExpectType, TokenType,
7 AmbiguousPlus, AttributeOnParamType, BadQPathStage2, BadTypePlus, BadTypePlusSub,
8 ComparisonOperatorsCannotBeChained, ComparisonOperatorsCannotBeChainedSugg,
9 ConstGenericWithoutBraces, ConstGenericWithoutBracesSugg, DocCommentOnParamType,
10 DoubleColonInBound, ExpectedIdentifier, ExpectedSemi, ExpectedSemiSugg,
11 GenericParamsWithoutAngleBrackets, GenericParamsWithoutAngleBracketsSugg, InInTypo,
12 IncorrectAwait, IncorrectSemicolon, IncorrectUseOfAwait, ParenthesesInForHead,
13 ParenthesesInForHeadSugg, PatternMethodParamWithoutBody, QuestionMarkInType,
14 QuestionMarkInTypeSugg, SelfParamNotFirst, StructLiteralBodyWithoutPath,
15 StructLiteralBodyWithoutPathSugg, SuggEscapeToUseAsIdentifier, SuggRemoveComma,
16 UnexpectedConstInGenericParam, UnexpectedConstParamDeclaration,
17 UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets, UseEqInstead,
20 use crate::lexer::UnmatchedBrace;
23 use rustc_ast::ptr::P;
24 use rustc_ast::token::{self, Delimiter, Lit, LitKind, TokenKind};
25 use rustc_ast::util::parser::AssocOp;
27 AngleBracketedArg, AngleBracketedArgs, AnonConst, AttrVec, BinOpKind, BindingAnnotation, Block,
28 BlockCheckMode, Expr, ExprKind, GenericArg, Generics, Item, ItemKind, Param, Pat, PatKind,
29 Path, PathSegment, QSelf, Ty, TyKind,
31 use rustc_ast_pretty::pprust;
32 use rustc_data_structures::fx::FxHashSet;
34 fluent, Applicability, DiagnosticBuilder, DiagnosticMessage, Handler, MultiSpan, PResult,
36 use rustc_errors::{pluralize, Diagnostic, ErrorGuaranteed, IntoDiagnostic};
37 use rustc_session::errors::ExprParenthesesNeeded;
38 use rustc_span::source_map::Spanned;
39 use rustc_span::symbol::{kw, sym, Ident};
40 use rustc_span::{Span, SpanSnippetError, DUMMY_SP};
42 use std::ops::{Deref, DerefMut};
43 use thin_vec::{thin_vec, ThinVec};
45 /// Creates a placeholder argument.
46 pub(super) fn dummy_arg(ident: Ident) -> Param {
48 id: ast::DUMMY_NODE_ID,
49 kind: PatKind::Ident(BindingAnnotation::NONE, ident, None),
53 let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID, tokens: None };
55 attrs: AttrVec::default(),
56 id: ast::DUMMY_NODE_ID,
60 is_placeholder: false,
64 pub(super) trait RecoverQPath: Sized + 'static {
65 const PATH_STYLE: PathStyle = PathStyle::Expr;
66 fn to_ty(&self) -> Option<P<Ty>>;
67 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self;
70 impl RecoverQPath for Ty {
71 const PATH_STYLE: PathStyle = PathStyle::Type;
72 fn to_ty(&self) -> Option<P<Ty>> {
75 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
78 kind: TyKind::Path(qself, path),
79 id: ast::DUMMY_NODE_ID,
85 impl RecoverQPath for Pat {
86 fn to_ty(&self) -> Option<P<Ty>> {
89 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
92 kind: PatKind::Path(qself, path),
93 id: ast::DUMMY_NODE_ID,
99 impl RecoverQPath for Expr {
100 fn to_ty(&self) -> Option<P<Ty>> {
103 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
106 kind: ExprKind::Path(qself, path),
107 attrs: AttrVec::new(),
108 id: ast::DUMMY_NODE_ID,
114 /// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
115 pub(crate) enum ConsumeClosingDelim {
120 #[derive(Clone, Copy)]
121 pub enum AttemptLocalParseRecovery {
126 impl AttemptLocalParseRecovery {
127 pub fn yes(&self) -> bool {
129 AttemptLocalParseRecovery::Yes => true,
130 AttemptLocalParseRecovery::No => false,
134 pub fn no(&self) -> bool {
136 AttemptLocalParseRecovery::Yes => false,
137 AttemptLocalParseRecovery::No => true,
142 /// Information for emitting suggestions and recovering from
143 /// C-style `i++`, `--i`, etc.
144 #[derive(Debug, Copy, Clone)]
145 struct IncDecRecovery {
146 /// Is this increment/decrement its own statement?
147 standalone: IsStandalone,
148 /// Is this an increment or decrement?
150 /// Is this pre- or postfix?
154 /// Is an increment or decrement expression its own statement?
155 #[derive(Debug, Copy, Clone)]
157 /// It's standalone, i.e., its own statement.
159 /// It's a subexpression, i.e., *not* standalone.
163 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
166 // FIXME: `i--` recovery isn't implemented yet
171 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
178 fn chr(&self) -> char {
185 fn name(&self) -> &'static str {
187 Self::Inc => "increment",
188 Self::Dec => "decrement",
193 impl std::fmt::Display for UnaryFixity {
194 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196 Self::Pre => write!(f, "prefix"),
197 Self::Post => write!(f, "postfix"),
204 patches: Vec<(Span, String)>,
205 applicability: Applicability,
209 fn emit(self, err: &mut Diagnostic) {
210 err.multipart_suggestion(&self.msg, self.patches, self.applicability);
213 fn emit_verbose(self, err: &mut Diagnostic) {
214 err.multipart_suggestion_verbose(&self.msg, self.patches, self.applicability);
218 /// SnapshotParser is used to create a snapshot of the parser
219 /// without causing duplicate errors being emitted when the `Parser`
221 pub struct SnapshotParser<'a> {
223 unclosed_delims: Vec<UnmatchedBrace>,
226 impl<'a> Deref for SnapshotParser<'a> {
227 type Target = Parser<'a>;
229 fn deref(&self) -> &Self::Target {
234 impl<'a> DerefMut for SnapshotParser<'a> {
235 fn deref_mut(&mut self) -> &mut Self::Target {
240 impl<'a> Parser<'a> {
241 #[rustc_lint_diagnostics]
242 pub fn struct_span_err<S: Into<MultiSpan>>(
245 m: impl Into<DiagnosticMessage>,
246 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
247 self.sess.span_diagnostic.struct_span_err(sp, m)
250 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: impl Into<DiagnosticMessage>) -> ! {
251 self.sess.span_diagnostic.span_bug(sp, m)
254 pub(super) fn diagnostic(&self) -> &'a Handler {
255 &self.sess.span_diagnostic
258 /// Replace `self` with `snapshot.parser` and extend `unclosed_delims` with `snapshot.unclosed_delims`.
259 /// This is to avoid losing unclosed delims errors `create_snapshot_for_diagnostic` clears.
260 pub(super) fn restore_snapshot(&mut self, snapshot: SnapshotParser<'a>) {
261 *self = snapshot.parser;
262 self.unclosed_delims.extend(snapshot.unclosed_delims);
265 pub fn unclosed_delims(&self) -> &[UnmatchedBrace] {
266 &self.unclosed_delims
269 /// Create a snapshot of the `Parser`.
270 pub fn create_snapshot_for_diagnostic(&self) -> SnapshotParser<'a> {
271 let mut snapshot = self.clone();
272 let unclosed_delims = self.unclosed_delims.clone();
273 // Clear `unclosed_delims` in snapshot to avoid
274 // duplicate errors being emitted when the `Parser`
275 // is dropped (which may or may not happen, depending
276 // if the parsing the snapshot is created for is successful)
277 snapshot.unclosed_delims.clear();
278 SnapshotParser { parser: snapshot, unclosed_delims }
281 pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
282 self.sess.source_map().span_to_snippet(span)
285 pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
286 let valid_follow = &[
292 TokenKind::OpenDelim(Delimiter::Brace),
293 TokenKind::OpenDelim(Delimiter::Parenthesis),
294 TokenKind::CloseDelim(Delimiter::Brace),
295 TokenKind::CloseDelim(Delimiter::Parenthesis),
297 let suggest_raw = match self.token.ident() {
299 if ident.is_raw_guess()
300 && self.look_ahead(1, |t| valid_follow.contains(&t.kind)) =>
302 Some(SuggEscapeToUseAsIdentifier {
303 span: ident.span.shrink_to_lo(),
304 // `Symbol::to_string()` is different from `Symbol::into_diagnostic_arg()`,
305 // which uses `Symbol::to_ident_string()` and "helpfully" adds an implicit `r#`
306 ident_name: ident.name.to_string(),
312 let suggest_remove_comma =
313 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
314 Some(SuggRemoveComma { span: self.token.span })
319 let err = ExpectedIdentifier {
320 span: self.token.span,
321 token: self.token.clone(),
323 suggest_remove_comma,
325 err.into_diagnostic(&self.sess.span_diagnostic)
328 pub(super) fn expected_one_of_not_found(
330 edible: &[TokenKind],
331 inedible: &[TokenKind],
332 ) -> PResult<'a, bool /* recovered */> {
333 debug!("expected_one_of_not_found(edible: {:?}, inedible: {:?})", edible, inedible);
334 fn tokens_to_string(tokens: &[TokenType]) -> String {
335 let mut i = tokens.iter();
336 // This might be a sign we need a connect method on `Iterator`.
337 let b = i.next().map_or_else(String::new, |t| t.to_string());
338 i.enumerate().fold(b, |mut b, (i, a)| {
339 if tokens.len() > 2 && i == tokens.len() - 2 {
341 } else if tokens.len() == 2 && i == tokens.len() - 2 {
346 b.push_str(&a.to_string());
351 let mut expected = edible
353 .map(|x| TokenType::Token(x.clone()))
354 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
355 .chain(self.expected_tokens.iter().cloned())
356 .filter_map(|token| {
357 // filter out suggestions which suggest the same token which was found and deemed incorrect
358 fn is_ident_eq_keyword(found: &TokenKind, expected: &TokenType) -> bool {
359 if let TokenKind::Ident(current_sym, _) = found {
360 if let TokenType::Keyword(suggested_sym) = expected {
361 return current_sym == suggested_sym;
366 if token != parser::TokenType::Token(self.token.kind.clone()) {
367 let eq = is_ident_eq_keyword(&self.token.kind, &token);
368 // if the suggestion is a keyword and the found token is an ident,
369 // the content of which are equal to the suggestion's content,
370 // we can remove that suggestion (see the return None statement below)
372 // if this isn't the case however, and the suggestion is a token the
373 // content of which is the same as the found token's, we remove it as well
375 if let TokenType::Token(kind) = &token {
376 if kind == &self.token.kind {
385 .collect::<Vec<_>>();
386 expected.sort_by_cached_key(|x| x.to_string());
389 let sm = self.sess.source_map();
391 // Special-case "expected `;`" errors
392 if expected.contains(&TokenType::Token(token::Semi)) {
393 if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
394 // Likely inside a macro, can't provide meaningful suggestions.
395 } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
396 // The current token is in the same line as the prior token, not recoverable.
397 } else if [token::Comma, token::Colon].contains(&self.token.kind)
398 && self.prev_token.kind == token::CloseDelim(Delimiter::Parenthesis)
400 // Likely typo: The current token is on a new line and is expected to be
401 // `.`, `;`, `?`, or an operator after a close delimiter token.
403 // let a = std::process::Command::new("echo")
407 // https://github.com/rust-lang/rust/issues/72253
408 } else if self.look_ahead(1, |t| {
409 t == &token::CloseDelim(Delimiter::Brace)
410 || t.can_begin_expr() && t.kind != token::Colon
411 }) && [token::Comma, token::Colon].contains(&self.token.kind)
413 // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is
414 // either `,` or `:`, and the next token could either start a new statement or is a
415 // block close. For example:
419 self.sess.emit_err(ExpectedSemi {
420 span: self.token.span,
421 token: self.token.clone(),
422 unexpected_token_label: None,
423 sugg: ExpectedSemiSugg::ChangeToSemi(self.token.span),
427 } else if self.look_ahead(0, |t| {
428 t == &token::CloseDelim(Delimiter::Brace)
429 || ((t.can_begin_expr() || t.can_begin_item())
431 && t != &token::Pound)
432 // Avoid triggering with too many trailing `#` in raw string.
434 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
435 ) && t == &token::Pound)
436 }) && !expected.contains(&TokenType::Token(token::Comma))
438 // Missing semicolon typo. This is triggered if the next token could either start a
439 // new statement or is a block close. For example:
443 let span = self.prev_token.span.shrink_to_hi();
444 self.sess.emit_err(ExpectedSemi {
446 token: self.token.clone(),
447 unexpected_token_label: Some(self.token.span),
448 sugg: ExpectedSemiSugg::AddSemi(span),
454 if self.token.kind == TokenKind::EqEq
455 && self.prev_token.is_ident()
456 && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Eq)))
458 // Likely typo: `=` → `==` in let expr or enum item
459 return Err(self.sess.create_err(UseEqInstead { span: self.token.span }));
462 let expect = tokens_to_string(&expected);
463 let actual = super::token_descr(&self.token);
464 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
465 let short_expect = if expected.len() > 6 {
466 format!("{} possible tokens", expected.len())
471 format!("expected one of {expect}, found {actual}"),
472 (self.prev_token.span.shrink_to_hi(), format!("expected one of {short_expect}")),
474 } else if expected.is_empty() {
476 format!("unexpected token: {actual}"),
477 (self.prev_token.span, "unexpected token after this".to_string()),
481 format!("expected {expect}, found {actual}"),
482 (self.prev_token.span.shrink_to_hi(), format!("expected {expect}")),
485 self.last_unexpected_token_span = Some(self.token.span);
486 // FIXME: translation requires list formatting (for `expect`)
487 let mut err = self.struct_span_err(self.token.span, &msg_exp);
489 if let TokenKind::Ident(symbol, _) = &self.prev_token.kind {
490 if ["def", "fun", "func", "function"].contains(&symbol.as_str()) {
491 err.span_suggestion_short(
492 self.prev_token.span,
493 &format!("write `fn` instead of `{symbol}` to declare a function"),
495 Applicability::MachineApplicable,
500 // `pub` may be used for an item or `pub(crate)`
501 if self.prev_token.is_ident_named(sym::public)
502 && (self.token.can_begin_item()
503 || self.token.kind == TokenKind::OpenDelim(Delimiter::Parenthesis))
505 err.span_suggestion_short(
506 self.prev_token.span,
507 "write `pub` instead of `public` to make the item public",
509 Applicability::MachineApplicable,
513 // Add suggestion for a missing closing angle bracket if '>' is included in expected_tokens
514 // there are unclosed angle brackets
515 if self.unmatched_angle_bracket_count > 0
516 && self.token.kind == TokenKind::Eq
517 && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Gt)))
519 err.span_label(self.prev_token.span, "maybe try to close unmatched angle bracket");
522 let sp = if self.token == token::Eof {
523 // This is EOF; don't want to point at the following char, but rather the last token.
528 match self.recover_closing_delimiter(
531 .filter_map(|tt| match tt {
532 TokenType::Token(t) => Some(t.clone()),
535 .collect::<Vec<_>>(),
540 return Ok(recovered);
544 if self.check_too_many_raw_str_terminators(&mut err) {
545 if expected.contains(&TokenType::Token(token::Semi)) && self.eat(&token::Semi) {
553 if self.prev_token.span == DUMMY_SP {
554 // Account for macro context where the previous span might not be
555 // available to avoid incorrect output (#54841).
556 err.span_label(self.token.span, label_exp);
557 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
558 // When the spans are in the same line, it means that the only content between
559 // them is whitespace, point at the found token in that case:
561 // X | () => { syntax error };
562 // | ^^^^^ expected one of 8 possible tokens here
564 // instead of having:
566 // X | () => { syntax error };
567 // | -^^^^^ unexpected token
569 // | expected one of 8 possible tokens here
570 err.span_label(self.token.span, label_exp);
572 err.span_label(sp, label_exp);
573 err.span_label(self.token.span, "unexpected token");
575 self.maybe_annotate_with_ascription(&mut err, false);
579 fn check_too_many_raw_str_terminators(&mut self, err: &mut Diagnostic) -> bool {
580 let sm = self.sess.source_map();
581 match (&self.prev_token.kind, &self.token.kind) {
583 TokenKind::Literal(Lit {
584 kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
588 ) if !sm.is_multiline(
589 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
592 let n_hashes: u8 = *n_hashes;
593 err.set_primary_message("too many `#` when terminating raw string");
594 let str_span = self.prev_token.span;
595 let mut span = self.token.span;
597 while self.token.kind == TokenKind::Pound
598 && !sm.is_multiline(span.shrink_to_hi().until(self.token.span.shrink_to_lo()))
600 span = span.with_hi(self.token.span.hi());
607 &format!("remove the extra `#`{}", pluralize!(count)),
609 Applicability::MachineApplicable,
613 &format!("this raw string started with {n_hashes} `#`{}", pluralize!(n_hashes)),
621 pub fn maybe_suggest_struct_literal(
625 ) -> Option<PResult<'a, P<Block>>> {
626 if self.token.is_ident() && self.look_ahead(1, |t| t == &token::Colon) {
627 // We might be having a struct literal where people forgot to include the path:
631 let mut snapshot = self.create_snapshot_for_diagnostic();
633 segments: ThinVec::new(),
634 span: self.prev_token.span.shrink_to_lo(),
637 let struct_expr = snapshot.parse_struct_expr(None, path, false);
638 let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No);
639 return Some(match (struct_expr, block_tail) {
640 (Ok(expr), Err(mut err)) => {
641 // We have encountered the following:
646 // fn foo() -> Foo { Path {
650 self.sess.emit_err(StructLiteralBodyWithoutPath {
652 sugg: StructLiteralBodyWithoutPathSugg {
653 before: expr.span.shrink_to_lo(),
654 after: expr.span.shrink_to_hi(),
657 self.restore_snapshot(snapshot);
658 let mut tail = self.mk_block(
659 vec![self.mk_stmt_err(expr.span)],
661 lo.to(self.prev_token.span),
663 tail.could_be_bare_literal = true;
666 (Err(err), Ok(tail)) => {
667 // We have a block tail that contains a somehow valid type ascription expr.
671 (Err(snapshot_err), Err(err)) => {
672 // We don't know what went wrong, emit the normal error.
673 snapshot_err.cancel();
674 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
677 (Ok(_), Ok(mut tail)) => {
678 tail.could_be_bare_literal = true;
686 pub fn maybe_annotate_with_ascription(
688 err: &mut Diagnostic,
689 maybe_expected_semicolon: bool,
691 if let Some((sp, likely_path)) = self.last_type_ascription.take() {
692 let sm = self.sess.source_map();
693 let next_pos = sm.lookup_char_pos(self.token.span.lo());
694 let op_pos = sm.lookup_char_pos(sp.hi());
696 let allow_unstable = self.sess.unstable_features.is_nightly_build();
701 "maybe write a path separator here",
704 Applicability::MaybeIncorrect
706 Applicability::MachineApplicable
709 self.sess.type_ascription_path_suggestions.borrow_mut().insert(sp);
710 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
713 "try using a semicolon",
715 Applicability::MaybeIncorrect,
717 } else if allow_unstable {
718 err.span_label(sp, "tried to parse a type due to this type ascription");
720 err.span_label(sp, "tried to parse a type due to this");
723 // Give extra information about type ascription only if it's a nightly compiler.
725 "`#![feature(type_ascription)]` lets you annotate an expression with a type: \
729 // Avoid giving too much info when it was likely an unrelated typo.
731 "see issue #23416 <https://github.com/rust-lang/rust/issues/23416> \
732 for more information",
739 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
740 /// passes through any errors encountered. Used for error recovery.
741 pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
743 self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
744 Ok(p.parse_token_tree())
751 /// This function checks if there are trailing angle brackets and produces
752 /// a diagnostic to suggest removing them.
754 /// ```ignore (diagnostic)
755 /// let _ = [1, 2, 3].into_iter().collect::<Vec<usize>>>>();
756 /// ^^ help: remove extra angle brackets
759 /// If `true` is returned, then trailing brackets were recovered, tokens were consumed
760 /// up until one of the tokens in 'end' was encountered, and an error was emitted.
761 pub(super) fn check_trailing_angle_brackets(
763 segment: &PathSegment,
766 if !self.may_recover() {
770 // This function is intended to be invoked after parsing a path segment where there are two
773 // 1. A specific token is expected after the path segment.
774 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
775 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
776 // 2. No specific token is expected after the path segment.
777 // eg. `x.foo` (field access)
779 // This function is called after parsing `.foo` and before parsing the token `end` (if
780 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
783 // We only care about trailing angle brackets if we previously parsed angle bracket
784 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
785 // removed in this case:
787 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
789 // This case is particularly tricky as we won't notice it just looking at the tokens -
790 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
791 // have already been parsed):
793 // `x.foo::<u32>>>(3)`
794 let parsed_angle_bracket_args =
795 segment.args.as_ref().map_or(false, |args| args.is_angle_bracketed());
798 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
799 parsed_angle_bracket_args,
801 if !parsed_angle_bracket_args {
805 // Keep the span at the start so we can highlight the sequence of `>` characters to be
807 let lo = self.token.span;
809 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
810 // (since we might have the field access case and the characters we're eating are
811 // actual operators and not trailing characters - ie `x.foo >> 3`).
812 let mut position = 0;
814 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
815 // many of each (so we can correctly pluralize our error messages) and continue to
817 let mut number_of_shr = 0;
818 let mut number_of_gt = 0;
819 while self.look_ahead(position, |t| {
820 trace!("check_trailing_angle_brackets: t={:?}", t);
821 if *t == token::BinOp(token::BinOpToken::Shr) {
824 } else if *t == token::Gt {
834 // If we didn't find any trailing `>` characters, then we have nothing to error about.
836 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
837 number_of_gt, number_of_shr,
839 if number_of_gt < 1 && number_of_shr < 1 {
843 // Finally, double check that we have our end token as otherwise this is the
845 if self.look_ahead(position, |t| {
846 trace!("check_trailing_angle_brackets: t={:?}", t);
847 end.contains(&&t.kind)
849 // Eat from where we started until the end token so that parsing can continue
850 // as if we didn't have those extra angle brackets.
851 self.eat_to_tokens(end);
852 let span = lo.until(self.token.span);
854 let num_extra_brackets = number_of_gt + number_of_shr * 2;
855 self.sess.emit_err(UnmatchedAngleBrackets { span, num_extra_brackets });
861 /// Check if a method call with an intended turbofish has been written without surrounding
863 pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
864 if !self.may_recover() {
868 if token::ModSep == self.token.kind && segment.args.is_none() {
869 let snapshot = self.create_snapshot_for_diagnostic();
871 let lo = self.token.span;
872 match self.parse_angle_args(None) {
874 let span = lo.to(self.prev_token.span);
875 // Detect trailing `>` like in `x.collect::Vec<_>>()`.
876 let mut trailing_span = self.prev_token.span.shrink_to_hi();
877 while self.token.kind == token::BinOp(token::Shr)
878 || self.token.kind == token::Gt
880 trailing_span = trailing_span.to(self.token.span);
883 if self.token.kind == token::OpenDelim(Delimiter::Parenthesis) {
884 // Recover from bad turbofish: `foo.collect::Vec<_>()`.
885 let args = AngleBracketedArgs { args, span }.into();
888 self.sess.emit_err(GenericParamsWithoutAngleBrackets {
890 sugg: GenericParamsWithoutAngleBracketsSugg {
891 left: span.shrink_to_lo(),
892 right: trailing_span,
896 // This doesn't look like an invalid turbofish, can't recover parse state.
897 self.restore_snapshot(snapshot);
901 // We couldn't parse generic parameters, unlikely to be a turbofish. Rely on
902 // generic parse error instead.
904 self.restore_snapshot(snapshot);
910 /// When writing a turbofish with multiple type parameters missing the leading `::`, we will
911 /// encounter a parse error when encountering the first `,`.
912 pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
914 mut e: DiagnosticBuilder<'a, ErrorGuaranteed>,
916 ) -> PResult<'a, ()> {
917 if let ExprKind::Binary(binop, _, _) = &expr.kind
918 && let ast::BinOpKind::Lt = binop.node
919 && self.eat(&token::Comma)
921 let x = self.parse_seq_to_before_end(
923 SeqSep::trailing_allowed(token::Comma),
924 |p| p.parse_generic_arg(None),
927 Ok((_, _, false)) => {
928 if self.eat(&token::Gt) {
929 e.span_suggestion_verbose(
930 binop.span.shrink_to_lo(),
931 fluent::parse_sugg_turbofish_syntax,
933 Applicability::MaybeIncorrect,
936 match self.parse_expr() {
939 self.mk_expr_err(expr.span.to(self.prev_token.span));
943 *expr = self.mk_expr_err(expr.span);
958 /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
959 /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
960 /// parenthesising the leftmost comparison.
961 fn attempt_chained_comparison_suggestion(
963 err: &mut ComparisonOperatorsCannotBeChained,
965 outer_op: &Spanned<AssocOp>,
966 ) -> bool /* advanced the cursor */ {
967 if let ExprKind::Binary(op, l1, r1) = &inner_op.kind {
968 if let ExprKind::Field(_, ident) = l1.kind
969 && ident.as_str().parse::<i32>().is_err()
970 && !matches!(r1.kind, ExprKind::Lit(_))
972 // The parser has encountered `foo.bar<baz`, the likelihood of the turbofish
973 // suggestion being the only one to apply is high.
976 return match (op.node, &outer_op.node) {
978 (BinOpKind::Eq, AssocOp::Equal) |
979 // `x < y < z` and friends.
980 (BinOpKind::Lt, AssocOp::Less | AssocOp::LessEqual) |
981 (BinOpKind::Le, AssocOp::LessEqual | AssocOp::Less) |
982 // `x > y > z` and friends.
983 (BinOpKind::Gt, AssocOp::Greater | AssocOp::GreaterEqual) |
984 (BinOpKind::Ge, AssocOp::GreaterEqual | AssocOp::Greater) => {
985 let expr_to_str = |e: &Expr| {
986 self.span_to_snippet(e.span)
987 .unwrap_or_else(|_| pprust::expr_to_string(&e))
989 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::SplitComparison {
990 span: inner_op.span.shrink_to_hi(),
991 middle_term: expr_to_str(&r1),
993 false // Keep the current parse behavior, where the AST is `(x < y) < z`.
996 (BinOpKind::Eq, AssocOp::Less | AssocOp::LessEqual | AssocOp::Greater | AssocOp::GreaterEqual) => {
997 // Consume `z`/outer-op-rhs.
998 let snapshot = self.create_snapshot_for_diagnostic();
999 match self.parse_expr() {
1001 // We are sure that outer-op-rhs could be consumed, the suggestion is
1003 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1004 left: r1.span.shrink_to_lo(),
1005 right: r2.span.shrink_to_hi(),
1011 self.restore_snapshot(snapshot);
1017 (BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge, AssocOp::Equal) => {
1018 let snapshot = self.create_snapshot_for_diagnostic();
1019 // At this point it is always valid to enclose the lhs in parentheses, no
1020 // further checks are necessary.
1021 match self.parse_expr() {
1023 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1024 left: l1.span.shrink_to_lo(),
1025 right: r1.span.shrink_to_hi(),
1031 self.restore_snapshot(snapshot);
1042 /// Produces an error if comparison operators are chained (RFC #558).
1043 /// We only need to check the LHS, not the RHS, because all comparison ops have same
1044 /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
1046 /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
1047 /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
1050 /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
1051 /// associative we can infer that we have:
1060 pub(super) fn check_no_chained_comparison(
1063 outer_op: &Spanned<AssocOp>,
1064 ) -> PResult<'a, Option<P<Expr>>> {
1066 outer_op.node.is_comparison(),
1067 "check_no_chained_comparison: {:?} is not comparison",
1071 let mk_err_expr = |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err)));
1073 match &inner_op.kind {
1074 ExprKind::Binary(op, l1, r1) if op.node.is_comparison() => {
1075 let mut err = ComparisonOperatorsCannotBeChained {
1076 span: vec![op.span, self.prev_token.span],
1077 suggest_turbofish: None,
1078 help_turbofish: None,
1079 chaining_sugg: None,
1082 // Include `<` to provide this recommendation even in a case like
1083 // `Foo<Bar<Baz<Qux, ()>>>`
1084 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Less
1085 || outer_op.node == AssocOp::Greater
1087 if outer_op.node == AssocOp::Less {
1088 let snapshot = self.create_snapshot_for_diagnostic();
1090 // So far we have parsed `foo<bar<`, consume the rest of the type args.
1092 [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
1093 self.consume_tts(1, &modifiers);
1095 if !&[token::OpenDelim(Delimiter::Parenthesis), token::ModSep]
1096 .contains(&self.token.kind)
1098 // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
1099 // parser and bail out.
1100 self.restore_snapshot(snapshot);
1103 return if token::ModSep == self.token.kind {
1104 // We have some certainty that this was a bad turbofish at this point.
1106 err.suggest_turbofish = Some(op.span.shrink_to_lo());
1108 let snapshot = self.create_snapshot_for_diagnostic();
1109 self.bump(); // `::`
1111 // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
1112 match self.parse_expr() {
1114 // 99% certain that the suggestion is correct, continue parsing.
1115 self.sess.emit_err(err);
1116 // FIXME: actually check that the two expressions in the binop are
1117 // paths and resynthesize new fn call expression instead of using
1118 // `ExprKind::Err` placeholder.
1119 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1123 // Not entirely sure now, but we bubble the error up with the
1125 self.restore_snapshot(snapshot);
1126 Err(err.into_diagnostic(&self.sess.span_diagnostic))
1129 } else if token::OpenDelim(Delimiter::Parenthesis) == self.token.kind {
1130 // We have high certainty that this was a bad turbofish at this point.
1132 err.suggest_turbofish = Some(op.span.shrink_to_lo());
1133 // Consume the fn call arguments.
1134 match self.consume_fn_args() {
1135 Err(()) => Err(err.into_diagnostic(&self.sess.span_diagnostic)),
1137 self.sess.emit_err(err);
1138 // FIXME: actually check that the two expressions in the binop are
1139 // paths and resynthesize new fn call expression instead of using
1140 // `ExprKind::Err` placeholder.
1141 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1145 if !matches!(l1.kind, ExprKind::Lit(_))
1146 && !matches!(r1.kind, ExprKind::Lit(_))
1148 // All we know is that this is `foo < bar >` and *nothing* else. Try to
1149 // be helpful, but don't attempt to recover.
1150 err.help_turbofish = Some(());
1153 // If it looks like a genuine attempt to chain operators (as opposed to a
1154 // misformatted turbofish, for instance), suggest a correct form.
1155 if self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op)
1157 self.sess.emit_err(err);
1158 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1160 // These cases cause too many knock-down errors, bail out (#61329).
1161 Err(err.into_diagnostic(&self.sess.span_diagnostic))
1166 self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1167 self.sess.emit_err(err);
1169 return mk_err_expr(self, inner_op.span.to(self.prev_token.span));
1177 fn consume_fn_args(&mut self) -> Result<(), ()> {
1178 let snapshot = self.create_snapshot_for_diagnostic();
1181 // Consume the fn call arguments.
1183 (token::OpenDelim(Delimiter::Parenthesis), 1),
1184 (token::CloseDelim(Delimiter::Parenthesis), -1),
1186 self.consume_tts(1, &modifiers);
1188 if self.token.kind == token::Eof {
1189 // Not entirely sure that what we consumed were fn arguments, rollback.
1190 self.restore_snapshot(snapshot);
1193 // 99% certain that the suggestion is correct, continue parsing.
1198 pub(super) fn maybe_report_ambiguous_plus(&mut self, impl_dyn_multi: bool, ty: &Ty) {
1200 self.sess.emit_err(AmbiguousPlus { sum_ty: pprust::ty_to_string(&ty), span: ty.span });
1204 /// Swift lets users write `Ty?` to mean `Option<Ty>`. Parse the construct and recover from it.
1205 pub(super) fn maybe_recover_from_question_mark(&mut self, ty: P<Ty>) -> P<Ty> {
1206 if self.token == token::Question {
1208 self.sess.emit_err(QuestionMarkInType {
1209 span: self.prev_token.span,
1210 sugg: QuestionMarkInTypeSugg {
1211 left: ty.span.shrink_to_lo(),
1212 right: self.prev_token.span,
1215 self.mk_ty(ty.span.to(self.prev_token.span), TyKind::Err)
1221 pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> {
1222 // Do not add `+` to expected tokens.
1223 if !self.token.is_like_plus() {
1228 let bounds = self.parse_generic_bounds(None)?;
1229 let sum_span = ty.span.to(self.prev_token.span);
1231 let sub = match &ty.kind {
1232 TyKind::Ref(lifetime, mut_ty) => {
1233 let sum_with_parens = pprust::to_string(|s| {
1235 s.print_opt_lifetime(lifetime);
1236 s.print_mutability(mut_ty.mutbl, false);
1238 s.print_type(&mut_ty.ty);
1239 if !bounds.is_empty() {
1241 s.print_type_bounds(&bounds);
1246 BadTypePlusSub::AddParen { sum_with_parens, span: sum_span }
1248 TyKind::Ptr(..) | TyKind::BareFn(..) => BadTypePlusSub::ForgotParen { span: sum_span },
1249 _ => BadTypePlusSub::ExpectPath { span: sum_span },
1252 self.sess.emit_err(BadTypePlus { ty: pprust::ty_to_string(ty), span: sum_span, sub });
1257 pub(super) fn recover_from_prefix_increment(
1259 operand_expr: P<Expr>,
1262 ) -> PResult<'a, P<Expr>> {
1263 let standalone = if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr };
1264 let kind = IncDecRecovery { standalone, op: IncOrDec::Inc, fixity: UnaryFixity::Pre };
1265 self.recover_from_inc_dec(operand_expr, kind, op_span)
1268 pub(super) fn recover_from_postfix_increment(
1270 operand_expr: P<Expr>,
1273 ) -> PResult<'a, P<Expr>> {
1274 let kind = IncDecRecovery {
1275 standalone: if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr },
1277 fixity: UnaryFixity::Post,
1279 self.recover_from_inc_dec(operand_expr, kind, op_span)
1282 fn recover_from_inc_dec(
1285 kind: IncDecRecovery,
1287 ) -> PResult<'a, P<Expr>> {
1288 let mut err = self.struct_span_err(
1290 &format!("Rust has no {} {} operator", kind.fixity, kind.op.name()),
1292 err.span_label(op_span, &format!("not a valid {} operator", kind.fixity));
1294 let help_base_case = |mut err: DiagnosticBuilder<'_, _>, base| {
1295 err.help(&format!("use `{}= 1` instead", kind.op.chr()));
1301 let spans = match kind.fixity {
1302 UnaryFixity::Pre => (op_span, base.span.shrink_to_hi()),
1303 UnaryFixity::Post => (base.span.shrink_to_lo(), op_span),
1306 match kind.standalone {
1307 IsStandalone::Standalone => {
1308 self.inc_dec_standalone_suggest(kind, spans).emit_verbose(&mut err)
1310 IsStandalone::Subexpr => {
1311 let Ok(base_src) = self.span_to_snippet(base.span)
1312 else { return help_base_case(err, base) };
1314 UnaryFixity::Pre => {
1315 self.prefix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1317 UnaryFixity::Post => {
1318 // won't suggest since we can not handle the precedences
1319 // for example: `a + b++` has been parsed (a + b)++ and we can not suggest here
1320 if !matches!(base.kind, ExprKind::Binary(_, _, _)) {
1321 self.postfix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1330 fn prefix_inc_dec_suggest(
1333 kind: IncDecRecovery,
1334 (pre_span, post_span): (Span, Span),
1337 msg: format!("use `{}= 1` instead", kind.op.chr()),
1339 (pre_span, "{ ".to_string()),
1340 (post_span, format!(" {}= 1; {} }}", kind.op.chr(), base_src)),
1342 applicability: Applicability::MachineApplicable,
1346 fn postfix_inc_dec_suggest(
1349 kind: IncDecRecovery,
1350 (pre_span, post_span): (Span, Span),
1352 let tmp_var = if base_src.trim() == "tmp" { "tmp_" } else { "tmp" };
1354 msg: format!("use `{}= 1` instead", kind.op.chr()),
1356 (pre_span, format!("{{ let {tmp_var} = ")),
1357 (post_span, format!("; {} {}= 1; {} }}", base_src, kind.op.chr(), tmp_var)),
1359 applicability: Applicability::HasPlaceholders,
1363 fn inc_dec_standalone_suggest(
1365 kind: IncDecRecovery,
1366 (pre_span, post_span): (Span, Span),
1368 let mut patches = Vec::new();
1370 if !pre_span.is_empty() {
1371 patches.push((pre_span, String::new()));
1374 patches.push((post_span, format!(" {}= 1", kind.op.chr())));
1376 msg: format!("use `{}= 1` instead", kind.op.chr()),
1378 applicability: Applicability::MachineApplicable,
1382 /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
1383 /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
1384 /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
1385 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
1388 ) -> PResult<'a, P<T>> {
1389 if !self.may_recover() {
1393 // Do not add `::` to expected tokens.
1394 if self.token == token::ModSep {
1395 if let Some(ty) = base.to_ty() {
1396 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1402 /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
1403 /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
1404 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
1408 ) -> PResult<'a, P<T>> {
1409 self.expect(&token::ModSep)?;
1411 let mut path = ast::Path { segments: ThinVec::new(), span: DUMMY_SP, tokens: None };
1412 self.parse_path_segments(&mut path.segments, T::PATH_STYLE, None)?;
1413 path.span = ty_span.to(self.prev_token.span);
1415 let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
1416 self.sess.emit_err(BadQPathStage2 {
1418 ty: format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
1421 let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
1422 Ok(P(T::recovered(Some(P(QSelf { ty, path_span, position: 0 })), path)))
1425 pub fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
1426 if self.token.kind == TokenKind::Semi {
1430 IncorrectSemicolon { span: self.prev_token.span, opt_help: None, name: "" };
1432 if !items.is_empty() {
1433 let previous_item = &items[items.len() - 1];
1434 let previous_item_kind_name = match previous_item.kind {
1435 // Say "braced struct" because tuple-structs and
1436 // braceless-empty-struct declarations do take a semicolon.
1437 ItemKind::Struct(..) => Some("braced struct"),
1438 ItemKind::Enum(..) => Some("enum"),
1439 ItemKind::Trait(..) => Some("trait"),
1440 ItemKind::Union(..) => Some("union"),
1443 if let Some(name) = previous_item_kind_name {
1444 err.opt_help = Some(());
1448 self.sess.emit_err(err);
1455 /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
1456 /// closing delimiter.
1457 pub(super) fn unexpected_try_recover(
1460 ) -> PResult<'a, bool /* recovered */> {
1461 let token_str = pprust::token_kind_to_string(t);
1462 let this_token_str = super::token_descr(&self.token);
1463 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1464 // Point at the end of the macro call when reaching end of macro arguments.
1465 (token::Eof, Some(_)) => {
1466 let sp = self.prev_token.span.shrink_to_hi();
1469 // We don't want to point at the following span after DUMMY_SP.
1470 // This happens when the parser finds an empty TokenStream.
1471 _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
1472 // EOF, don't want to point at the following char, but rather the last token.
1473 (token::Eof, None) => (self.prev_token.span, self.token.span),
1474 _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
1477 "expected `{}`, found {}",
1479 match (&self.token.kind, self.subparser_name) {
1480 (token::Eof, Some(origin)) => format!("end of {origin}"),
1481 _ => this_token_str,
1484 let mut err = self.struct_span_err(sp, &msg);
1485 let label_exp = format!("expected `{token_str}`");
1486 match self.recover_closing_delimiter(&[t.clone()], err) {
1489 return Ok(recovered);
1492 let sm = self.sess.source_map();
1493 if !sm.is_multiline(prev_sp.until(sp)) {
1494 // When the spans are in the same line, it means that the only content
1495 // between them is whitespace, point only at the found token.
1496 err.span_label(sp, label_exp);
1498 err.span_label(prev_sp, label_exp);
1499 err.span_label(sp, "unexpected token");
1504 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1505 if self.eat(&token::Semi) {
1508 self.expect(&token::Semi).map(drop) // Error unconditionally
1511 /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
1512 /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
1513 pub(super) fn recover_incorrect_await_syntax(
1517 ) -> PResult<'a, P<Expr>> {
1518 let (hi, expr, is_question) = if self.token == token::Not {
1519 // Handle `await!(<expr>)`.
1520 self.recover_await_macro()?
1522 self.recover_await_prefix(await_sp)?
1524 let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
1525 let kind = match expr.kind {
1526 // Avoid knock-down errors as we don't know whether to interpret this as `foo().await?`
1527 // or `foo()?.await` (the very reason we went with postfix syntax 😅).
1528 ExprKind::Try(_) => ExprKind::Err,
1529 _ => ExprKind::Await(expr),
1531 let expr = self.mk_expr(lo.to(sp), kind);
1532 self.maybe_recover_from_bad_qpath(expr)
1535 fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1536 self.expect(&token::Not)?;
1537 self.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
1538 let expr = self.parse_expr()?;
1539 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
1540 Ok((self.prev_token.span, expr, false))
1543 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
1544 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
1545 let expr = if self.token == token::OpenDelim(Delimiter::Brace) {
1546 // Handle `await { <expr> }`.
1547 // This needs to be handled separately from the next arm to avoid
1548 // interpreting `await { <expr> }?` as `<expr>?.await`.
1549 self.parse_block_expr(None, self.token.span, BlockCheckMode::Default)
1553 .map_err(|mut err| {
1554 err.span_label(await_sp, "while parsing this incorrect await expression");
1557 Ok((expr.span, expr, is_question))
1560 fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
1561 let span = lo.to(hi);
1562 let applicability = match expr.kind {
1563 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
1564 _ => Applicability::MachineApplicable,
1567 self.sess.emit_err(IncorrectAwait {
1569 sugg_span: (span, applicability),
1570 expr: self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr)),
1571 question_mark: if is_question { "?" } else { "" },
1577 /// If encountering `future.await()`, consumes and emits an error.
1578 pub(super) fn recover_from_await_method_call(&mut self) {
1579 if self.token == token::OpenDelim(Delimiter::Parenthesis)
1580 && self.look_ahead(1, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
1583 let lo = self.token.span;
1585 let span = lo.to(self.token.span);
1588 self.sess.emit_err(IncorrectUseOfAwait { span });
1592 pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, P<Expr>> {
1593 let is_try = self.token.is_keyword(kw::Try);
1594 let is_questionmark = self.look_ahead(1, |t| t == &token::Not); //check for !
1595 let is_open = self.look_ahead(2, |t| t == &token::OpenDelim(Delimiter::Parenthesis)); //check for (
1597 if is_try && is_questionmark && is_open {
1598 let lo = self.token.span;
1599 self.bump(); //remove try
1600 self.bump(); //remove !
1601 let try_span = lo.to(self.token.span); //we take the try!( span
1602 self.bump(); //remove (
1603 let is_empty = self.token == token::CloseDelim(Delimiter::Parenthesis); //check if the block is empty
1604 self.consume_block(Delimiter::Parenthesis, ConsumeClosingDelim::No); //eat the block
1605 let hi = self.token.span;
1606 self.bump(); //remove )
1607 let mut err = self.struct_span_err(lo.to(hi), "use of deprecated `try` macro");
1608 err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
1609 let prefix = if is_empty { "" } else { "alternatively, " };
1611 err.multipart_suggestion(
1612 "you can use the `?` operator instead",
1613 vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
1614 Applicability::MachineApplicable,
1617 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);
1619 Ok(self.mk_expr_err(lo.to(hi)))
1621 Err(self.expected_expression_found()) // The user isn't trying to invoke the try! macro
1625 /// Recovers a situation like `for ( $pat in $expr )`
1626 /// and suggest writing `for $pat in $expr` instead.
1628 /// This should be called before parsing the `$block`.
1629 pub(super) fn recover_parens_around_for_head(
1632 begin_paren: Option<Span>,
1634 match (&self.token.kind, begin_paren) {
1635 (token::CloseDelim(Delimiter::Parenthesis), Some(begin_par_sp)) => {
1638 let sm = self.sess.source_map();
1639 let left = begin_par_sp;
1640 let right = self.prev_token.span;
1641 let left_snippet = if let Ok(snip) = sm.span_to_prev_source(left) &&
1642 !snip.ends_with(' ') {
1648 let right_snippet = if let Ok(snip) = sm.span_to_next_source(right) &&
1649 !snip.starts_with(' ') {
1655 self.sess.emit_err(ParenthesesInForHead {
1656 span: vec![left, right],
1657 // With e.g. `for (x) in y)` this would replace `(x) in y)`
1658 // with `x) in y)` which is syntactically invalid.
1659 // However, this is prevented before we get here.
1660 sugg: ParenthesesInForHeadSugg { left, right, left_snippet, right_snippet },
1663 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1664 pat.and_then(|pat| match pat.kind {
1665 PatKind::Paren(pat) => pat,
1673 pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1674 (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1675 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1676 || self.token.is_ident() &&
1677 matches!(node, ast::ExprKind::Path(..) | ast::ExprKind::Field(..)) &&
1678 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
1679 self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Parenthesis))
1680 || self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Brace)) // `foo:bar {`
1681 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar::<baz`
1682 self.look_ahead(2, |t| t == &token::Lt) &&
1683 self.look_ahead(3, |t| t.is_ident())
1684 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
1685 self.look_ahead(2, |t| t.is_ident())
1686 || self.look_ahead(1, |t| t == &token::ModSep)
1687 && (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
1688 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1691 pub(super) fn recover_seq_parse_error(
1695 result: PResult<'a, P<Expr>>,
1701 // Recover from parse error, callers expect the closing delim to be consumed.
1702 self.consume_block(delim, ConsumeClosingDelim::Yes);
1703 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err)
1708 pub(super) fn recover_closing_delimiter(
1710 tokens: &[TokenKind],
1711 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
1712 ) -> PResult<'a, bool> {
1714 // We want to use the last closing delim that would apply.
1715 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1716 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1717 && Some(self.token.span) > unmatched.unclosed_span
1724 // Recover and assume that the detected unclosed delimiter was meant for
1725 // this location. Emit the diagnostic and act as if the delimiter was
1726 // present for the parser's sake.
1728 // Don't attempt to recover from this unclosed delimiter more than once.
1729 let unmatched = self.unclosed_delims.remove(pos);
1730 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1731 if unmatched.found_delim.is_none() {
1732 // We encountered `Eof`, set this fact here to avoid complaining about missing
1733 // `fn main()` when we found place to suggest the closing brace.
1734 *self.sess.reached_eof.borrow_mut() = true;
1737 // We want to suggest the inclusion of the closing delimiter where it makes
1738 // the most sense, which is immediately after the last token:
1743 // | help: `)` may belong here
1745 // unclosed delimiter
1746 if let Some(sp) = unmatched.unclosed_span {
1747 let mut primary_span: Vec<Span> =
1748 err.span.primary_spans().iter().cloned().collect();
1749 primary_span.push(sp);
1750 let mut primary_span: MultiSpan = primary_span.into();
1751 for span_label in err.span.span_labels() {
1752 if let Some(label) = span_label.label {
1753 primary_span.push_span_label(span_label.span, label);
1756 err.set_span(primary_span);
1757 err.span_label(sp, "unclosed delimiter");
1759 // Backticks should be removed to apply suggestions.
1760 let mut delim = delim.to_string();
1761 delim.retain(|c| c != '`');
1762 err.span_suggestion_short(
1763 self.prev_token.span.shrink_to_hi(),
1764 &format!("`{delim}` may belong here"),
1766 Applicability::MaybeIncorrect,
1768 if unmatched.found_delim.is_none() {
1769 // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1770 // errors which would be emitted elsewhere in the parser and let other error
1771 // recovery consume the rest of the file.
1775 self.expected_tokens.clear(); // Reduce the number of errors.
1783 /// Eats tokens until we can be relatively sure we reached the end of the
1784 /// statement. This is something of a best-effort heuristic.
1786 /// We terminate when we find an unmatched `}` (without consuming it).
1787 pub(super) fn recover_stmt(&mut self) {
1788 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1791 /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1792 /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1793 /// approximate -- it can mean we break too early due to macros, but that
1794 /// should only lead to sub-optimal recovery, not inaccurate parsing).
1796 /// If `break_on_block` is `Break`, then we will stop consuming tokens
1797 /// after finding (and consuming) a brace-delimited block.
1798 pub(super) fn recover_stmt_(
1800 break_on_semi: SemiColonMode,
1801 break_on_block: BlockMode,
1803 let mut brace_depth = 0;
1804 let mut bracket_depth = 0;
1805 let mut in_block = false;
1806 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1808 debug!("recover_stmt_ loop {:?}", self.token);
1809 match self.token.kind {
1810 token::OpenDelim(Delimiter::Brace) => {
1813 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1818 token::OpenDelim(Delimiter::Bracket) => {
1822 token::CloseDelim(Delimiter::Brace) => {
1823 if brace_depth == 0 {
1824 debug!("recover_stmt_ return - close delim {:?}", self.token);
1829 if in_block && bracket_depth == 0 && brace_depth == 0 {
1830 debug!("recover_stmt_ return - block end {:?}", self.token);
1834 token::CloseDelim(Delimiter::Bracket) => {
1836 if bracket_depth < 0 {
1842 debug!("recover_stmt_ return - Eof");
1847 if break_on_semi == SemiColonMode::Break
1849 && bracket_depth == 0
1851 debug!("recover_stmt_ return - Semi");
1856 if break_on_semi == SemiColonMode::Comma
1858 && bracket_depth == 0 =>
1860 debug!("recover_stmt_ return - Semi");
1868 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1869 if self.eat_keyword(kw::In) {
1870 // a common typo: `for _ in in bar {}`
1871 self.sess.emit_err(InInTypo {
1872 span: self.prev_token.span,
1873 sugg_span: in_span.until(self.prev_token.span),
1878 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1879 if let token::DocComment(..) = self.token.kind {
1880 self.sess.emit_err(DocCommentOnParamType { span: self.token.span });
1882 } else if self.token == token::Pound
1883 && self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Bracket))
1885 let lo = self.token.span;
1886 // Skip every token until next possible arg.
1887 while self.token != token::CloseDelim(Delimiter::Bracket) {
1890 let sp = lo.to(self.token.span);
1892 self.sess.emit_err(AttributeOnParamType { span: sp });
1896 pub(super) fn parameter_without_type(
1898 err: &mut Diagnostic,
1902 ) -> Option<Ident> {
1903 // If we find a pattern followed by an identifier, it could be an (incorrect)
1904 // C-style parameter declaration.
1905 if self.check_ident()
1906 && self.look_ahead(1, |t| {
1907 *t == token::Comma || *t == token::CloseDelim(Delimiter::Parenthesis)
1910 // `fn foo(String s) {}`
1911 let ident = self.parse_ident().unwrap();
1912 let span = pat.span.with_hi(ident.span.hi());
1914 err.span_suggestion(
1916 "declare the type after the parameter binding",
1917 "<identifier>: <type>",
1918 Applicability::HasPlaceholders,
1921 } else if require_name
1922 && (self.token == token::Comma
1923 || self.token == token::Lt
1924 || self.token == token::CloseDelim(Delimiter::Parenthesis))
1926 let rfc_note = "anonymous parameters are removed in the 2018 edition (see RFC 1685)";
1928 let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
1930 PatKind::Ident(_, ident, _) => (
1933 ": TypeName".to_string(),
1935 pat.span.shrink_to_lo(),
1936 pat.span.shrink_to_hi(),
1937 pat.span.shrink_to_lo(),
1939 // Also catches `fn foo(&a)`.
1940 PatKind::Ref(ref inner_pat, mutab)
1941 if matches!(inner_pat.clone().into_inner().kind, PatKind::Ident(..)) =>
1943 match inner_pat.clone().into_inner().kind {
1944 PatKind::Ident(_, ident, _) => {
1945 let mutab = mutab.prefix_str();
1949 format!("{ident}: &{mutab}TypeName"),
1951 pat.span.shrink_to_lo(),
1953 pat.span.shrink_to_lo(),
1956 _ => unreachable!(),
1960 // Otherwise, try to get a type and emit a suggestion.
1961 if let Some(ty) = pat.to_ty() {
1962 err.span_suggestion_verbose(
1964 "explicitly ignore the parameter name",
1965 format!("_: {}", pprust::ty_to_string(&ty)),
1966 Applicability::MachineApplicable,
1975 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1977 err.span_suggestion(
1979 "if this is a `self` type, give it a parameter name",
1981 Applicability::MaybeIncorrect,
1984 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
1985 // `fn foo(HashMap: TypeName<u32>)`.
1986 if self.token != token::Lt {
1987 err.span_suggestion(
1989 "if this is a parameter name, give it a type",
1991 Applicability::HasPlaceholders,
1994 err.span_suggestion(
1996 "if this is a type, explicitly ignore the parameter name",
1998 Applicability::MachineApplicable,
2002 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
2003 return if self.token == token::Lt { None } else { Some(ident) };
2008 pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
2009 let pat = self.parse_pat_no_top_alt(Some("argument name"))?;
2010 self.expect(&token::Colon)?;
2011 let ty = self.parse_ty()?;
2013 self.sess.emit_err(PatternMethodParamWithoutBody { span: pat.span });
2015 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2017 P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID, tokens: None });
2021 pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
2022 let span = param.pat.span;
2023 param.ty.kind = TyKind::Err;
2024 self.sess.emit_err(SelfParamNotFirst { span });
2028 pub(super) fn consume_block(&mut self, delim: Delimiter, consume_close: ConsumeClosingDelim) {
2029 let mut brace_depth = 0;
2031 if self.eat(&token::OpenDelim(delim)) {
2033 } else if self.check(&token::CloseDelim(delim)) {
2034 if brace_depth == 0 {
2035 if let ConsumeClosingDelim::Yes = consume_close {
2036 // Some of the callers of this method expect to be able to parse the
2037 // closing delimiter themselves, so we leave it alone. Otherwise we advance
2047 } else if self.token == token::Eof {
2055 pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2056 let (span, msg) = match (&self.token.kind, self.subparser_name) {
2057 (&token::Eof, Some(origin)) => {
2058 let sp = self.prev_token.span.shrink_to_hi();
2059 (sp, format!("expected expression, found end of {origin}"))
2063 format!("expected expression, found {}", super::token_descr(&self.token),),
2066 let mut err = self.struct_span_err(span, &msg);
2067 let sp = self.sess.source_map().start_point(self.token.span);
2068 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
2069 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
2071 err.span_label(span, "expected expression");
2077 mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
2078 // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
2079 modifier: &[(token::TokenKind, i64)],
2082 if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
2085 if self.token.kind == token::Eof {
2092 /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
2094 /// This is necessary because at this point we don't know whether we parsed a function with
2095 /// anonymous parameters or a function with names but no types. In order to minimize
2096 /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
2097 /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
2098 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
2099 /// we deduplicate them to not complain about duplicated parameter names.
2100 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
2101 let mut seen_inputs = FxHashSet::default();
2102 for input in fn_inputs.iter_mut() {
2103 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
2104 (&input.pat.kind, &input.ty.kind)
2110 if let Some(ident) = opt_ident {
2111 if seen_inputs.contains(&ident) {
2112 input.pat.kind = PatKind::Wild;
2114 seen_inputs.insert(ident);
2119 /// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
2120 /// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
2121 /// like the user has forgotten them.
2122 pub fn handle_ambiguous_unbraced_const_arg(
2124 args: &mut Vec<AngleBracketedArg>,
2125 ) -> PResult<'a, bool> {
2126 // If we haven't encountered a closing `>`, then the argument is malformed.
2127 // It's likely that the user has written a const expression without enclosing it
2128 // in braces, so we try to recover here.
2129 let arg = args.pop().unwrap();
2130 // FIXME: for some reason using `unexpected` or `expected_one_of_not_found` has
2131 // adverse side-effects to subsequent errors and seems to advance the parser.
2132 // We are causing this error here exclusively in case that a `const` expression
2133 // could be recovered from the current parser state, even if followed by more
2134 // arguments after a comma.
2135 let mut err = self.struct_span_err(
2137 &format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
2139 err.span_label(self.token.span, "expected one of `,` or `>`");
2140 match self.recover_const_arg(arg.span(), err) {
2142 args.push(AngleBracketedArg::Arg(arg));
2143 if self.eat(&token::Comma) {
2144 return Ok(true); // Continue
2149 // We will emit a more generic error later.
2153 return Ok(false); // Don't continue.
2156 /// Attempt to parse a generic const argument that has not been enclosed in braces.
2157 /// There are a limited number of expressions that are permitted without being encoded
2160 /// - Single-segment paths (i.e. standalone generic const parameters).
2161 /// All other expressions that can be parsed will emit an error suggesting the expression be
2162 /// wrapped in braces.
2163 pub fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
2164 let start = self.token.span;
2165 let expr = self.parse_expr_res(Restrictions::CONST_EXPR, None).map_err(|mut err| {
2167 start.shrink_to_lo(),
2168 "while parsing a const generic argument starting here",
2172 if !self.expr_is_valid_const_arg(&expr) {
2173 self.sess.emit_err(ConstGenericWithoutBraces {
2175 sugg: ConstGenericWithoutBracesSugg {
2176 left: expr.span.shrink_to_lo(),
2177 right: expr.span.shrink_to_hi(),
2184 fn recover_const_param_decl(&mut self, ty_generics: Option<&Generics>) -> Option<GenericArg> {
2185 let snapshot = self.create_snapshot_for_diagnostic();
2186 let param = match self.parse_const_param(AttrVec::new()) {
2190 self.restore_snapshot(snapshot);
2195 let ident = param.ident.to_string();
2196 let sugg = match (ty_generics, self.sess.source_map().span_to_snippet(param.span())) {
2197 (Some(Generics { params, span: impl_generics, .. }), Ok(snippet)) => {
2198 Some(match ¶ms[..] {
2199 [] => UnexpectedConstParamDeclarationSugg::AddParam {
2200 impl_generics: *impl_generics,
2201 incorrect_decl: param.span(),
2205 [.., generic] => UnexpectedConstParamDeclarationSugg::AppendParam {
2206 impl_generics_end: generic.span().shrink_to_hi(),
2207 incorrect_decl: param.span(),
2215 self.sess.emit_err(UnexpectedConstParamDeclaration { span: param.span(), sugg });
2217 let value = self.mk_expr_err(param.span());
2218 Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }))
2221 pub fn recover_const_param_declaration(
2223 ty_generics: Option<&Generics>,
2224 ) -> PResult<'a, Option<GenericArg>> {
2225 // We have to check for a few different cases.
2226 if let Some(arg) = self.recover_const_param_decl(ty_generics) {
2227 return Ok(Some(arg));
2230 // We haven't consumed `const` yet.
2231 let start = self.token.span;
2232 self.bump(); // `const`
2234 // Detect and recover from the old, pre-RFC2000 syntax for const generics.
2235 let mut err = UnexpectedConstInGenericParam { span: start, to_remove: None };
2236 if self.check_const_arg() {
2237 err.to_remove = Some(start.until(self.token.span));
2238 self.sess.emit_err(err);
2239 Ok(Some(GenericArg::Const(self.parse_const_arg()?)))
2241 let after_kw_const = self.token.span;
2242 self.recover_const_arg(after_kw_const, err.into_diagnostic(&self.sess.span_diagnostic))
2247 /// Try to recover from possible generic const argument without `{` and `}`.
2249 /// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
2250 /// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
2251 /// if we think that the resulting expression would be well formed.
2252 pub fn recover_const_arg(
2255 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2256 ) -> PResult<'a, GenericArg> {
2257 let is_op_or_dot = AssocOp::from_token(&self.token)
2259 if let AssocOp::Greater
2261 | AssocOp::ShiftRight
2262 | AssocOp::GreaterEqual
2263 // Don't recover from `foo::<bar = baz>`, because this could be an attempt to
2264 // assign a value to a defaulted generic parameter.
2266 | AssocOp::AssignOp(_) = op
2274 || self.token.kind == TokenKind::Dot;
2275 // This will be true when a trait object type `Foo +` or a path which was a `const fn` with
2276 // type params has been parsed.
2278 matches!(self.prev_token.kind, token::BinOp(token::Plus | token::Shr) | token::Gt);
2279 if !is_op_or_dot && !was_op {
2280 // We perform these checks and early return to avoid taking a snapshot unnecessarily.
2283 let snapshot = self.create_snapshot_for_diagnostic();
2287 match self.parse_expr_res(Restrictions::CONST_EXPR, None) {
2289 // Find a mistake like `MyTrait<Assoc == S::Assoc>`.
2290 if token::EqEq == snapshot.token.kind {
2291 err.span_suggestion(
2292 snapshot.token.span,
2293 "if you meant to use an associated type binding, replace `==` with `=`",
2295 Applicability::MaybeIncorrect,
2297 let value = self.mk_expr_err(start.to(expr.span));
2299 return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
2300 } else if token::Colon == snapshot.token.kind
2301 && expr.span.lo() == snapshot.token.span.hi()
2302 && matches!(expr.kind, ExprKind::Path(..))
2304 // Find a mistake like "foo::var:A".
2305 err.span_suggestion(
2306 snapshot.token.span,
2307 "write a path separator here",
2309 Applicability::MaybeIncorrect,
2312 return Ok(GenericArg::Type(self.mk_ty(start.to(expr.span), TyKind::Err)));
2313 } else if token::Comma == self.token.kind || self.token.kind.should_end_const_arg()
2315 // Avoid the following output by checking that we consumed a full const arg:
2316 // help: expressions must be enclosed in braces to be used as const generic
2319 // LL | let sr: Vec<{ (u32, _, _) = vec![] };
2321 return Ok(self.dummy_const_arg_needs_braces(err, start.to(expr.span)));
2328 self.restore_snapshot(snapshot);
2332 /// Creates a dummy const argument, and reports that the expression must be enclosed in braces
2333 pub fn dummy_const_arg_needs_braces(
2335 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2338 err.multipart_suggestion(
2339 "expressions must be enclosed in braces to be used as const generic \
2341 vec![(span.shrink_to_lo(), "{ ".to_string()), (span.shrink_to_hi(), " }".to_string())],
2342 Applicability::MaybeIncorrect,
2344 let value = self.mk_expr_err(span);
2346 GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })
2349 /// Some special error handling for the "top-level" patterns in a match arm,
2350 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2351 pub(crate) fn maybe_recover_colon_colon_in_pat_typo(
2353 mut first_pat: P<Pat>,
2356 if token::Colon != self.token.kind {
2359 if !matches!(first_pat.kind, PatKind::Ident(_, _, None) | PatKind::Path(..))
2360 || !self.look_ahead(1, |token| token.is_ident() && !token.is_reserved_ident())
2364 // The pattern looks like it might be a path with a `::` -> `:` typo:
2365 // `match foo { bar:baz => {} }`
2366 let span = self.token.span;
2367 // We only emit "unexpected `:`" error here if we can successfully parse the
2368 // whole pattern correctly in that case.
2369 let snapshot = self.create_snapshot_for_diagnostic();
2371 // Create error for "unexpected `:`".
2372 match self.expected_one_of_not_found(&[], &[]) {
2374 self.bump(); // Skip the `:`.
2375 match self.parse_pat_no_top_alt(expected) {
2377 // Carry on as if we had not done anything, callers will emit a
2378 // reasonable error.
2381 self.restore_snapshot(snapshot);
2384 // We've parsed the rest of the pattern.
2385 let new_span = first_pat.span.to(pat.span);
2386 let mut show_sugg = false;
2387 // Try to construct a recovered pattern.
2388 match &mut pat.kind {
2389 PatKind::Struct(qself @ None, path, ..)
2390 | PatKind::TupleStruct(qself @ None, path, _)
2391 | PatKind::Path(qself @ None, path) => match &first_pat.kind {
2392 PatKind::Ident(_, ident, _) => {
2393 path.segments.insert(0, PathSegment::from_ident(*ident));
2394 path.span = new_span;
2398 PatKind::Path(old_qself, old_path) => {
2399 path.segments = old_path
2403 .chain(take(&mut path.segments))
2405 path.span = new_span;
2406 *qself = old_qself.clone();
2412 PatKind::Ident(BindingAnnotation::NONE, ident, None) => {
2413 match &first_pat.kind {
2414 PatKind::Ident(_, old_ident, _) => {
2415 let path = PatKind::Path(
2419 segments: thin_vec![
2420 PathSegment::from_ident(*old_ident),
2421 PathSegment::from_ident(*ident),
2426 first_pat = self.mk_pat(new_span, path);
2429 PatKind::Path(old_qself, old_path) => {
2430 let mut segments = old_path.segments.clone();
2431 segments.push(PathSegment::from_ident(*ident));
2432 let path = PatKind::Path(
2434 Path { span: new_span, segments, tokens: None },
2436 first_pat = self.mk_pat(new_span, path);
2445 err.span_suggestion(
2447 "maybe write a path separator here",
2449 Applicability::MaybeIncorrect,
2452 first_pat = self.mk_pat(new_span, PatKind::Wild);
2459 // Carry on as if we had not done anything. This should be unreachable.
2460 self.restore_snapshot(snapshot);
2466 pub(crate) fn maybe_recover_unexpected_block_label(&mut self) -> bool {
2467 // Check for `'a : {`
2468 if !(self.check_lifetime()
2469 && self.look_ahead(1, |tok| tok.kind == token::Colon)
2470 && self.look_ahead(2, |tok| tok.kind == token::OpenDelim(Delimiter::Brace)))
2474 let label = self.eat_label().expect("just checked if a label exists");
2475 self.bump(); // eat `:`
2476 let span = label.ident.span.to(self.prev_token.span);
2477 let mut err = self.struct_span_err(span, "block label not supported here");
2478 err.span_label(span, "not supported here");
2479 err.tool_only_span_suggestion(
2480 label.ident.span.until(self.token.span),
2481 "remove this block label",
2483 Applicability::MachineApplicable,
2489 /// Some special error handling for the "top-level" patterns in a match arm,
2490 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2491 pub(crate) fn maybe_recover_unexpected_comma(
2494 rt: CommaRecoveryMode,
2495 ) -> PResult<'a, ()> {
2496 if self.token != token::Comma {
2500 // An unexpected comma after a top-level pattern is a clue that the
2501 // user (perhaps more accustomed to some other language) forgot the
2502 // parentheses in what should have been a tuple pattern; return a
2503 // suggestion-enhanced error here rather than choking on the comma later.
2504 let comma_span = self.token.span;
2506 if let Err(err) = self.skip_pat_list() {
2507 // We didn't expect this to work anyway; we just wanted to advance to the
2508 // end of the comma-sequence so we know the span to suggest parenthesizing.
2511 let seq_span = lo.to(self.prev_token.span);
2512 let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
2513 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
2514 err.multipart_suggestion(
2516 "try adding parentheses to match on a tuple{}",
2517 if let CommaRecoveryMode::LikelyTuple = rt { "" } else { "..." },
2520 (seq_span.shrink_to_lo(), "(".to_string()),
2521 (seq_span.shrink_to_hi(), ")".to_string()),
2523 Applicability::MachineApplicable,
2525 if let CommaRecoveryMode::EitherTupleOrPipe = rt {
2526 err.span_suggestion(
2528 "...or a vertical bar to match on multiple alternatives",
2529 seq_snippet.replace(',', " |"),
2530 Applicability::MachineApplicable,
2537 pub(crate) fn maybe_recover_bounds_doubled_colon(&mut self, ty: &Ty) -> PResult<'a, ()> {
2538 let TyKind::Path(qself, path) = &ty.kind else { return Ok(()) };
2539 let qself_position = qself.as_ref().map(|qself| qself.position);
2540 for (i, segments) in path.segments.windows(2).enumerate() {
2541 if qself_position.map(|pos| i < pos).unwrap_or(false) {
2544 if let [a, b] = segments {
2545 let (a_span, b_span) = (a.span(), b.span());
2546 let between_span = a_span.shrink_to_hi().to(b_span.shrink_to_lo());
2547 if self.span_to_snippet(between_span).as_deref() == Ok(":: ") {
2548 return Err(DoubleColonInBound {
2549 span: path.span.shrink_to_hi(),
2550 between: between_span,
2552 .into_diagnostic(&self.sess.span_diagnostic));
2559 /// Parse and throw away a parenthesized comma separated
2560 /// sequence of patterns until `)` is reached.
2561 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
2562 while !self.check(&token::CloseDelim(Delimiter::Parenthesis)) {
2563 self.parse_pat_no_top_alt(None)?;
2564 if !self.eat(&token::Comma) {