1 use super::pat::Expected;
3 BlockMode, CommaRecoveryMode, Parser, PathStyle, Restrictions, SemiColonMode, SeqSep,
4 TokenExpectType, TokenType,
7 AmbiguousPlus, AttributeOnParamType, BadQPathStage2, BadTypePlus, BadTypePlusSub,
8 ComparisonOperatorsCannotBeChained, ComparisonOperatorsCannotBeChainedSugg,
9 ConstGenericWithoutBraces, ConstGenericWithoutBracesSugg, DocCommentOnParamType,
10 DoubleColonInBound, ExpectedIdentifier, ExpectedSemi, ExpectedSemiSugg,
11 GenericParamsWithoutAngleBrackets, GenericParamsWithoutAngleBracketsSugg, InInTypo,
12 IncorrectAwait, IncorrectSemicolon, IncorrectUseOfAwait, ParenthesesInForHead,
13 ParenthesesInForHeadSugg, PatternMethodParamWithoutBody, QuestionMarkInType,
14 QuestionMarkInTypeSugg, SelfParamNotFirst, StructLiteralBodyWithoutPath,
15 StructLiteralBodyWithoutPathSugg, SuggEscapeToUseAsIdentifier, SuggRemoveComma,
16 UnexpectedConstInGenericParam, UnexpectedConstParamDeclaration,
17 UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets, UseEqInstead,
20 use crate::lexer::UnmatchedBrace;
23 use rustc_ast::ptr::P;
24 use rustc_ast::token::{self, Delimiter, Lit, LitKind, TokenKind};
25 use rustc_ast::util::parser::AssocOp;
27 AngleBracketedArg, AngleBracketedArgs, AnonConst, AttrVec, BinOpKind, BindingAnnotation, Block,
28 BlockCheckMode, Expr, ExprKind, GenericArg, Generics, Item, ItemKind, Param, Pat, PatKind,
29 Path, PathSegment, QSelf, Ty, TyKind,
31 use rustc_ast_pretty::pprust;
32 use rustc_data_structures::fx::FxHashSet;
34 fluent, Applicability, DiagnosticBuilder, DiagnosticMessage, FatalError, Handler, MultiSpan,
37 use rustc_errors::{pluralize, Diagnostic, ErrorGuaranteed, IntoDiagnostic};
38 use rustc_session::errors::ExprParenthesesNeeded;
39 use rustc_span::source_map::Spanned;
40 use rustc_span::symbol::{kw, sym, Ident};
41 use rustc_span::{Span, SpanSnippetError, DUMMY_SP};
43 use std::ops::{Deref, DerefMut};
44 use thin_vec::{thin_vec, ThinVec};
46 /// Creates a placeholder argument.
47 pub(super) fn dummy_arg(ident: Ident) -> Param {
49 id: ast::DUMMY_NODE_ID,
50 kind: PatKind::Ident(BindingAnnotation::NONE, ident, None),
54 let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID, tokens: None };
56 attrs: AttrVec::default(),
57 id: ast::DUMMY_NODE_ID,
61 is_placeholder: false,
65 pub(super) trait RecoverQPath: Sized + 'static {
66 const PATH_STYLE: PathStyle = PathStyle::Expr;
67 fn to_ty(&self) -> Option<P<Ty>>;
68 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self;
71 impl RecoverQPath for Ty {
72 const PATH_STYLE: PathStyle = PathStyle::Type;
73 fn to_ty(&self) -> Option<P<Ty>> {
76 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
79 kind: TyKind::Path(qself, path),
80 id: ast::DUMMY_NODE_ID,
86 impl RecoverQPath for Pat {
87 fn to_ty(&self) -> Option<P<Ty>> {
90 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
93 kind: PatKind::Path(qself, path),
94 id: ast::DUMMY_NODE_ID,
100 impl RecoverQPath for Expr {
101 fn to_ty(&self) -> Option<P<Ty>> {
104 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
107 kind: ExprKind::Path(qself, path),
108 attrs: AttrVec::new(),
109 id: ast::DUMMY_NODE_ID,
115 /// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
116 pub(crate) enum ConsumeClosingDelim {
121 #[derive(Clone, Copy)]
122 pub enum AttemptLocalParseRecovery {
127 impl AttemptLocalParseRecovery {
128 pub fn yes(&self) -> bool {
130 AttemptLocalParseRecovery::Yes => true,
131 AttemptLocalParseRecovery::No => false,
135 pub fn no(&self) -> bool {
137 AttemptLocalParseRecovery::Yes => false,
138 AttemptLocalParseRecovery::No => true,
143 /// Information for emitting suggestions and recovering from
144 /// C-style `i++`, `--i`, etc.
145 #[derive(Debug, Copy, Clone)]
146 struct IncDecRecovery {
147 /// Is this increment/decrement its own statement?
148 standalone: IsStandalone,
149 /// Is this an increment or decrement?
151 /// Is this pre- or postfix?
155 /// Is an increment or decrement expression its own statement?
156 #[derive(Debug, Copy, Clone)]
158 /// It's standalone, i.e., its own statement.
160 /// It's a subexpression, i.e., *not* standalone.
164 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
167 // FIXME: `i--` recovery isn't implemented yet
172 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
179 fn chr(&self) -> char {
186 fn name(&self) -> &'static str {
188 Self::Inc => "increment",
189 Self::Dec => "decrement",
194 impl std::fmt::Display for UnaryFixity {
195 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197 Self::Pre => write!(f, "prefix"),
198 Self::Post => write!(f, "postfix"),
205 patches: Vec<(Span, String)>,
206 applicability: Applicability,
210 fn emit(self, err: &mut Diagnostic) {
211 err.multipart_suggestion(&self.msg, self.patches, self.applicability);
214 fn emit_verbose(self, err: &mut Diagnostic) {
215 err.multipart_suggestion_verbose(&self.msg, self.patches, self.applicability);
219 /// SnapshotParser is used to create a snapshot of the parser
220 /// without causing duplicate errors being emitted when the `Parser`
222 pub struct SnapshotParser<'a> {
224 unclosed_delims: Vec<UnmatchedBrace>,
227 impl<'a> Deref for SnapshotParser<'a> {
228 type Target = Parser<'a>;
230 fn deref(&self) -> &Self::Target {
235 impl<'a> DerefMut for SnapshotParser<'a> {
236 fn deref_mut(&mut self) -> &mut Self::Target {
241 impl<'a> Parser<'a> {
242 #[rustc_lint_diagnostics]
243 pub fn struct_span_err<S: Into<MultiSpan>>(
246 m: impl Into<DiagnosticMessage>,
247 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
248 self.sess.span_diagnostic.struct_span_err(sp, m)
251 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: impl Into<DiagnosticMessage>) -> ! {
252 self.sess.span_diagnostic.span_bug(sp, m)
255 pub(super) fn diagnostic(&self) -> &'a Handler {
256 &self.sess.span_diagnostic
259 /// Replace `self` with `snapshot.parser` and extend `unclosed_delims` with `snapshot.unclosed_delims`.
260 /// This is to avoid losing unclosed delims errors `create_snapshot_for_diagnostic` clears.
261 pub(super) fn restore_snapshot(&mut self, snapshot: SnapshotParser<'a>) {
262 *self = snapshot.parser;
263 self.unclosed_delims.extend(snapshot.unclosed_delims);
266 pub fn unclosed_delims(&self) -> &[UnmatchedBrace] {
267 &self.unclosed_delims
270 /// Create a snapshot of the `Parser`.
271 pub fn create_snapshot_for_diagnostic(&self) -> SnapshotParser<'a> {
272 let mut snapshot = self.clone();
273 let unclosed_delims = self.unclosed_delims.clone();
274 // Clear `unclosed_delims` in snapshot to avoid
275 // duplicate errors being emitted when the `Parser`
276 // is dropped (which may or may not happen, depending
277 // if the parsing the snapshot is created for is successful)
278 snapshot.unclosed_delims.clear();
279 SnapshotParser { parser: snapshot, unclosed_delims }
282 pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
283 self.sess.source_map().span_to_snippet(span)
286 pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
287 let valid_follow = &[
293 TokenKind::OpenDelim(Delimiter::Brace),
294 TokenKind::OpenDelim(Delimiter::Parenthesis),
295 TokenKind::CloseDelim(Delimiter::Brace),
296 TokenKind::CloseDelim(Delimiter::Parenthesis),
298 let suggest_raw = match self.token.ident() {
300 if ident.is_raw_guess()
301 && self.look_ahead(1, |t| valid_follow.contains(&t.kind)) =>
303 Some(SuggEscapeToUseAsIdentifier {
304 span: ident.span.shrink_to_lo(),
305 // `Symbol::to_string()` is different from `Symbol::into_diagnostic_arg()`,
306 // which uses `Symbol::to_ident_string()` and "helpfully" adds an implicit `r#`
307 ident_name: ident.name.to_string(),
313 let suggest_remove_comma =
314 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
315 Some(SuggRemoveComma { span: self.token.span })
320 let err = ExpectedIdentifier {
321 span: self.token.span,
322 token: self.token.clone(),
324 suggest_remove_comma,
326 err.into_diagnostic(&self.sess.span_diagnostic)
329 pub(super) fn expected_one_of_not_found(
331 edible: &[TokenKind],
332 inedible: &[TokenKind],
333 ) -> PResult<'a, bool /* recovered */> {
334 debug!("expected_one_of_not_found(edible: {:?}, inedible: {:?})", edible, inedible);
335 fn tokens_to_string(tokens: &[TokenType]) -> String {
336 let mut i = tokens.iter();
337 // This might be a sign we need a connect method on `Iterator`.
338 let b = i.next().map_or_else(String::new, |t| t.to_string());
339 i.enumerate().fold(b, |mut b, (i, a)| {
340 if tokens.len() > 2 && i == tokens.len() - 2 {
342 } else if tokens.len() == 2 && i == tokens.len() - 2 {
347 b.push_str(&a.to_string());
352 let mut expected = edible
354 .map(|x| TokenType::Token(x.clone()))
355 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
356 .chain(self.expected_tokens.iter().cloned())
357 .filter_map(|token| {
358 // filter out suggestions which suggest the same token which was found and deemed incorrect
359 fn is_ident_eq_keyword(found: &TokenKind, expected: &TokenType) -> bool {
360 if let TokenKind::Ident(current_sym, _) = found {
361 if let TokenType::Keyword(suggested_sym) = expected {
362 return current_sym == suggested_sym;
367 if token != parser::TokenType::Token(self.token.kind.clone()) {
368 let eq = is_ident_eq_keyword(&self.token.kind, &token);
369 // if the suggestion is a keyword and the found token is an ident,
370 // the content of which are equal to the suggestion's content,
371 // we can remove that suggestion (see the return None statement below)
373 // if this isn't the case however, and the suggestion is a token the
374 // content of which is the same as the found token's, we remove it as well
376 if let TokenType::Token(kind) = &token {
377 if kind == &self.token.kind {
386 .collect::<Vec<_>>();
387 expected.sort_by_cached_key(|x| x.to_string());
390 let sm = self.sess.source_map();
392 // Special-case "expected `;`" errors
393 if expected.contains(&TokenType::Token(token::Semi)) {
394 if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
395 // Likely inside a macro, can't provide meaningful suggestions.
396 } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
397 // The current token is in the same line as the prior token, not recoverable.
398 } else if [token::Comma, token::Colon].contains(&self.token.kind)
399 && self.prev_token.kind == token::CloseDelim(Delimiter::Parenthesis)
401 // Likely typo: The current token is on a new line and is expected to be
402 // `.`, `;`, `?`, or an operator after a close delimiter token.
404 // let a = std::process::Command::new("echo")
408 // https://github.com/rust-lang/rust/issues/72253
409 } else if self.look_ahead(1, |t| {
410 t == &token::CloseDelim(Delimiter::Brace)
411 || t.can_begin_expr() && t.kind != token::Colon
412 }) && [token::Comma, token::Colon].contains(&self.token.kind)
414 // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is
415 // either `,` or `:`, and the next token could either start a new statement or is a
416 // block close. For example:
420 self.sess.emit_err(ExpectedSemi {
421 span: self.token.span,
422 token: self.token.clone(),
423 unexpected_token_label: None,
424 sugg: ExpectedSemiSugg::ChangeToSemi(self.token.span),
428 } else if self.look_ahead(0, |t| {
429 t == &token::CloseDelim(Delimiter::Brace)
430 || ((t.can_begin_expr() || t.can_begin_item())
432 && t != &token::Pound)
433 // Avoid triggering with too many trailing `#` in raw string.
435 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
436 ) && t == &token::Pound)
437 }) && !expected.contains(&TokenType::Token(token::Comma))
439 // Missing semicolon typo. This is triggered if the next token could either start a
440 // new statement or is a block close. For example:
444 let span = self.prev_token.span.shrink_to_hi();
445 self.sess.emit_err(ExpectedSemi {
447 token: self.token.clone(),
448 unexpected_token_label: Some(self.token.span),
449 sugg: ExpectedSemiSugg::AddSemi(span),
455 if self.token.kind == TokenKind::EqEq
456 && self.prev_token.is_ident()
457 && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Eq)))
459 // Likely typo: `=` → `==` in let expr or enum item
460 return Err(self.sess.create_err(UseEqInstead { span: self.token.span }));
463 let expect = tokens_to_string(&expected);
464 let actual = super::token_descr(&self.token);
465 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
466 let short_expect = if expected.len() > 6 {
467 format!("{} possible tokens", expected.len())
472 format!("expected one of {expect}, found {actual}"),
473 (self.prev_token.span.shrink_to_hi(), format!("expected one of {short_expect}")),
475 } else if expected.is_empty() {
477 format!("unexpected token: {actual}"),
478 (self.prev_token.span, "unexpected token after this".to_string()),
482 format!("expected {expect}, found {actual}"),
483 (self.prev_token.span.shrink_to_hi(), format!("expected {expect}")),
486 self.last_unexpected_token_span = Some(self.token.span);
487 // FIXME: translation requires list formatting (for `expect`)
488 let mut err = self.struct_span_err(self.token.span, &msg_exp);
490 if let TokenKind::Ident(symbol, _) = &self.prev_token.kind {
491 if ["def", "fun", "func", "function"].contains(&symbol.as_str()) {
492 err.span_suggestion_short(
493 self.prev_token.span,
494 &format!("write `fn` instead of `{symbol}` to declare a function"),
496 Applicability::MachineApplicable,
501 // `pub` may be used for an item or `pub(crate)`
502 if self.prev_token.is_ident_named(sym::public)
503 && (self.token.can_begin_item()
504 || self.token.kind == TokenKind::OpenDelim(Delimiter::Parenthesis))
506 err.span_suggestion_short(
507 self.prev_token.span,
508 "write `pub` instead of `public` to make the item public",
510 Applicability::MachineApplicable,
514 // Add suggestion for a missing closing angle bracket if '>' is included in expected_tokens
515 // there are unclosed angle brackets
516 if self.unmatched_angle_bracket_count > 0
517 && self.token.kind == TokenKind::Eq
518 && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Gt)))
520 err.span_label(self.prev_token.span, "maybe try to close unmatched angle bracket");
523 let sp = if self.token == token::Eof {
524 // This is EOF; don't want to point at the following char, but rather the last token.
529 match self.recover_closing_delimiter(
532 .filter_map(|tt| match tt {
533 TokenType::Token(t) => Some(t.clone()),
536 .collect::<Vec<_>>(),
541 return Ok(recovered);
545 if self.check_too_many_raw_str_terminators(&mut err) {
546 if expected.contains(&TokenType::Token(token::Semi)) && self.eat(&token::Semi) {
554 if self.prev_token.span == DUMMY_SP {
555 // Account for macro context where the previous span might not be
556 // available to avoid incorrect output (#54841).
557 err.span_label(self.token.span, label_exp);
558 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
559 // When the spans are in the same line, it means that the only content between
560 // them is whitespace, point at the found token in that case:
562 // X | () => { syntax error };
563 // | ^^^^^ expected one of 8 possible tokens here
565 // instead of having:
567 // X | () => { syntax error };
568 // | -^^^^^ unexpected token
570 // | expected one of 8 possible tokens here
571 err.span_label(self.token.span, label_exp);
573 err.span_label(sp, label_exp);
574 err.span_label(self.token.span, "unexpected token");
576 self.maybe_annotate_with_ascription(&mut err, false);
580 fn check_too_many_raw_str_terminators(&mut self, err: &mut Diagnostic) -> bool {
581 let sm = self.sess.source_map();
582 match (&self.prev_token.kind, &self.token.kind) {
584 TokenKind::Literal(Lit {
585 kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
589 ) if !sm.is_multiline(
590 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
593 let n_hashes: u8 = *n_hashes;
594 err.set_primary_message("too many `#` when terminating raw string");
595 let str_span = self.prev_token.span;
596 let mut span = self.token.span;
598 while self.token.kind == TokenKind::Pound
599 && !sm.is_multiline(span.shrink_to_hi().until(self.token.span.shrink_to_lo()))
601 span = span.with_hi(self.token.span.hi());
608 &format!("remove the extra `#`{}", pluralize!(count)),
610 Applicability::MachineApplicable,
614 &format!("this raw string started with {n_hashes} `#`{}", pluralize!(n_hashes)),
622 pub fn maybe_suggest_struct_literal(
626 ) -> Option<PResult<'a, P<Block>>> {
627 if self.token.is_ident() && self.look_ahead(1, |t| t == &token::Colon) {
628 // We might be having a struct literal where people forgot to include the path:
632 let mut snapshot = self.create_snapshot_for_diagnostic();
634 segments: ThinVec::new(),
635 span: self.prev_token.span.shrink_to_lo(),
638 let struct_expr = snapshot.parse_struct_expr(None, path, false);
639 let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No);
640 return Some(match (struct_expr, block_tail) {
641 (Ok(expr), Err(mut err)) => {
642 // We have encountered the following:
647 // fn foo() -> Foo { Path {
651 self.sess.emit_err(StructLiteralBodyWithoutPath {
653 sugg: StructLiteralBodyWithoutPathSugg {
654 before: expr.span.shrink_to_lo(),
655 after: expr.span.shrink_to_hi(),
658 self.restore_snapshot(snapshot);
659 let mut tail = self.mk_block(
660 vec![self.mk_stmt_err(expr.span)],
662 lo.to(self.prev_token.span),
664 tail.could_be_bare_literal = true;
667 (Err(err), Ok(tail)) => {
668 // We have a block tail that contains a somehow valid type ascription expr.
672 (Err(snapshot_err), Err(err)) => {
673 // We don't know what went wrong, emit the normal error.
674 snapshot_err.cancel();
675 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
678 (Ok(_), Ok(mut tail)) => {
679 tail.could_be_bare_literal = true;
687 pub fn maybe_annotate_with_ascription(
689 err: &mut Diagnostic,
690 maybe_expected_semicolon: bool,
692 if let Some((sp, likely_path)) = self.last_type_ascription.take() {
693 let sm = self.sess.source_map();
694 let next_pos = sm.lookup_char_pos(self.token.span.lo());
695 let op_pos = sm.lookup_char_pos(sp.hi());
697 let allow_unstable = self.sess.unstable_features.is_nightly_build();
702 "maybe write a path separator here",
705 Applicability::MaybeIncorrect
707 Applicability::MachineApplicable
710 self.sess.type_ascription_path_suggestions.borrow_mut().insert(sp);
711 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
714 "try using a semicolon",
716 Applicability::MaybeIncorrect,
718 } else if allow_unstable {
719 err.span_label(sp, "tried to parse a type due to this type ascription");
721 err.span_label(sp, "tried to parse a type due to this");
724 // Give extra information about type ascription only if it's a nightly compiler.
726 "`#![feature(type_ascription)]` lets you annotate an expression with a type: \
730 // Avoid giving too much info when it was likely an unrelated typo.
732 "see issue #23416 <https://github.com/rust-lang/rust/issues/23416> \
733 for more information",
740 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
741 /// passes through any errors encountered. Used for error recovery.
742 pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
744 self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
745 Ok(p.parse_token_tree())
752 /// This function checks if there are trailing angle brackets and produces
753 /// a diagnostic to suggest removing them.
755 /// ```ignore (diagnostic)
756 /// let _ = [1, 2, 3].into_iter().collect::<Vec<usize>>>>();
757 /// ^^ help: remove extra angle brackets
760 /// If `true` is returned, then trailing brackets were recovered, tokens were consumed
761 /// up until one of the tokens in 'end' was encountered, and an error was emitted.
762 pub(super) fn check_trailing_angle_brackets(
764 segment: &PathSegment,
767 if !self.may_recover() {
771 // This function is intended to be invoked after parsing a path segment where there are two
774 // 1. A specific token is expected after the path segment.
775 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
776 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
777 // 2. No specific token is expected after the path segment.
778 // eg. `x.foo` (field access)
780 // This function is called after parsing `.foo` and before parsing the token `end` (if
781 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
784 // We only care about trailing angle brackets if we previously parsed angle bracket
785 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
786 // removed in this case:
788 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
790 // This case is particularly tricky as we won't notice it just looking at the tokens -
791 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
792 // have already been parsed):
794 // `x.foo::<u32>>>(3)`
795 let parsed_angle_bracket_args =
796 segment.args.as_ref().map_or(false, |args| args.is_angle_bracketed());
799 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
800 parsed_angle_bracket_args,
802 if !parsed_angle_bracket_args {
806 // Keep the span at the start so we can highlight the sequence of `>` characters to be
808 let lo = self.token.span;
810 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
811 // (since we might have the field access case and the characters we're eating are
812 // actual operators and not trailing characters - ie `x.foo >> 3`).
813 let mut position = 0;
815 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
816 // many of each (so we can correctly pluralize our error messages) and continue to
818 let mut number_of_shr = 0;
819 let mut number_of_gt = 0;
820 while self.look_ahead(position, |t| {
821 trace!("check_trailing_angle_brackets: t={:?}", t);
822 if *t == token::BinOp(token::BinOpToken::Shr) {
825 } else if *t == token::Gt {
835 // If we didn't find any trailing `>` characters, then we have nothing to error about.
837 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
838 number_of_gt, number_of_shr,
840 if number_of_gt < 1 && number_of_shr < 1 {
844 // Finally, double check that we have our end token as otherwise this is the
846 if self.look_ahead(position, |t| {
847 trace!("check_trailing_angle_brackets: t={:?}", t);
848 end.contains(&&t.kind)
850 // Eat from where we started until the end token so that parsing can continue
851 // as if we didn't have those extra angle brackets.
852 self.eat_to_tokens(end);
853 let span = lo.until(self.token.span);
855 let num_extra_brackets = number_of_gt + number_of_shr * 2;
856 self.sess.emit_err(UnmatchedAngleBrackets { span, num_extra_brackets });
862 /// Check if a method call with an intended turbofish has been written without surrounding
864 pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
865 if !self.may_recover() {
869 if token::ModSep == self.token.kind && segment.args.is_none() {
870 let snapshot = self.create_snapshot_for_diagnostic();
872 let lo = self.token.span;
873 match self.parse_angle_args(None) {
875 let span = lo.to(self.prev_token.span);
876 // Detect trailing `>` like in `x.collect::Vec<_>>()`.
877 let mut trailing_span = self.prev_token.span.shrink_to_hi();
878 while self.token.kind == token::BinOp(token::Shr)
879 || self.token.kind == token::Gt
881 trailing_span = trailing_span.to(self.token.span);
884 if self.token.kind == token::OpenDelim(Delimiter::Parenthesis) {
885 // Recover from bad turbofish: `foo.collect::Vec<_>()`.
886 let args = AngleBracketedArgs { args, span }.into();
889 self.sess.emit_err(GenericParamsWithoutAngleBrackets {
891 sugg: GenericParamsWithoutAngleBracketsSugg {
892 left: span.shrink_to_lo(),
893 right: trailing_span,
897 // This doesn't look like an invalid turbofish, can't recover parse state.
898 self.restore_snapshot(snapshot);
902 // We couldn't parse generic parameters, unlikely to be a turbofish. Rely on
903 // generic parse error instead.
905 self.restore_snapshot(snapshot);
911 /// When writing a turbofish with multiple type parameters missing the leading `::`, we will
912 /// encounter a parse error when encountering the first `,`.
913 pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
915 mut e: DiagnosticBuilder<'a, ErrorGuaranteed>,
917 ) -> PResult<'a, ()> {
918 if let ExprKind::Binary(binop, _, _) = &expr.kind
919 && let ast::BinOpKind::Lt = binop.node
920 && self.eat(&token::Comma)
922 let x = self.parse_seq_to_before_end(
924 SeqSep::trailing_allowed(token::Comma),
925 |p| p.parse_generic_arg(None),
928 Ok((_, _, false)) => {
929 if self.eat(&token::Gt) {
930 e.span_suggestion_verbose(
931 binop.span.shrink_to_lo(),
932 fluent::parse_sugg_turbofish_syntax,
934 Applicability::MaybeIncorrect,
937 match self.parse_expr() {
940 self.mk_expr_err(expr.span.to(self.prev_token.span));
944 *expr = self.mk_expr_err(expr.span);
959 /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
960 /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
961 /// parenthesising the leftmost comparison.
962 fn attempt_chained_comparison_suggestion(
964 err: &mut ComparisonOperatorsCannotBeChained,
966 outer_op: &Spanned<AssocOp>,
967 ) -> bool /* advanced the cursor */ {
968 if let ExprKind::Binary(op, l1, r1) = &inner_op.kind {
969 if let ExprKind::Field(_, ident) = l1.kind
970 && ident.as_str().parse::<i32>().is_err()
971 && !matches!(r1.kind, ExprKind::Lit(_))
973 // The parser has encountered `foo.bar<baz`, the likelihood of the turbofish
974 // suggestion being the only one to apply is high.
977 return match (op.node, &outer_op.node) {
979 (BinOpKind::Eq, AssocOp::Equal) |
980 // `x < y < z` and friends.
981 (BinOpKind::Lt, AssocOp::Less | AssocOp::LessEqual) |
982 (BinOpKind::Le, AssocOp::LessEqual | AssocOp::Less) |
983 // `x > y > z` and friends.
984 (BinOpKind::Gt, AssocOp::Greater | AssocOp::GreaterEqual) |
985 (BinOpKind::Ge, AssocOp::GreaterEqual | AssocOp::Greater) => {
986 let expr_to_str = |e: &Expr| {
987 self.span_to_snippet(e.span)
988 .unwrap_or_else(|_| pprust::expr_to_string(&e))
990 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::SplitComparison {
991 span: inner_op.span.shrink_to_hi(),
992 middle_term: expr_to_str(&r1),
994 false // Keep the current parse behavior, where the AST is `(x < y) < z`.
997 (BinOpKind::Eq, AssocOp::Less | AssocOp::LessEqual | AssocOp::Greater | AssocOp::GreaterEqual) => {
998 // Consume `z`/outer-op-rhs.
999 let snapshot = self.create_snapshot_for_diagnostic();
1000 match self.parse_expr() {
1002 // We are sure that outer-op-rhs could be consumed, the suggestion is
1004 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1005 left: r1.span.shrink_to_lo(),
1006 right: r2.span.shrink_to_hi(),
1012 self.restore_snapshot(snapshot);
1018 (BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge, AssocOp::Equal) => {
1019 let snapshot = self.create_snapshot_for_diagnostic();
1020 // At this point it is always valid to enclose the lhs in parentheses, no
1021 // further checks are necessary.
1022 match self.parse_expr() {
1024 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1025 left: l1.span.shrink_to_lo(),
1026 right: r1.span.shrink_to_hi(),
1032 self.restore_snapshot(snapshot);
1043 /// Produces an error if comparison operators are chained (RFC #558).
1044 /// We only need to check the LHS, not the RHS, because all comparison ops have same
1045 /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
1047 /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
1048 /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
1051 /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
1052 /// associative we can infer that we have:
1061 pub(super) fn check_no_chained_comparison(
1064 outer_op: &Spanned<AssocOp>,
1065 ) -> PResult<'a, Option<P<Expr>>> {
1067 outer_op.node.is_comparison(),
1068 "check_no_chained_comparison: {:?} is not comparison",
1072 let mk_err_expr = |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err)));
1074 match &inner_op.kind {
1075 ExprKind::Binary(op, l1, r1) if op.node.is_comparison() => {
1076 let mut err = ComparisonOperatorsCannotBeChained {
1077 span: vec![op.span, self.prev_token.span],
1078 suggest_turbofish: None,
1079 help_turbofish: None,
1080 chaining_sugg: None,
1083 // Include `<` to provide this recommendation even in a case like
1084 // `Foo<Bar<Baz<Qux, ()>>>`
1085 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Less
1086 || outer_op.node == AssocOp::Greater
1088 if outer_op.node == AssocOp::Less {
1089 let snapshot = self.create_snapshot_for_diagnostic();
1091 // So far we have parsed `foo<bar<`, consume the rest of the type args.
1093 [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
1094 self.consume_tts(1, &modifiers);
1096 if !&[token::OpenDelim(Delimiter::Parenthesis), token::ModSep]
1097 .contains(&self.token.kind)
1099 // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
1100 // parser and bail out.
1101 self.restore_snapshot(snapshot);
1104 return if token::ModSep == self.token.kind {
1105 // We have some certainty that this was a bad turbofish at this point.
1107 if let ExprKind::Binary(o, ..) = inner_op.kind && o.node == BinOpKind::Lt {
1108 err.suggest_turbofish = Some(op.span.shrink_to_lo());
1110 err.help_turbofish = Some(());
1113 let snapshot = self.create_snapshot_for_diagnostic();
1114 self.bump(); // `::`
1116 // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
1117 match self.parse_expr() {
1119 // 99% certain that the suggestion is correct, continue parsing.
1120 self.sess.emit_err(err);
1121 // FIXME: actually check that the two expressions in the binop are
1122 // paths and resynthesize new fn call expression instead of using
1123 // `ExprKind::Err` placeholder.
1124 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1128 // Not entirely sure now, but we bubble the error up with the
1130 self.restore_snapshot(snapshot);
1131 Err(err.into_diagnostic(&self.sess.span_diagnostic))
1134 } else if token::OpenDelim(Delimiter::Parenthesis) == self.token.kind {
1135 // We have high certainty that this was a bad turbofish at this point.
1137 if let ExprKind::Binary(o, ..) = inner_op.kind && o.node == BinOpKind::Lt {
1138 err.suggest_turbofish = Some(op.span.shrink_to_lo());
1140 err.help_turbofish = Some(());
1142 // Consume the fn call arguments.
1143 match self.consume_fn_args() {
1144 Err(()) => Err(err.into_diagnostic(&self.sess.span_diagnostic)),
1146 self.sess.emit_err(err);
1147 // FIXME: actually check that the two expressions in the binop are
1148 // paths and resynthesize new fn call expression instead of using
1149 // `ExprKind::Err` placeholder.
1150 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1154 if !matches!(l1.kind, ExprKind::Lit(_))
1155 && !matches!(r1.kind, ExprKind::Lit(_))
1157 // All we know is that this is `foo < bar >` and *nothing* else. Try to
1158 // be helpful, but don't attempt to recover.
1159 err.help_turbofish = Some(());
1162 // If it looks like a genuine attempt to chain operators (as opposed to a
1163 // misformatted turbofish, for instance), suggest a correct form.
1164 if self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op)
1166 self.sess.emit_err(err);
1167 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1169 // These cases cause too many knock-down errors, bail out (#61329).
1170 Err(err.into_diagnostic(&self.sess.span_diagnostic))
1175 self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1176 self.sess.emit_err(err);
1178 return mk_err_expr(self, inner_op.span.to(self.prev_token.span));
1186 fn consume_fn_args(&mut self) -> Result<(), ()> {
1187 let snapshot = self.create_snapshot_for_diagnostic();
1190 // Consume the fn call arguments.
1192 (token::OpenDelim(Delimiter::Parenthesis), 1),
1193 (token::CloseDelim(Delimiter::Parenthesis), -1),
1195 self.consume_tts(1, &modifiers);
1197 if self.token.kind == token::Eof {
1198 // Not entirely sure that what we consumed were fn arguments, rollback.
1199 self.restore_snapshot(snapshot);
1202 // 99% certain that the suggestion is correct, continue parsing.
1207 pub(super) fn maybe_report_ambiguous_plus(&mut self, impl_dyn_multi: bool, ty: &Ty) {
1209 self.sess.emit_err(AmbiguousPlus { sum_ty: pprust::ty_to_string(&ty), span: ty.span });
1213 /// Swift lets users write `Ty?` to mean `Option<Ty>`. Parse the construct and recover from it.
1214 pub(super) fn maybe_recover_from_question_mark(&mut self, ty: P<Ty>) -> P<Ty> {
1215 if self.token == token::Question {
1217 self.sess.emit_err(QuestionMarkInType {
1218 span: self.prev_token.span,
1219 sugg: QuestionMarkInTypeSugg {
1220 left: ty.span.shrink_to_lo(),
1221 right: self.prev_token.span,
1224 self.mk_ty(ty.span.to(self.prev_token.span), TyKind::Err)
1230 pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> {
1231 // Do not add `+` to expected tokens.
1232 if !self.token.is_like_plus() {
1237 let bounds = self.parse_generic_bounds(None)?;
1238 let sum_span = ty.span.to(self.prev_token.span);
1240 let sub = match &ty.kind {
1241 TyKind::Ref(lifetime, mut_ty) => {
1242 let sum_with_parens = pprust::to_string(|s| {
1244 s.print_opt_lifetime(lifetime);
1245 s.print_mutability(mut_ty.mutbl, false);
1247 s.print_type(&mut_ty.ty);
1248 if !bounds.is_empty() {
1250 s.print_type_bounds(&bounds);
1255 BadTypePlusSub::AddParen { sum_with_parens, span: sum_span }
1257 TyKind::Ptr(..) | TyKind::BareFn(..) => BadTypePlusSub::ForgotParen { span: sum_span },
1258 _ => BadTypePlusSub::ExpectPath { span: sum_span },
1261 self.sess.emit_err(BadTypePlus { ty: pprust::ty_to_string(ty), span: sum_span, sub });
1266 pub(super) fn recover_from_prefix_increment(
1268 operand_expr: P<Expr>,
1271 ) -> PResult<'a, P<Expr>> {
1272 let standalone = if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr };
1273 let kind = IncDecRecovery { standalone, op: IncOrDec::Inc, fixity: UnaryFixity::Pre };
1274 self.recover_from_inc_dec(operand_expr, kind, op_span)
1277 pub(super) fn recover_from_postfix_increment(
1279 operand_expr: P<Expr>,
1282 ) -> PResult<'a, P<Expr>> {
1283 let kind = IncDecRecovery {
1284 standalone: if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr },
1286 fixity: UnaryFixity::Post,
1288 self.recover_from_inc_dec(operand_expr, kind, op_span)
1291 fn recover_from_inc_dec(
1294 kind: IncDecRecovery,
1296 ) -> PResult<'a, P<Expr>> {
1297 let mut err = self.struct_span_err(
1299 &format!("Rust has no {} {} operator", kind.fixity, kind.op.name()),
1301 err.span_label(op_span, &format!("not a valid {} operator", kind.fixity));
1303 let help_base_case = |mut err: DiagnosticBuilder<'_, _>, base| {
1304 err.help(&format!("use `{}= 1` instead", kind.op.chr()));
1310 let spans = match kind.fixity {
1311 UnaryFixity::Pre => (op_span, base.span.shrink_to_hi()),
1312 UnaryFixity::Post => (base.span.shrink_to_lo(), op_span),
1315 match kind.standalone {
1316 IsStandalone::Standalone => {
1317 self.inc_dec_standalone_suggest(kind, spans).emit_verbose(&mut err)
1319 IsStandalone::Subexpr => {
1320 let Ok(base_src) = self.span_to_snippet(base.span)
1321 else { return help_base_case(err, base) };
1323 UnaryFixity::Pre => {
1324 self.prefix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1326 UnaryFixity::Post => {
1327 // won't suggest since we can not handle the precedences
1328 // for example: `a + b++` has been parsed (a + b)++ and we can not suggest here
1329 if !matches!(base.kind, ExprKind::Binary(_, _, _)) {
1330 self.postfix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1339 fn prefix_inc_dec_suggest(
1342 kind: IncDecRecovery,
1343 (pre_span, post_span): (Span, Span),
1346 msg: format!("use `{}= 1` instead", kind.op.chr()),
1348 (pre_span, "{ ".to_string()),
1349 (post_span, format!(" {}= 1; {} }}", kind.op.chr(), base_src)),
1351 applicability: Applicability::MachineApplicable,
1355 fn postfix_inc_dec_suggest(
1358 kind: IncDecRecovery,
1359 (pre_span, post_span): (Span, Span),
1361 let tmp_var = if base_src.trim() == "tmp" { "tmp_" } else { "tmp" };
1363 msg: format!("use `{}= 1` instead", kind.op.chr()),
1365 (pre_span, format!("{{ let {tmp_var} = ")),
1366 (post_span, format!("; {} {}= 1; {} }}", base_src, kind.op.chr(), tmp_var)),
1368 applicability: Applicability::HasPlaceholders,
1372 fn inc_dec_standalone_suggest(
1374 kind: IncDecRecovery,
1375 (pre_span, post_span): (Span, Span),
1377 let mut patches = Vec::new();
1379 if !pre_span.is_empty() {
1380 patches.push((pre_span, String::new()));
1383 patches.push((post_span, format!(" {}= 1", kind.op.chr())));
1385 msg: format!("use `{}= 1` instead", kind.op.chr()),
1387 applicability: Applicability::MachineApplicable,
1391 /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
1392 /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
1393 /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
1394 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
1397 ) -> PResult<'a, P<T>> {
1398 if !self.may_recover() {
1402 // Do not add `::` to expected tokens.
1403 if 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: ThinVec::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.sess.emit_err(BadQPathStage2 {
1427 ty: format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
1430 let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
1431 Ok(P(T::recovered(Some(P(QSelf { ty, path_span, position: 0 })), path)))
1434 pub fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
1435 if self.token.kind == TokenKind::Semi {
1439 IncorrectSemicolon { span: self.prev_token.span, opt_help: None, name: "" };
1441 if !items.is_empty() {
1442 let previous_item = &items[items.len() - 1];
1443 let previous_item_kind_name = match previous_item.kind {
1444 // Say "braced struct" because tuple-structs and
1445 // braceless-empty-struct declarations do take a semicolon.
1446 ItemKind::Struct(..) => Some("braced struct"),
1447 ItemKind::Enum(..) => Some("enum"),
1448 ItemKind::Trait(..) => Some("trait"),
1449 ItemKind::Union(..) => Some("union"),
1452 if let Some(name) = previous_item_kind_name {
1453 err.opt_help = Some(());
1457 self.sess.emit_err(err);
1464 /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
1465 /// closing delimiter.
1466 pub(super) fn unexpected_try_recover(
1469 ) -> PResult<'a, bool /* recovered */> {
1470 let token_str = pprust::token_kind_to_string(t);
1471 let this_token_str = super::token_descr(&self.token);
1472 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1473 // Point at the end of the macro call when reaching end of macro arguments.
1474 (token::Eof, Some(_)) => {
1475 let sp = self.prev_token.span.shrink_to_hi();
1478 // We don't want to point at the following span after DUMMY_SP.
1479 // This happens when the parser finds an empty TokenStream.
1480 _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
1481 // EOF, don't want to point at the following char, but rather the last token.
1482 (token::Eof, None) => (self.prev_token.span, self.token.span),
1483 _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
1486 "expected `{}`, found {}",
1488 match (&self.token.kind, self.subparser_name) {
1489 (token::Eof, Some(origin)) => format!("end of {origin}"),
1490 _ => this_token_str,
1493 let mut err = self.struct_span_err(sp, &msg);
1494 let label_exp = format!("expected `{token_str}`");
1495 match self.recover_closing_delimiter(&[t.clone()], err) {
1498 return Ok(recovered);
1501 let sm = self.sess.source_map();
1502 if !sm.is_multiline(prev_sp.until(sp)) {
1503 // When the spans are in the same line, it means that the only content
1504 // between them is whitespace, point only at the found token.
1505 err.span_label(sp, label_exp);
1507 err.span_label(prev_sp, label_exp);
1508 err.span_label(sp, "unexpected token");
1513 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1514 if self.eat(&token::Semi) {
1517 self.expect(&token::Semi).map(drop) // Error unconditionally
1520 /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
1521 /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
1522 pub(super) fn recover_incorrect_await_syntax(
1526 ) -> PResult<'a, P<Expr>> {
1527 let (hi, expr, is_question) = if self.token == token::Not {
1528 // Handle `await!(<expr>)`.
1529 self.recover_await_macro()?
1531 self.recover_await_prefix(await_sp)?
1533 let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
1534 let kind = match expr.kind {
1535 // Avoid knock-down errors as we don't know whether to interpret this as `foo().await?`
1536 // or `foo()?.await` (the very reason we went with postfix syntax 😅).
1537 ExprKind::Try(_) => ExprKind::Err,
1538 _ => ExprKind::Await(expr),
1540 let expr = self.mk_expr(lo.to(sp), kind);
1541 self.maybe_recover_from_bad_qpath(expr)
1544 fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1545 self.expect(&token::Not)?;
1546 self.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
1547 let expr = self.parse_expr()?;
1548 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
1549 Ok((self.prev_token.span, expr, false))
1552 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
1553 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
1554 let expr = if self.token == token::OpenDelim(Delimiter::Brace) {
1555 // Handle `await { <expr> }`.
1556 // This needs to be handled separately from the next arm to avoid
1557 // interpreting `await { <expr> }?` as `<expr>?.await`.
1558 self.parse_block_expr(None, self.token.span, BlockCheckMode::Default)
1562 .map_err(|mut err| {
1563 err.span_label(await_sp, "while parsing this incorrect await expression");
1566 Ok((expr.span, expr, is_question))
1569 fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
1570 let span = lo.to(hi);
1571 let applicability = match expr.kind {
1572 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
1573 _ => Applicability::MachineApplicable,
1576 self.sess.emit_err(IncorrectAwait {
1578 sugg_span: (span, applicability),
1579 expr: self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr)),
1580 question_mark: if is_question { "?" } else { "" },
1586 /// If encountering `future.await()`, consumes and emits an error.
1587 pub(super) fn recover_from_await_method_call(&mut self) {
1588 if self.token == token::OpenDelim(Delimiter::Parenthesis)
1589 && self.look_ahead(1, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
1592 let lo = self.token.span;
1594 let span = lo.to(self.token.span);
1597 self.sess.emit_err(IncorrectUseOfAwait { span });
1601 pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, P<Expr>> {
1602 let is_try = self.token.is_keyword(kw::Try);
1603 let is_questionmark = self.look_ahead(1, |t| t == &token::Not); //check for !
1604 let is_open = self.look_ahead(2, |t| t == &token::OpenDelim(Delimiter::Parenthesis)); //check for (
1606 if is_try && is_questionmark && is_open {
1607 let lo = self.token.span;
1608 self.bump(); //remove try
1609 self.bump(); //remove !
1610 let try_span = lo.to(self.token.span); //we take the try!( span
1611 self.bump(); //remove (
1612 let is_empty = self.token == token::CloseDelim(Delimiter::Parenthesis); //check if the block is empty
1613 self.consume_block(Delimiter::Parenthesis, ConsumeClosingDelim::No); //eat the block
1614 let hi = self.token.span;
1615 self.bump(); //remove )
1616 let mut err = self.struct_span_err(lo.to(hi), "use of deprecated `try` macro");
1617 err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
1618 let prefix = if is_empty { "" } else { "alternatively, " };
1620 err.multipart_suggestion(
1621 "you can use the `?` operator instead",
1622 vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
1623 Applicability::MachineApplicable,
1626 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);
1628 Ok(self.mk_expr_err(lo.to(hi)))
1630 Err(self.expected_expression_found()) // The user isn't trying to invoke the try! macro
1634 /// Recovers a situation like `for ( $pat in $expr )`
1635 /// and suggest writing `for $pat in $expr` instead.
1637 /// This should be called before parsing the `$block`.
1638 pub(super) fn recover_parens_around_for_head(
1641 begin_paren: Option<Span>,
1643 match (&self.token.kind, begin_paren) {
1644 (token::CloseDelim(Delimiter::Parenthesis), Some(begin_par_sp)) => {
1647 let sm = self.sess.source_map();
1648 let left = begin_par_sp;
1649 let right = self.prev_token.span;
1650 let left_snippet = if let Ok(snip) = sm.span_to_prev_source(left) &&
1651 !snip.ends_with(' ') {
1657 let right_snippet = if let Ok(snip) = sm.span_to_next_source(right) &&
1658 !snip.starts_with(' ') {
1664 self.sess.emit_err(ParenthesesInForHead {
1665 span: vec![left, right],
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 sugg: ParenthesesInForHeadSugg { left, right, left_snippet, right_snippet },
1672 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1673 pat.and_then(|pat| match pat.kind {
1674 PatKind::Paren(pat) => pat,
1682 pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1683 (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1684 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1685 || self.token.is_ident() &&
1686 matches!(node, ast::ExprKind::Path(..) | ast::ExprKind::Field(..)) &&
1687 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
1688 self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Parenthesis))
1689 || self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Brace)) // `foo:bar {`
1690 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar::<baz`
1691 self.look_ahead(2, |t| t == &token::Lt) &&
1692 self.look_ahead(3, |t| t.is_ident())
1693 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
1694 self.look_ahead(2, |t| t.is_ident())
1695 || self.look_ahead(1, |t| t == &token::ModSep)
1696 && (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
1697 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1700 pub(super) fn recover_seq_parse_error(
1704 result: PResult<'a, P<Expr>>,
1710 // Recover from parse error, callers expect the closing delim to be consumed.
1711 self.consume_block(delim, ConsumeClosingDelim::Yes);
1712 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err)
1717 pub(super) fn recover_closing_delimiter(
1719 tokens: &[TokenKind],
1720 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
1721 ) -> PResult<'a, bool> {
1723 // We want to use the last closing delim that would apply.
1724 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1725 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1726 && Some(self.token.span) > unmatched.unclosed_span
1733 // Recover and assume that the detected unclosed delimiter was meant for
1734 // this location. Emit the diagnostic and act as if the delimiter was
1735 // present for the parser's sake.
1737 // Don't attempt to recover from this unclosed delimiter more than once.
1738 let unmatched = self.unclosed_delims.remove(pos);
1739 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1740 if unmatched.found_delim.is_none() {
1741 // We encountered `Eof`, set this fact here to avoid complaining about missing
1742 // `fn main()` when we found place to suggest the closing brace.
1743 *self.sess.reached_eof.borrow_mut() = true;
1746 // We want to suggest the inclusion of the closing delimiter where it makes
1747 // the most sense, which is immediately after the last token:
1752 // | help: `)` may belong here
1754 // unclosed delimiter
1755 if let Some(sp) = unmatched.unclosed_span {
1756 let mut primary_span: Vec<Span> =
1757 err.span.primary_spans().iter().cloned().collect();
1758 primary_span.push(sp);
1759 let mut primary_span: MultiSpan = primary_span.into();
1760 for span_label in err.span.span_labels() {
1761 if let Some(label) = span_label.label {
1762 primary_span.push_span_label(span_label.span, label);
1765 err.set_span(primary_span);
1766 err.span_label(sp, "unclosed delimiter");
1768 // Backticks should be removed to apply suggestions.
1769 let mut delim = delim.to_string();
1770 delim.retain(|c| c != '`');
1771 err.span_suggestion_short(
1772 self.prev_token.span.shrink_to_hi(),
1773 &format!("`{delim}` may belong here"),
1775 Applicability::MaybeIncorrect,
1777 if unmatched.found_delim.is_none() {
1778 // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1779 // errors which would be emitted elsewhere in the parser and let other error
1780 // recovery consume the rest of the file.
1784 self.expected_tokens.clear(); // Reduce the number of errors.
1792 /// Eats tokens until we can be relatively sure we reached the end of the
1793 /// statement. This is something of a best-effort heuristic.
1795 /// We terminate when we find an unmatched `}` (without consuming it).
1796 pub(super) fn recover_stmt(&mut self) {
1797 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1800 /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1801 /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1802 /// approximate -- it can mean we break too early due to macros, but that
1803 /// should only lead to sub-optimal recovery, not inaccurate parsing).
1805 /// If `break_on_block` is `Break`, then we will stop consuming tokens
1806 /// after finding (and consuming) a brace-delimited block.
1807 pub(super) fn recover_stmt_(
1809 break_on_semi: SemiColonMode,
1810 break_on_block: BlockMode,
1812 let mut brace_depth = 0;
1813 let mut bracket_depth = 0;
1814 let mut in_block = false;
1815 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1817 debug!("recover_stmt_ loop {:?}", self.token);
1818 match self.token.kind {
1819 token::OpenDelim(Delimiter::Brace) => {
1822 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1827 token::OpenDelim(Delimiter::Bracket) => {
1831 token::CloseDelim(Delimiter::Brace) => {
1832 if brace_depth == 0 {
1833 debug!("recover_stmt_ return - close delim {:?}", self.token);
1838 if in_block && bracket_depth == 0 && brace_depth == 0 {
1839 debug!("recover_stmt_ return - block end {:?}", self.token);
1843 token::CloseDelim(Delimiter::Bracket) => {
1845 if bracket_depth < 0 {
1851 debug!("recover_stmt_ return - Eof");
1856 if break_on_semi == SemiColonMode::Break
1858 && bracket_depth == 0
1860 debug!("recover_stmt_ return - Semi");
1865 if break_on_semi == SemiColonMode::Comma
1867 && bracket_depth == 0 =>
1869 debug!("recover_stmt_ return - Semi");
1877 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1878 if self.eat_keyword(kw::In) {
1879 // a common typo: `for _ in in bar {}`
1880 self.sess.emit_err(InInTypo {
1881 span: self.prev_token.span,
1882 sugg_span: in_span.until(self.prev_token.span),
1887 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1888 if let token::DocComment(..) = self.token.kind {
1889 self.sess.emit_err(DocCommentOnParamType { span: self.token.span });
1891 } else if self.token == token::Pound
1892 && self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Bracket))
1894 let lo = self.token.span;
1895 // Skip every token until next possible arg.
1896 while self.token != token::CloseDelim(Delimiter::Bracket) {
1899 let sp = lo.to(self.token.span);
1901 self.sess.emit_err(AttributeOnParamType { span: sp });
1905 pub(super) fn parameter_without_type(
1907 err: &mut Diagnostic,
1911 ) -> Option<Ident> {
1912 // If we find a pattern followed by an identifier, it could be an (incorrect)
1913 // C-style parameter declaration.
1914 if self.check_ident()
1915 && self.look_ahead(1, |t| {
1916 *t == token::Comma || *t == token::CloseDelim(Delimiter::Parenthesis)
1919 // `fn foo(String s) {}`
1920 let ident = self.parse_ident().unwrap();
1921 let span = pat.span.with_hi(ident.span.hi());
1923 err.span_suggestion(
1925 "declare the type after the parameter binding",
1926 "<identifier>: <type>",
1927 Applicability::HasPlaceholders,
1930 } else if require_name
1931 && (self.token == token::Comma
1932 || self.token == token::Lt
1933 || self.token == token::CloseDelim(Delimiter::Parenthesis))
1935 let rfc_note = "anonymous parameters are removed in the 2018 edition (see RFC 1685)";
1937 let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
1939 PatKind::Ident(_, ident, _) => (
1942 ": TypeName".to_string(),
1944 pat.span.shrink_to_lo(),
1945 pat.span.shrink_to_hi(),
1946 pat.span.shrink_to_lo(),
1948 // Also catches `fn foo(&a)`.
1949 PatKind::Ref(ref inner_pat, mutab)
1950 if matches!(inner_pat.clone().into_inner().kind, PatKind::Ident(..)) =>
1952 match inner_pat.clone().into_inner().kind {
1953 PatKind::Ident(_, ident, _) => {
1954 let mutab = mutab.prefix_str();
1958 format!("{ident}: &{mutab}TypeName"),
1960 pat.span.shrink_to_lo(),
1962 pat.span.shrink_to_lo(),
1965 _ => unreachable!(),
1969 // Otherwise, try to get a type and emit a suggestion.
1970 if let Some(ty) = pat.to_ty() {
1971 err.span_suggestion_verbose(
1973 "explicitly ignore the parameter name",
1974 format!("_: {}", pprust::ty_to_string(&ty)),
1975 Applicability::MachineApplicable,
1984 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1986 err.span_suggestion(
1988 "if this is a `self` type, give it a parameter name",
1990 Applicability::MaybeIncorrect,
1993 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
1994 // `fn foo(HashMap: TypeName<u32>)`.
1995 if self.token != token::Lt {
1996 err.span_suggestion(
1998 "if this is a parameter name, give it a type",
2000 Applicability::HasPlaceholders,
2003 err.span_suggestion(
2005 "if this is a type, explicitly ignore the parameter name",
2007 Applicability::MachineApplicable,
2011 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
2012 return if self.token == token::Lt { None } else { Some(ident) };
2017 pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
2018 let pat = self.parse_pat_no_top_alt(Some("argument name"))?;
2019 self.expect(&token::Colon)?;
2020 let ty = self.parse_ty()?;
2022 self.sess.emit_err(PatternMethodParamWithoutBody { span: pat.span });
2024 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2026 P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID, tokens: None });
2030 pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
2031 let span = param.pat.span;
2032 param.ty.kind = TyKind::Err;
2033 self.sess.emit_err(SelfParamNotFirst { span });
2037 pub(super) fn consume_block(&mut self, delim: Delimiter, consume_close: ConsumeClosingDelim) {
2038 let mut brace_depth = 0;
2040 if self.eat(&token::OpenDelim(delim)) {
2042 } else if self.check(&token::CloseDelim(delim)) {
2043 if brace_depth == 0 {
2044 if let ConsumeClosingDelim::Yes = consume_close {
2045 // Some of the callers of this method expect to be able to parse the
2046 // closing delimiter themselves, so we leave it alone. Otherwise we advance
2056 } else if self.token == token::Eof {
2064 pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2065 let (span, msg) = match (&self.token.kind, self.subparser_name) {
2066 (&token::Eof, Some(origin)) => {
2067 let sp = self.prev_token.span.shrink_to_hi();
2068 (sp, format!("expected expression, found end of {origin}"))
2072 format!("expected expression, found {}", super::token_descr(&self.token),),
2075 let mut err = self.struct_span_err(span, &msg);
2076 let sp = self.sess.source_map().start_point(self.token.span);
2077 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
2078 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
2080 err.span_label(span, "expected expression");
2086 mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
2087 // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
2088 modifier: &[(token::TokenKind, i64)],
2091 if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
2094 if self.token.kind == token::Eof {
2101 /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
2103 /// This is necessary because at this point we don't know whether we parsed a function with
2104 /// anonymous parameters or a function with names but no types. In order to minimize
2105 /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
2106 /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
2107 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
2108 /// we deduplicate them to not complain about duplicated parameter names.
2109 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
2110 let mut seen_inputs = FxHashSet::default();
2111 for input in fn_inputs.iter_mut() {
2112 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
2113 (&input.pat.kind, &input.ty.kind)
2119 if let Some(ident) = opt_ident {
2120 if seen_inputs.contains(&ident) {
2121 input.pat.kind = PatKind::Wild;
2123 seen_inputs.insert(ident);
2128 /// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
2129 /// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
2130 /// like the user has forgotten them.
2131 pub fn handle_ambiguous_unbraced_const_arg(
2133 args: &mut Vec<AngleBracketedArg>,
2134 ) -> PResult<'a, bool> {
2135 // If we haven't encountered a closing `>`, then the argument is malformed.
2136 // It's likely that the user has written a const expression without enclosing it
2137 // in braces, so we try to recover here.
2138 let arg = args.pop().unwrap();
2139 // FIXME: for some reason using `unexpected` or `expected_one_of_not_found` has
2140 // adverse side-effects to subsequent errors and seems to advance the parser.
2141 // We are causing this error here exclusively in case that a `const` expression
2142 // could be recovered from the current parser state, even if followed by more
2143 // arguments after a comma.
2144 let mut err = self.struct_span_err(
2146 &format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
2148 err.span_label(self.token.span, "expected one of `,` or `>`");
2149 match self.recover_const_arg(arg.span(), err) {
2151 args.push(AngleBracketedArg::Arg(arg));
2152 if self.eat(&token::Comma) {
2153 return Ok(true); // Continue
2158 // We will emit a more generic error later.
2162 return Ok(false); // Don't continue.
2165 /// Attempt to parse a generic const argument that has not been enclosed in braces.
2166 /// There are a limited number of expressions that are permitted without being encoded
2169 /// - Single-segment paths (i.e. standalone generic const parameters).
2170 /// All other expressions that can be parsed will emit an error suggesting the expression be
2171 /// wrapped in braces.
2172 pub fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
2173 let start = self.token.span;
2174 let expr = self.parse_expr_res(Restrictions::CONST_EXPR, None).map_err(|mut err| {
2176 start.shrink_to_lo(),
2177 "while parsing a const generic argument starting here",
2181 if !self.expr_is_valid_const_arg(&expr) {
2182 self.sess.emit_err(ConstGenericWithoutBraces {
2184 sugg: ConstGenericWithoutBracesSugg {
2185 left: expr.span.shrink_to_lo(),
2186 right: expr.span.shrink_to_hi(),
2193 fn recover_const_param_decl(&mut self, ty_generics: Option<&Generics>) -> Option<GenericArg> {
2194 let snapshot = self.create_snapshot_for_diagnostic();
2195 let param = match self.parse_const_param(AttrVec::new()) {
2199 self.restore_snapshot(snapshot);
2204 let ident = param.ident.to_string();
2205 let sugg = match (ty_generics, self.sess.source_map().span_to_snippet(param.span())) {
2206 (Some(Generics { params, span: impl_generics, .. }), Ok(snippet)) => {
2207 Some(match ¶ms[..] {
2208 [] => UnexpectedConstParamDeclarationSugg::AddParam {
2209 impl_generics: *impl_generics,
2210 incorrect_decl: param.span(),
2214 [.., generic] => UnexpectedConstParamDeclarationSugg::AppendParam {
2215 impl_generics_end: generic.span().shrink_to_hi(),
2216 incorrect_decl: param.span(),
2224 self.sess.emit_err(UnexpectedConstParamDeclaration { span: param.span(), sugg });
2226 let value = self.mk_expr_err(param.span());
2227 Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }))
2230 pub fn recover_const_param_declaration(
2232 ty_generics: Option<&Generics>,
2233 ) -> PResult<'a, Option<GenericArg>> {
2234 // We have to check for a few different cases.
2235 if let Some(arg) = self.recover_const_param_decl(ty_generics) {
2236 return Ok(Some(arg));
2239 // We haven't consumed `const` yet.
2240 let start = self.token.span;
2241 self.bump(); // `const`
2243 // Detect and recover from the old, pre-RFC2000 syntax for const generics.
2244 let mut err = UnexpectedConstInGenericParam { span: start, to_remove: None };
2245 if self.check_const_arg() {
2246 err.to_remove = Some(start.until(self.token.span));
2247 self.sess.emit_err(err);
2248 Ok(Some(GenericArg::Const(self.parse_const_arg()?)))
2250 let after_kw_const = self.token.span;
2251 self.recover_const_arg(after_kw_const, err.into_diagnostic(&self.sess.span_diagnostic))
2256 /// Try to recover from possible generic const argument without `{` and `}`.
2258 /// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
2259 /// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
2260 /// if we think that the resulting expression would be well formed.
2261 pub fn recover_const_arg(
2264 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2265 ) -> PResult<'a, GenericArg> {
2266 let is_op_or_dot = AssocOp::from_token(&self.token)
2268 if let AssocOp::Greater
2270 | AssocOp::ShiftRight
2271 | AssocOp::GreaterEqual
2272 // Don't recover from `foo::<bar = baz>`, because this could be an attempt to
2273 // assign a value to a defaulted generic parameter.
2275 | AssocOp::AssignOp(_) = op
2283 || self.token.kind == TokenKind::Dot;
2284 // This will be true when a trait object type `Foo +` or a path which was a `const fn` with
2285 // type params has been parsed.
2287 matches!(self.prev_token.kind, token::BinOp(token::Plus | token::Shr) | token::Gt);
2288 if !is_op_or_dot && !was_op {
2289 // We perform these checks and early return to avoid taking a snapshot unnecessarily.
2292 let snapshot = self.create_snapshot_for_diagnostic();
2296 match self.parse_expr_res(Restrictions::CONST_EXPR, None) {
2298 // Find a mistake like `MyTrait<Assoc == S::Assoc>`.
2299 if token::EqEq == snapshot.token.kind {
2300 err.span_suggestion(
2301 snapshot.token.span,
2302 "if you meant to use an associated type binding, replace `==` with `=`",
2304 Applicability::MaybeIncorrect,
2306 let value = self.mk_expr_err(start.to(expr.span));
2308 return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
2309 } else if token::Colon == snapshot.token.kind
2310 && expr.span.lo() == snapshot.token.span.hi()
2311 && matches!(expr.kind, ExprKind::Path(..))
2313 // Find a mistake like "foo::var:A".
2314 err.span_suggestion(
2315 snapshot.token.span,
2316 "write a path separator here",
2318 Applicability::MaybeIncorrect,
2321 return Ok(GenericArg::Type(self.mk_ty(start.to(expr.span), TyKind::Err)));
2322 } else if token::Comma == self.token.kind || self.token.kind.should_end_const_arg()
2324 // Avoid the following output by checking that we consumed a full const arg:
2325 // help: expressions must be enclosed in braces to be used as const generic
2328 // LL | let sr: Vec<{ (u32, _, _) = vec![] };
2330 return Ok(self.dummy_const_arg_needs_braces(err, start.to(expr.span)));
2337 self.restore_snapshot(snapshot);
2341 /// Creates a dummy const argument, and reports that the expression must be enclosed in braces
2342 pub fn dummy_const_arg_needs_braces(
2344 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2347 err.multipart_suggestion(
2348 "expressions must be enclosed in braces to be used as const generic \
2350 vec![(span.shrink_to_lo(), "{ ".to_string()), (span.shrink_to_hi(), " }".to_string())],
2351 Applicability::MaybeIncorrect,
2353 let value = self.mk_expr_err(span);
2355 GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })
2358 /// Some special error handling for the "top-level" patterns in a match arm,
2359 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2360 pub(crate) fn maybe_recover_colon_colon_in_pat_typo(
2362 mut first_pat: P<Pat>,
2365 if token::Colon != self.token.kind {
2368 if !matches!(first_pat.kind, PatKind::Ident(_, _, None) | PatKind::Path(..))
2369 || !self.look_ahead(1, |token| token.is_ident() && !token.is_reserved_ident())
2373 // The pattern looks like it might be a path with a `::` -> `:` typo:
2374 // `match foo { bar:baz => {} }`
2375 let span = self.token.span;
2376 // We only emit "unexpected `:`" error here if we can successfully parse the
2377 // whole pattern correctly in that case.
2378 let snapshot = self.create_snapshot_for_diagnostic();
2380 // Create error for "unexpected `:`".
2381 match self.expected_one_of_not_found(&[], &[]) {
2383 self.bump(); // Skip the `:`.
2384 match self.parse_pat_no_top_alt(expected) {
2386 // Carry on as if we had not done anything, callers will emit a
2387 // reasonable error.
2390 self.restore_snapshot(snapshot);
2393 // We've parsed the rest of the pattern.
2394 let new_span = first_pat.span.to(pat.span);
2395 let mut show_sugg = false;
2396 // Try to construct a recovered pattern.
2397 match &mut pat.kind {
2398 PatKind::Struct(qself @ None, path, ..)
2399 | PatKind::TupleStruct(qself @ None, path, _)
2400 | PatKind::Path(qself @ None, path) => match &first_pat.kind {
2401 PatKind::Ident(_, ident, _) => {
2402 path.segments.insert(0, PathSegment::from_ident(*ident));
2403 path.span = new_span;
2407 PatKind::Path(old_qself, old_path) => {
2408 path.segments = old_path
2412 .chain(take(&mut path.segments))
2414 path.span = new_span;
2415 *qself = old_qself.clone();
2421 PatKind::Ident(BindingAnnotation::NONE, ident, None) => {
2422 match &first_pat.kind {
2423 PatKind::Ident(_, old_ident, _) => {
2424 let path = PatKind::Path(
2428 segments: thin_vec![
2429 PathSegment::from_ident(*old_ident),
2430 PathSegment::from_ident(*ident),
2435 first_pat = self.mk_pat(new_span, path);
2438 PatKind::Path(old_qself, old_path) => {
2439 let mut segments = old_path.segments.clone();
2440 segments.push(PathSegment::from_ident(*ident));
2441 let path = PatKind::Path(
2443 Path { span: new_span, segments, tokens: None },
2445 first_pat = self.mk_pat(new_span, path);
2454 err.span_suggestion(
2456 "maybe write a path separator here",
2458 Applicability::MaybeIncorrect,
2461 first_pat = self.mk_pat(new_span, PatKind::Wild);
2468 // Carry on as if we had not done anything. This should be unreachable.
2469 self.restore_snapshot(snapshot);
2475 pub(crate) fn maybe_recover_unexpected_block_label(&mut self) -> bool {
2476 // Check for `'a : {`
2477 if !(self.check_lifetime()
2478 && self.look_ahead(1, |tok| tok.kind == token::Colon)
2479 && self.look_ahead(2, |tok| tok.kind == token::OpenDelim(Delimiter::Brace)))
2483 let label = self.eat_label().expect("just checked if a label exists");
2484 self.bump(); // eat `:`
2485 let span = label.ident.span.to(self.prev_token.span);
2486 let mut err = self.struct_span_err(span, "block label not supported here");
2487 err.span_label(span, "not supported here");
2488 err.tool_only_span_suggestion(
2489 label.ident.span.until(self.token.span),
2490 "remove this block label",
2492 Applicability::MachineApplicable,
2498 /// Some special error handling for the "top-level" patterns in a match arm,
2499 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2500 pub(crate) fn maybe_recover_unexpected_comma(
2503 rt: CommaRecoveryMode,
2504 ) -> PResult<'a, ()> {
2505 if self.token != token::Comma {
2509 // An unexpected comma after a top-level pattern is a clue that the
2510 // user (perhaps more accustomed to some other language) forgot the
2511 // parentheses in what should have been a tuple pattern; return a
2512 // suggestion-enhanced error here rather than choking on the comma later.
2513 let comma_span = self.token.span;
2515 if let Err(err) = self.skip_pat_list() {
2516 // We didn't expect this to work anyway; we just wanted to advance to the
2517 // end of the comma-sequence so we know the span to suggest parenthesizing.
2520 let seq_span = lo.to(self.prev_token.span);
2521 let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
2522 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
2523 err.multipart_suggestion(
2525 "try adding parentheses to match on a tuple{}",
2526 if let CommaRecoveryMode::LikelyTuple = rt { "" } else { "..." },
2529 (seq_span.shrink_to_lo(), "(".to_string()),
2530 (seq_span.shrink_to_hi(), ")".to_string()),
2532 Applicability::MachineApplicable,
2534 if let CommaRecoveryMode::EitherTupleOrPipe = rt {
2535 err.span_suggestion(
2537 "...or a vertical bar to match on multiple alternatives",
2538 seq_snippet.replace(',', " |"),
2539 Applicability::MachineApplicable,
2546 pub(crate) fn maybe_recover_bounds_doubled_colon(&mut self, ty: &Ty) -> PResult<'a, ()> {
2547 let TyKind::Path(qself, path) = &ty.kind else { return Ok(()) };
2548 let qself_position = qself.as_ref().map(|qself| qself.position);
2549 for (i, segments) in path.segments.windows(2).enumerate() {
2550 if qself_position.map(|pos| i < pos).unwrap_or(false) {
2553 if let [a, b] = segments {
2554 let (a_span, b_span) = (a.span(), b.span());
2555 let between_span = a_span.shrink_to_hi().to(b_span.shrink_to_lo());
2556 if self.span_to_snippet(between_span).as_deref() == Ok(":: ") {
2557 return Err(DoubleColonInBound {
2558 span: path.span.shrink_to_hi(),
2559 between: between_span,
2561 .into_diagnostic(&self.sess.span_diagnostic));
2568 pub fn is_diff_marker(&mut self, long_kind: &TokenKind, short_kind: &TokenKind) -> bool {
2569 (0..3).all(|i| self.look_ahead(i, |tok| tok == long_kind))
2570 && self.look_ahead(3, |tok| tok == short_kind)
2573 fn diff_marker(&mut self, long_kind: &TokenKind, short_kind: &TokenKind) -> Option<Span> {
2574 if self.is_diff_marker(long_kind, short_kind) {
2575 let lo = self.token.span;
2579 return Some(lo.to(self.prev_token.span));
2584 pub fn recover_diff_marker(&mut self) {
2585 let Some(start) = self.diff_marker(&TokenKind::BinOp(token::Shl), &TokenKind::Lt) else {
2588 let mut spans = Vec::with_capacity(3);
2590 let mut middlediff3 = None;
2591 let mut middle = None;
2594 if self.token.kind == TokenKind::Eof {
2597 if let Some(span) = self.diff_marker(&TokenKind::OrOr, &TokenKind::BinOp(token::Or)) {
2598 middlediff3 = Some(span);
2600 if let Some(span) = self.diff_marker(&TokenKind::EqEq, &TokenKind::Eq) {
2601 middle = Some(span);
2603 if let Some(span) = self.diff_marker(&TokenKind::BinOp(token::Shr), &TokenKind::Gt) {
2610 let mut err = self.struct_span_err(spans, "encountered diff marker");
2611 err.span_label(start, "after this is the code before the merge");
2612 if let Some(middle) = middlediff3 {
2613 err.span_label(middle, "");
2615 if let Some(middle) = middle {
2616 err.span_label(middle, "");
2618 if let Some(end) = end {
2619 err.span_label(end, "above this are the incoming code changes");
2622 "if you're having merge conflicts after pulling new code, the top section is the code \
2623 you already had and the bottom section is the remote code",
2626 "if you're in the middle of a rebase, the top section is the code being rebased onto \
2627 and the bottom section is the code coming from the current commit being rebased",
2630 "for an explanation on these markers from the `git` documentation, visit \
2631 <https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging#_checking_out_conflicts>",
2637 /// Parse and throw away a parenthesized comma separated
2638 /// sequence of patterns until `)` is reached.
2639 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
2640 while !self.check(&token::CloseDelim(Delimiter::Parenthesis)) {
2641 self.parse_pat_no_top_alt(None)?;
2642 if !self.eat(&token::Comma) {