1 use super::pat::Expected;
2 use super::ty::{AllowPlus, RecoverQuestionMark};
4 BlockMode, CommaRecoveryMode, Parser, PathStyle, RecoverColon, RecoverComma, Restrictions,
5 SemiColonMode, SeqSep, TokenExpectType, TokenType,
10 use rustc_ast::token::{self, Lit, LitKind, TokenKind};
11 use rustc_ast::util::parser::AssocOp;
13 AngleBracketedArg, AngleBracketedArgs, AnonConst, AttrVec, BinOpKind, BindingMode, Block,
14 BlockCheckMode, Expr, ExprKind, GenericArg, Generics, Item, ItemKind, Mutability, Param, Pat,
15 PatKind, Path, PathSegment, QSelf, Ty, TyKind,
17 use rustc_ast_pretty::pprust;
18 use rustc_data_structures::fx::FxHashSet;
19 use rustc_errors::{pluralize, struct_span_err, Diagnostic, ErrorGuaranteed};
20 use rustc_errors::{Applicability, DiagnosticBuilder, Handler, PResult};
21 use rustc_span::source_map::Spanned;
22 use rustc_span::symbol::{kw, Ident};
23 use rustc_span::{MultiSpan, Span, SpanSnippetError, DUMMY_SP};
27 use tracing::{debug, trace};
29 const TURBOFISH_SUGGESTION_STR: &str =
30 "use `::<...>` instead of `<...>` to specify lifetime, type, or const arguments";
32 /// Creates a placeholder argument.
33 pub(super) fn dummy_arg(ident: Ident) -> Param {
35 id: ast::DUMMY_NODE_ID,
36 kind: PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None),
40 let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID, tokens: None };
42 attrs: AttrVec::default(),
43 id: ast::DUMMY_NODE_ID,
47 is_placeholder: false,
58 sp: impl Into<MultiSpan>,
60 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
62 Error::UselessDocComment => {
63 let mut err = struct_span_err!(
67 "found a documentation comment that doesn't document anything",
70 "doc comments must come before what they document, maybe a comment was \
79 pub(super) trait RecoverQPath: Sized + 'static {
80 const PATH_STYLE: PathStyle = PathStyle::Expr;
81 fn to_ty(&self) -> Option<P<Ty>>;
82 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
85 impl RecoverQPath for Ty {
86 const PATH_STYLE: PathStyle = PathStyle::Type;
87 fn to_ty(&self) -> Option<P<Ty>> {
90 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
93 kind: TyKind::Path(qself, path),
94 id: ast::DUMMY_NODE_ID,
100 impl RecoverQPath for Pat {
101 fn to_ty(&self) -> Option<P<Ty>> {
104 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
107 kind: PatKind::Path(qself, path),
108 id: ast::DUMMY_NODE_ID,
114 impl RecoverQPath for Expr {
115 fn to_ty(&self) -> Option<P<Ty>> {
118 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
121 kind: ExprKind::Path(qself, path),
122 attrs: AttrVec::new(),
123 id: ast::DUMMY_NODE_ID,
129 /// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
130 crate enum ConsumeClosingDelim {
135 #[derive(Clone, Copy)]
136 pub enum AttemptLocalParseRecovery {
141 impl AttemptLocalParseRecovery {
142 pub fn yes(&self) -> bool {
144 AttemptLocalParseRecovery::Yes => true,
145 AttemptLocalParseRecovery::No => false,
149 pub fn no(&self) -> bool {
151 AttemptLocalParseRecovery::Yes => false,
152 AttemptLocalParseRecovery::No => true,
157 impl<'a> Parser<'a> {
158 pub(super) fn span_err<S: Into<MultiSpan>>(
162 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
163 err.span_err(sp, self.diagnostic())
166 pub fn struct_span_err<S: Into<MultiSpan>>(
170 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
171 self.sess.span_diagnostic.struct_span_err(sp, m)
174 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
175 self.sess.span_diagnostic.span_bug(sp, m)
178 pub(super) fn diagnostic(&self) -> &'a Handler {
179 &self.sess.span_diagnostic
182 pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
183 self.sess.source_map().span_to_snippet(span)
186 pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
187 let mut err = self.struct_span_err(
189 &format!("expected identifier, found {}", super::token_descr(&self.token)),
191 let valid_follow = &[
197 TokenKind::OpenDelim(token::DelimToken::Brace),
198 TokenKind::OpenDelim(token::DelimToken::Paren),
199 TokenKind::CloseDelim(token::DelimToken::Brace),
200 TokenKind::CloseDelim(token::DelimToken::Paren),
202 match self.token.ident() {
204 if ident.is_raw_guess()
205 && self.look_ahead(1, |t| valid_follow.contains(&t.kind)) =>
207 err.span_suggestion_verbose(
208 ident.span.shrink_to_lo(),
209 &format!("escape `{}` to use it as an identifier", ident.name),
211 Applicability::MaybeIncorrect,
216 if let Some(token_descr) = super::token_descr_opt(&self.token) {
217 err.span_label(self.token.span, format!("expected identifier, found {}", token_descr));
219 err.span_label(self.token.span, "expected identifier");
220 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
225 Applicability::MachineApplicable,
232 pub(super) fn expected_one_of_not_found(
234 edible: &[TokenKind],
235 inedible: &[TokenKind],
236 ) -> PResult<'a, bool /* recovered */> {
237 debug!("expected_one_of_not_found(edible: {:?}, inedible: {:?})", edible, inedible);
238 fn tokens_to_string(tokens: &[TokenType]) -> String {
239 let mut i = tokens.iter();
240 // This might be a sign we need a connect method on `Iterator`.
241 let b = i.next().map_or_else(String::new, |t| t.to_string());
242 i.enumerate().fold(b, |mut b, (i, a)| {
243 if tokens.len() > 2 && i == tokens.len() - 2 {
245 } else if tokens.len() == 2 && i == tokens.len() - 2 {
250 b.push_str(&a.to_string());
255 let mut expected = edible
257 .map(|x| TokenType::Token(x.clone()))
258 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
259 .chain(self.expected_tokens.iter().cloned())
260 .collect::<Vec<_>>();
261 expected.sort_by_cached_key(|x| x.to_string());
264 let sm = self.sess.source_map();
265 let msg = format!("expected `;`, found {}", super::token_descr(&self.token));
266 let appl = Applicability::MachineApplicable;
267 if expected.contains(&TokenType::Token(token::Semi)) {
268 if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
269 // Likely inside a macro, can't provide meaningful suggestions.
270 } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
271 // The current token is in the same line as the prior token, not recoverable.
272 } else if [token::Comma, token::Colon].contains(&self.token.kind)
273 && self.prev_token.kind == token::CloseDelim(token::Paren)
275 // Likely typo: The current token is on a new line and is expected to be
276 // `.`, `;`, `?`, or an operator after a close delimiter token.
278 // let a = std::process::Command::new("echo")
282 // https://github.com/rust-lang/rust/issues/72253
283 } else if self.look_ahead(1, |t| {
284 t == &token::CloseDelim(token::Brace)
285 || t.can_begin_expr() && t.kind != token::Colon
286 }) && [token::Comma, token::Colon].contains(&self.token.kind)
288 // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is
289 // either `,` or `:`, and the next token could either start a new statement or is a
290 // block close. For example:
295 let sp = self.prev_token.span;
296 self.struct_span_err(sp, &msg)
297 .span_suggestion_short(sp, "change this to `;`", ";".to_string(), appl)
300 } else if self.look_ahead(0, |t| {
301 t == &token::CloseDelim(token::Brace)
303 t.can_begin_expr() && t != &token::Semi && t != &token::Pound
304 // Avoid triggering with too many trailing `#` in raw string.
307 // Missing semicolon typo. This is triggered if the next token could either start a
308 // new statement or is a block close. For example:
312 let sp = self.prev_token.span.shrink_to_hi();
313 self.struct_span_err(sp, &msg)
314 .span_label(self.token.span, "unexpected token")
315 .span_suggestion_short(sp, "add `;` here", ";".to_string(), appl)
321 let expect = tokens_to_string(&expected);
322 let actual = super::token_descr(&self.token);
323 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
324 let short_expect = if expected.len() > 6 {
325 format!("{} possible tokens", expected.len())
330 format!("expected one of {}, found {}", expect, actual),
331 (self.prev_token.span.shrink_to_hi(), format!("expected one of {}", short_expect)),
333 } else if expected.is_empty() {
335 format!("unexpected token: {}", actual),
336 (self.prev_token.span, "unexpected token after this".to_string()),
340 format!("expected {}, found {}", expect, actual),
341 (self.prev_token.span.shrink_to_hi(), format!("expected {}", expect)),
344 self.last_unexpected_token_span = Some(self.token.span);
345 let mut err = self.struct_span_err(self.token.span, &msg_exp);
347 // Add suggestion for a missing closing angle bracket if '>' is included in expected_tokens
348 // there are unclosed angle brackets
349 if self.unmatched_angle_bracket_count > 0
350 && self.token.kind == TokenKind::Eq
351 && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Gt)))
353 err.span_label(self.prev_token.span, "maybe try to close unmatched angle bracket");
356 let sp = if self.token == token::Eof {
357 // This is EOF; don't want to point at the following char, but rather the last token.
362 match self.recover_closing_delimiter(
365 .filter_map(|tt| match tt {
366 TokenType::Token(t) => Some(t.clone()),
369 .collect::<Vec<_>>(),
374 return Ok(recovered);
378 if self.check_too_many_raw_str_terminators(&mut err) {
382 if self.prev_token.span == DUMMY_SP {
383 // Account for macro context where the previous span might not be
384 // available to avoid incorrect output (#54841).
385 err.span_label(self.token.span, label_exp);
386 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
387 // When the spans are in the same line, it means that the only content between
388 // them is whitespace, point at the found token in that case:
390 // X | () => { syntax error };
391 // | ^^^^^ expected one of 8 possible tokens here
393 // instead of having:
395 // X | () => { syntax error };
396 // | -^^^^^ unexpected token
398 // | expected one of 8 possible tokens here
399 err.span_label(self.token.span, label_exp);
401 err.span_label(sp, label_exp);
402 err.span_label(self.token.span, "unexpected token");
404 self.maybe_annotate_with_ascription(&mut err, false);
408 fn check_too_many_raw_str_terminators(&mut self, err: &mut Diagnostic) -> bool {
409 match (&self.prev_token.kind, &self.token.kind) {
411 TokenKind::Literal(Lit {
412 kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
417 err.set_primary_message("too many `#` when terminating raw string");
420 "remove the extra `#`",
422 Applicability::MachineApplicable,
424 err.note(&format!("the raw string started with {} `#`s", n_hashes));
431 pub fn maybe_suggest_struct_literal(
435 ) -> Option<PResult<'a, P<Block>>> {
436 if self.token.is_ident() && self.look_ahead(1, |t| t == &token::Colon) {
437 // We might be having a struct literal where people forgot to include the path:
441 let mut snapshot = self.clone();
443 Path { segments: vec![], span: self.prev_token.span.shrink_to_lo(), tokens: None };
444 let struct_expr = snapshot.parse_struct_expr(None, path, AttrVec::new(), false);
445 let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No);
446 return Some(match (struct_expr, block_tail) {
447 (Ok(expr), Err(mut err)) => {
448 // We have encountered the following:
453 // fn foo() -> Foo { Path {
457 self.struct_span_err(expr.span, "struct literal body without path")
458 .multipart_suggestion(
459 "you might have forgotten to add the struct literal inside the block",
461 (expr.span.shrink_to_lo(), "{ SomeStruct ".to_string()),
462 (expr.span.shrink_to_hi(), " }".to_string()),
464 Applicability::MaybeIncorrect,
468 let mut tail = self.mk_block(
469 vec![self.mk_stmt_err(expr.span)],
471 lo.to(self.prev_token.span),
473 tail.could_be_bare_literal = true;
476 (Err(err), Ok(tail)) => {
477 // We have a block tail that contains a somehow valid type ascription expr.
481 (Err(snapshot_err), Err(err)) => {
482 // We don't know what went wrong, emit the normal error.
483 snapshot_err.cancel();
484 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
487 (Ok(_), Ok(mut tail)) => {
488 tail.could_be_bare_literal = true;
496 pub fn maybe_annotate_with_ascription(
498 err: &mut Diagnostic,
499 maybe_expected_semicolon: bool,
501 if let Some((sp, likely_path)) = self.last_type_ascription.take() {
502 let sm = self.sess.source_map();
503 let next_pos = sm.lookup_char_pos(self.token.span.lo());
504 let op_pos = sm.lookup_char_pos(sp.hi());
506 let allow_unstable = self.sess.unstable_features.is_nightly_build();
511 "maybe write a path separator here",
514 Applicability::MaybeIncorrect
516 Applicability::MachineApplicable
519 self.sess.type_ascription_path_suggestions.borrow_mut().insert(sp);
520 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
523 "try using a semicolon",
525 Applicability::MaybeIncorrect,
527 } else if allow_unstable {
528 err.span_label(sp, "tried to parse a type due to this type ascription");
530 err.span_label(sp, "tried to parse a type due to this");
533 // Give extra information about type ascription only if it's a nightly compiler.
535 "`#![feature(type_ascription)]` lets you annotate an expression with a type: \
539 // Avoid giving too much info when it was likely an unrelated typo.
541 "see issue #23416 <https://github.com/rust-lang/rust/issues/23416> \
542 for more information",
549 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
550 /// passes through any errors encountered. Used for error recovery.
551 pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
553 self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
554 Ok(p.parse_token_tree())
561 /// This function checks if there are trailing angle brackets and produces
562 /// a diagnostic to suggest removing them.
564 /// ```ignore (diagnostic)
565 /// let _ = [1, 2, 3].into_iter().collect::<Vec<usize>>>>();
566 /// ^^ help: remove extra angle brackets
569 /// If `true` is returned, then trailing brackets were recovered, tokens were consumed
570 /// up until one of the tokens in 'end' was encountered, and an error was emitted.
571 pub(super) fn check_trailing_angle_brackets(
573 segment: &PathSegment,
576 // This function is intended to be invoked after parsing a path segment where there are two
579 // 1. A specific token is expected after the path segment.
580 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
581 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
582 // 2. No specific token is expected after the path segment.
583 // eg. `x.foo` (field access)
585 // This function is called after parsing `.foo` and before parsing the token `end` (if
586 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
589 // We only care about trailing angle brackets if we previously parsed angle bracket
590 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
591 // removed in this case:
593 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
595 // This case is particularly tricky as we won't notice it just looking at the tokens -
596 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
597 // have already been parsed):
599 // `x.foo::<u32>>>(3)`
600 let parsed_angle_bracket_args =
601 segment.args.as_ref().map_or(false, |args| args.is_angle_bracketed());
604 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
605 parsed_angle_bracket_args,
607 if !parsed_angle_bracket_args {
611 // Keep the span at the start so we can highlight the sequence of `>` characters to be
613 let lo = self.token.span;
615 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
616 // (since we might have the field access case and the characters we're eating are
617 // actual operators and not trailing characters - ie `x.foo >> 3`).
618 let mut position = 0;
620 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
621 // many of each (so we can correctly pluralize our error messages) and continue to
623 let mut number_of_shr = 0;
624 let mut number_of_gt = 0;
625 while self.look_ahead(position, |t| {
626 trace!("check_trailing_angle_brackets: t={:?}", t);
627 if *t == token::BinOp(token::BinOpToken::Shr) {
630 } else if *t == token::Gt {
640 // If we didn't find any trailing `>` characters, then we have nothing to error about.
642 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
643 number_of_gt, number_of_shr,
645 if number_of_gt < 1 && number_of_shr < 1 {
649 // Finally, double check that we have our end token as otherwise this is the
651 if self.look_ahead(position, |t| {
652 trace!("check_trailing_angle_brackets: t={:?}", t);
653 end.contains(&&t.kind)
655 // Eat from where we started until the end token so that parsing can continue
656 // as if we didn't have those extra angle brackets.
657 self.eat_to_tokens(end);
658 let span = lo.until(self.token.span);
660 let total_num_of_gt = number_of_gt + number_of_shr * 2;
661 self.struct_span_err(
663 &format!("unmatched angle bracket{}", pluralize!(total_num_of_gt)),
667 &format!("remove extra angle bracket{}", pluralize!(total_num_of_gt)),
669 Applicability::MachineApplicable,
677 /// Check if a method call with an intended turbofish has been written without surrounding
679 pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
680 if token::ModSep == self.token.kind && segment.args.is_none() {
681 let snapshot = self.clone();
683 let lo = self.token.span;
684 match self.parse_angle_args(None) {
686 let span = lo.to(self.prev_token.span);
687 // Detect trailing `>` like in `x.collect::Vec<_>>()`.
688 let mut trailing_span = self.prev_token.span.shrink_to_hi();
689 while self.token.kind == token::BinOp(token::Shr)
690 || self.token.kind == token::Gt
692 trailing_span = trailing_span.to(self.token.span);
695 if self.token.kind == token::OpenDelim(token::Paren) {
696 // Recover from bad turbofish: `foo.collect::Vec<_>()`.
697 let args = AngleBracketedArgs { args, span }.into();
700 self.struct_span_err(
702 "generic parameters without surrounding angle brackets",
704 .multipart_suggestion(
705 "surround the type parameters with angle brackets",
707 (span.shrink_to_lo(), "<".to_string()),
708 (trailing_span, ">".to_string()),
710 Applicability::MachineApplicable,
714 // This doesn't look like an invalid turbofish, can't recover parse state.
719 // We couldn't parse generic parameters, unlikely to be a turbofish. Rely on
720 // generic parse error instead.
728 /// When writing a turbofish with multiple type parameters missing the leading `::`, we will
729 /// encounter a parse error when encountering the first `,`.
730 pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
732 mut e: DiagnosticBuilder<'a, ErrorGuaranteed>,
734 ) -> PResult<'a, ()> {
735 if let ExprKind::Binary(binop, _, _) = &expr.kind
736 && let ast::BinOpKind::Lt = binop.node
737 && self.eat(&token::Comma)
739 let x = self.parse_seq_to_before_end(
741 SeqSep::trailing_allowed(token::Comma),
742 |p| p.parse_generic_arg(None),
745 Ok((_, _, false)) => {
746 if self.eat(&token::Gt) {
747 e.span_suggestion_verbose(
748 binop.span.shrink_to_lo(),
749 TURBOFISH_SUGGESTION_STR,
751 Applicability::MaybeIncorrect,
754 match self.parse_expr() {
757 self.mk_expr_err(expr.span.to(self.prev_token.span));
761 *expr = self.mk_expr_err(expr.span);
776 /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
777 /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
778 /// parenthesising the leftmost comparison.
779 fn attempt_chained_comparison_suggestion(
781 err: &mut Diagnostic,
783 outer_op: &Spanned<AssocOp>,
784 ) -> bool /* advanced the cursor */ {
785 if let ExprKind::Binary(op, ref l1, ref r1) = inner_op.kind {
786 if let ExprKind::Field(_, ident) = l1.kind
787 && ident.as_str().parse::<i32>().is_err()
788 && !matches!(r1.kind, ExprKind::Lit(_))
790 // The parser has encountered `foo.bar<baz`, the likelihood of the turbofish
791 // suggestion being the only one to apply is high.
794 let mut enclose = |left: Span, right: Span| {
795 err.multipart_suggestion(
796 "parenthesize the comparison",
798 (left.shrink_to_lo(), "(".to_string()),
799 (right.shrink_to_hi(), ")".to_string()),
801 Applicability::MaybeIncorrect,
804 return match (op.node, &outer_op.node) {
806 (BinOpKind::Eq, AssocOp::Equal) |
807 // `x < y < z` and friends.
808 (BinOpKind::Lt, AssocOp::Less | AssocOp::LessEqual) |
809 (BinOpKind::Le, AssocOp::LessEqual | AssocOp::Less) |
810 // `x > y > z` and friends.
811 (BinOpKind::Gt, AssocOp::Greater | AssocOp::GreaterEqual) |
812 (BinOpKind::Ge, AssocOp::GreaterEqual | AssocOp::Greater) => {
813 let expr_to_str = |e: &Expr| {
814 self.span_to_snippet(e.span)
815 .unwrap_or_else(|_| pprust::expr_to_string(&e))
817 err.span_suggestion_verbose(
818 inner_op.span.shrink_to_hi(),
819 "split the comparison into two",
820 format!(" && {}", expr_to_str(&r1)),
821 Applicability::MaybeIncorrect,
823 false // Keep the current parse behavior, where the AST is `(x < y) < z`.
826 (BinOpKind::Eq, AssocOp::Less | AssocOp::LessEqual | AssocOp::Greater | AssocOp::GreaterEqual) => {
827 // Consume `z`/outer-op-rhs.
828 let snapshot = self.clone();
829 match self.parse_expr() {
831 // We are sure that outer-op-rhs could be consumed, the suggestion is
833 enclose(r1.span, r2.span);
844 (BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge, AssocOp::Equal) => {
845 let snapshot = self.clone();
846 // At this point it is always valid to enclose the lhs in parentheses, no
847 // further checks are necessary.
848 match self.parse_expr() {
850 enclose(l1.span, r1.span);
866 /// Produces an error if comparison operators are chained (RFC #558).
867 /// We only need to check the LHS, not the RHS, because all comparison ops have same
868 /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
870 /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
871 /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
874 /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
875 /// associative we can infer that we have:
884 pub(super) fn check_no_chained_comparison(
887 outer_op: &Spanned<AssocOp>,
888 ) -> PResult<'a, Option<P<Expr>>> {
890 outer_op.node.is_comparison(),
891 "check_no_chained_comparison: {:?} is not comparison",
896 |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err, AttrVec::new())));
898 match inner_op.kind {
899 ExprKind::Binary(op, ref l1, ref r1) if op.node.is_comparison() => {
900 let mut err = self.struct_span_err(
901 vec![op.span, self.prev_token.span],
902 "comparison operators cannot be chained",
905 let suggest = |err: &mut Diagnostic| {
906 err.span_suggestion_verbose(
907 op.span.shrink_to_lo(),
908 TURBOFISH_SUGGESTION_STR,
910 Applicability::MaybeIncorrect,
914 // Include `<` to provide this recommendation even in a case like
915 // `Foo<Bar<Baz<Qux, ()>>>`
916 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Less
917 || outer_op.node == AssocOp::Greater
919 if outer_op.node == AssocOp::Less {
920 let snapshot = self.clone();
922 // So far we have parsed `foo<bar<`, consume the rest of the type args.
924 [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
925 self.consume_tts(1, &modifiers);
927 if !&[token::OpenDelim(token::Paren), token::ModSep]
928 .contains(&self.token.kind)
930 // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
931 // parser and bail out.
932 *self = snapshot.clone();
935 return if token::ModSep == self.token.kind {
936 // We have some certainty that this was a bad turbofish at this point.
940 let snapshot = self.clone();
943 // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
944 match self.parse_expr() {
946 // 99% certain that the suggestion is correct, continue parsing.
948 // FIXME: actually check that the two expressions in the binop are
949 // paths and resynthesize new fn call expression instead of using
950 // `ExprKind::Err` placeholder.
951 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
955 // Not entirely sure now, but we bubble the error up with the
961 } else if token::OpenDelim(token::Paren) == self.token.kind {
962 // We have high certainty that this was a bad turbofish at this point.
965 // Consume the fn call arguments.
966 match self.consume_fn_args() {
970 // FIXME: actually check that the two expressions in the binop are
971 // paths and resynthesize new fn call expression instead of using
972 // `ExprKind::Err` placeholder.
973 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
977 if !matches!(l1.kind, ExprKind::Lit(_))
978 && !matches!(r1.kind, ExprKind::Lit(_))
980 // All we know is that this is `foo < bar >` and *nothing* else. Try to
981 // be helpful, but don't attempt to recover.
982 err.help(TURBOFISH_SUGGESTION_STR);
983 err.help("or use `(...)` if you meant to specify fn arguments");
986 // If it looks like a genuine attempt to chain operators (as opposed to a
987 // misformatted turbofish, for instance), suggest a correct form.
988 if self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op)
991 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
993 // These cases cause too many knock-down errors, bail out (#61329).
999 self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1002 return mk_err_expr(self, inner_op.span.to(self.prev_token.span));
1010 fn consume_fn_args(&mut self) -> Result<(), ()> {
1011 let snapshot = self.clone();
1014 // Consume the fn call arguments.
1016 [(token::OpenDelim(token::Paren), 1), (token::CloseDelim(token::Paren), -1)];
1017 self.consume_tts(1, &modifiers);
1019 if self.token.kind == token::Eof {
1020 // Not entirely sure that what we consumed were fn arguments, rollback.
1024 // 99% certain that the suggestion is correct, continue parsing.
1029 pub(super) fn maybe_report_ambiguous_plus(
1031 allow_plus: AllowPlus,
1032 impl_dyn_multi: bool,
1035 if matches!(allow_plus, AllowPlus::No) && impl_dyn_multi {
1036 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1037 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1040 "use parentheses to disambiguate",
1042 Applicability::MachineApplicable,
1048 /// Swift lets users write `Ty?` to mean `Option<Ty>`. Parse the construct and recover from it.
1049 pub(super) fn maybe_recover_from_question_mark(
1052 recover_question_mark: RecoverQuestionMark,
1054 if let RecoverQuestionMark::No = recover_question_mark {
1057 if self.token == token::Question {
1059 self.struct_span_err(self.prev_token.span, "invalid `?` in type")
1060 .span_label(self.prev_token.span, "`?` is only allowed on expressions, not types")
1061 .multipart_suggestion(
1062 "if you meant to express that the type might not contain a value, use the `Option` wrapper type",
1064 (ty.span.shrink_to_lo(), "Option<".to_string()),
1065 (self.prev_token.span, ">".to_string()),
1067 Applicability::MachineApplicable,
1070 self.mk_ty(ty.span.to(self.prev_token.span), TyKind::Err)
1076 pub(super) fn maybe_recover_from_bad_type_plus(
1078 allow_plus: AllowPlus,
1080 ) -> PResult<'a, ()> {
1081 // Do not add `+` to expected tokens.
1082 if matches!(allow_plus, AllowPlus::No) || !self.token.is_like_plus() {
1087 let bounds = self.parse_generic_bounds(None)?;
1088 let sum_span = ty.span.to(self.prev_token.span);
1090 let mut err = struct_span_err!(
1091 self.sess.span_diagnostic,
1094 "expected a path on the left-hand side of `+`, not `{}`",
1095 pprust::ty_to_string(ty)
1099 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1100 let sum_with_parens = pprust::to_string(|s| {
1102 s.print_opt_lifetime(lifetime);
1103 s.print_mutability(mut_ty.mutbl, false);
1105 s.print_type(&mut_ty.ty);
1106 s.print_type_bounds(" +", &bounds);
1109 err.span_suggestion(
1111 "try adding parentheses",
1113 Applicability::MachineApplicable,
1116 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1117 err.span_label(sum_span, "perhaps you forgot parentheses?");
1120 err.span_label(sum_span, "expected a path");
1127 /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
1128 /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
1129 /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
1130 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
1133 allow_recovery: bool,
1134 ) -> PResult<'a, P<T>> {
1135 // Do not add `::` to expected tokens.
1136 if allow_recovery && self.token == token::ModSep {
1137 if let Some(ty) = base.to_ty() {
1138 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1144 /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
1145 /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
1146 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
1150 ) -> PResult<'a, P<T>> {
1151 self.expect(&token::ModSep)?;
1153 let mut path = ast::Path { segments: Vec::new(), span: DUMMY_SP, tokens: None };
1154 self.parse_path_segments(&mut path.segments, T::PATH_STYLE, None)?;
1155 path.span = ty_span.to(self.prev_token.span);
1157 let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
1158 self.struct_span_err(path.span, "missing angle brackets in associated item path")
1160 // This is a best-effort recovery.
1163 format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
1164 Applicability::MaybeIncorrect,
1168 let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
1169 Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path)))
1172 pub fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
1173 if self.token.kind == TokenKind::Semi {
1175 let mut err = self.struct_span_err(self.prev_token.span, "expected item, found `;`");
1176 err.span_suggestion_short(
1177 self.prev_token.span,
1178 "remove this semicolon",
1180 Applicability::MachineApplicable,
1182 if !items.is_empty() {
1183 let previous_item = &items[items.len() - 1];
1184 let previous_item_kind_name = match previous_item.kind {
1185 // Say "braced struct" because tuple-structs and
1186 // braceless-empty-struct declarations do take a semicolon.
1187 ItemKind::Struct(..) => Some("braced struct"),
1188 ItemKind::Enum(..) => Some("enum"),
1189 ItemKind::Trait(..) => Some("trait"),
1190 ItemKind::Union(..) => Some("union"),
1193 if let Some(name) = previous_item_kind_name {
1194 err.help(&format!("{} declarations are not followed by a semicolon", name));
1204 /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
1205 /// closing delimiter.
1206 pub(super) fn unexpected_try_recover(
1209 ) -> PResult<'a, bool /* recovered */> {
1210 let token_str = pprust::token_kind_to_string(t);
1211 let this_token_str = super::token_descr(&self.token);
1212 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1213 // Point at the end of the macro call when reaching end of macro arguments.
1214 (token::Eof, Some(_)) => {
1215 let sp = self.sess.source_map().next_point(self.prev_token.span);
1218 // We don't want to point at the following span after DUMMY_SP.
1219 // This happens when the parser finds an empty TokenStream.
1220 _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
1221 // EOF, don't want to point at the following char, but rather the last token.
1222 (token::Eof, None) => (self.prev_token.span, self.token.span),
1223 _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
1226 "expected `{}`, found {}",
1228 match (&self.token.kind, self.subparser_name) {
1229 (token::Eof, Some(origin)) => format!("end of {}", origin),
1230 _ => this_token_str,
1233 let mut err = self.struct_span_err(sp, &msg);
1234 let label_exp = format!("expected `{}`", token_str);
1235 match self.recover_closing_delimiter(&[t.clone()], err) {
1238 return Ok(recovered);
1241 let sm = self.sess.source_map();
1242 if !sm.is_multiline(prev_sp.until(sp)) {
1243 // When the spans are in the same line, it means that the only content
1244 // between them is whitespace, point only at the found token.
1245 err.span_label(sp, label_exp);
1247 err.span_label(prev_sp, label_exp);
1248 err.span_label(sp, "unexpected token");
1253 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1254 if self.eat(&token::Semi) {
1257 self.expect(&token::Semi).map(drop) // Error unconditionally
1260 /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
1261 /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
1262 pub(super) fn recover_incorrect_await_syntax(
1267 ) -> PResult<'a, P<Expr>> {
1268 let (hi, expr, is_question) = if self.token == token::Not {
1269 // Handle `await!(<expr>)`.
1270 self.recover_await_macro()?
1272 self.recover_await_prefix(await_sp)?
1274 let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
1275 let kind = match expr.kind {
1276 // Avoid knock-down errors as we don't know whether to interpret this as `foo().await?`
1277 // or `foo()?.await` (the very reason we went with postfix syntax 😅).
1278 ExprKind::Try(_) => ExprKind::Err,
1279 _ => ExprKind::Await(expr),
1281 let expr = self.mk_expr(lo.to(sp), kind, attrs);
1282 self.maybe_recover_from_bad_qpath(expr, true)
1285 fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1286 self.expect(&token::Not)?;
1287 self.expect(&token::OpenDelim(token::Paren))?;
1288 let expr = self.parse_expr()?;
1289 self.expect(&token::CloseDelim(token::Paren))?;
1290 Ok((self.prev_token.span, expr, false))
1293 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
1294 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
1295 let expr = if self.token == token::OpenDelim(token::Brace) {
1296 // Handle `await { <expr> }`.
1297 // This needs to be handled separately from the next arm to avoid
1298 // interpreting `await { <expr> }?` as `<expr>?.await`.
1299 self.parse_block_expr(None, self.token.span, BlockCheckMode::Default, AttrVec::new())
1303 .map_err(|mut err| {
1304 err.span_label(await_sp, "while parsing this incorrect await expression");
1307 Ok((expr.span, expr, is_question))
1310 fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
1312 self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr));
1313 let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" });
1315 let app = match expr.kind {
1316 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
1317 _ => Applicability::MachineApplicable,
1319 self.struct_span_err(sp, "incorrect use of `await`")
1320 .span_suggestion(sp, "`await` is a postfix operation", suggestion, app)
1325 /// If encountering `future.await()`, consumes and emits an error.
1326 pub(super) fn recover_from_await_method_call(&mut self) {
1327 if self.token == token::OpenDelim(token::Paren)
1328 && self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren))
1331 let lo = self.token.span;
1333 let sp = lo.to(self.token.span);
1335 self.struct_span_err(sp, "incorrect use of `await`")
1338 "`await` is not a method call, remove the parentheses",
1340 Applicability::MachineApplicable,
1346 pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, P<Expr>> {
1347 let is_try = self.token.is_keyword(kw::Try);
1348 let is_questionmark = self.look_ahead(1, |t| t == &token::Not); //check for !
1349 let is_open = self.look_ahead(2, |t| t == &token::OpenDelim(token::Paren)); //check for (
1351 if is_try && is_questionmark && is_open {
1352 let lo = self.token.span;
1353 self.bump(); //remove try
1354 self.bump(); //remove !
1355 let try_span = lo.to(self.token.span); //we take the try!( span
1356 self.bump(); //remove (
1357 let is_empty = self.token == token::CloseDelim(token::Paren); //check if the block is empty
1358 self.consume_block(token::Paren, ConsumeClosingDelim::No); //eat the block
1359 let hi = self.token.span;
1360 self.bump(); //remove )
1361 let mut err = self.struct_span_err(lo.to(hi), "use of deprecated `try` macro");
1362 err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
1363 let prefix = if is_empty { "" } else { "alternatively, " };
1365 err.multipart_suggestion(
1366 "you can use the `?` operator instead",
1367 vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
1368 Applicability::MachineApplicable,
1371 err.span_suggestion(lo.shrink_to_lo(), &format!("{}you can still access the deprecated `try!()` macro using the \"raw identifier\" syntax", prefix), "r#".to_string(), Applicability::MachineApplicable);
1373 Ok(self.mk_expr_err(lo.to(hi)))
1375 Err(self.expected_expression_found()) // The user isn't trying to invoke the try! macro
1379 /// Recovers a situation like `for ( $pat in $expr )`
1380 /// and suggest writing `for $pat in $expr` instead.
1382 /// This should be called before parsing the `$block`.
1383 pub(super) fn recover_parens_around_for_head(
1386 begin_paren: Option<Span>,
1388 match (&self.token.kind, begin_paren) {
1389 (token::CloseDelim(token::Paren), Some(begin_par_sp)) => {
1392 self.struct_span_err(
1393 MultiSpan::from_spans(vec![begin_par_sp, self.prev_token.span]),
1394 "unexpected parentheses surrounding `for` loop head",
1396 .multipart_suggestion(
1397 "remove parentheses in `for` loop",
1398 vec![(begin_par_sp, String::new()), (self.prev_token.span, String::new())],
1399 // With e.g. `for (x) in y)` this would replace `(x) in y)`
1400 // with `x) in y)` which is syntactically invalid.
1401 // However, this is prevented before we get here.
1402 Applicability::MachineApplicable,
1406 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1407 pat.and_then(|pat| match pat.kind {
1408 PatKind::Paren(pat) => pat,
1416 pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1417 (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1418 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1419 || self.token.is_ident() &&
1420 matches!(node, ast::ExprKind::Path(..) | ast::ExprKind::Field(..)) &&
1421 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
1422 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren))
1423 || self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) // `foo:bar {`
1424 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar::<baz`
1425 self.look_ahead(2, |t| t == &token::Lt) &&
1426 self.look_ahead(3, |t| t.is_ident())
1427 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
1428 self.look_ahead(2, |t| t.is_ident())
1429 || self.look_ahead(1, |t| t == &token::ModSep)
1430 && (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
1431 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1434 pub(super) fn recover_seq_parse_error(
1436 delim: token::DelimToken,
1438 result: PResult<'a, P<Expr>>,
1444 // Recover from parse error, callers expect the closing delim to be consumed.
1445 self.consume_block(delim, ConsumeClosingDelim::Yes);
1446 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err, AttrVec::new())
1451 pub(super) fn recover_closing_delimiter(
1453 tokens: &[TokenKind],
1454 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
1455 ) -> PResult<'a, bool> {
1457 // We want to use the last closing delim that would apply.
1458 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1459 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1460 && Some(self.token.span) > unmatched.unclosed_span
1467 // Recover and assume that the detected unclosed delimiter was meant for
1468 // this location. Emit the diagnostic and act as if the delimiter was
1469 // present for the parser's sake.
1471 // Don't attempt to recover from this unclosed delimiter more than once.
1472 let unmatched = self.unclosed_delims.remove(pos);
1473 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1474 if unmatched.found_delim.is_none() {
1475 // We encountered `Eof`, set this fact here to avoid complaining about missing
1476 // `fn main()` when we found place to suggest the closing brace.
1477 *self.sess.reached_eof.borrow_mut() = true;
1480 // We want to suggest the inclusion of the closing delimiter where it makes
1481 // the most sense, which is immediately after the last token:
1486 // | help: `)` may belong here
1488 // unclosed delimiter
1489 if let Some(sp) = unmatched.unclosed_span {
1490 let mut primary_span: Vec<Span> =
1491 err.span.primary_spans().iter().cloned().collect();
1492 primary_span.push(sp);
1493 let mut primary_span: MultiSpan = primary_span.into();
1494 for span_label in err.span.span_labels() {
1495 if let Some(label) = span_label.label {
1496 primary_span.push_span_label(span_label.span, label);
1499 err.set_span(primary_span);
1500 err.span_label(sp, "unclosed delimiter");
1502 // Backticks should be removed to apply suggestions.
1503 let mut delim = delim.to_string();
1504 delim.retain(|c| c != '`');
1505 err.span_suggestion_short(
1506 self.prev_token.span.shrink_to_hi(),
1507 &format!("`{}` may belong here", delim),
1509 Applicability::MaybeIncorrect,
1511 if unmatched.found_delim.is_none() {
1512 // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1513 // errors which would be emitted elsewhere in the parser and let other error
1514 // recovery consume the rest of the file.
1518 self.expected_tokens.clear(); // Reduce the number of errors.
1526 /// Eats tokens until we can be relatively sure we reached the end of the
1527 /// statement. This is something of a best-effort heuristic.
1529 /// We terminate when we find an unmatched `}` (without consuming it).
1530 pub(super) fn recover_stmt(&mut self) {
1531 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1534 /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1535 /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1536 /// approximate -- it can mean we break too early due to macros, but that
1537 /// should only lead to sub-optimal recovery, not inaccurate parsing).
1539 /// If `break_on_block` is `Break`, then we will stop consuming tokens
1540 /// after finding (and consuming) a brace-delimited block.
1541 pub(super) fn recover_stmt_(
1543 break_on_semi: SemiColonMode,
1544 break_on_block: BlockMode,
1546 let mut brace_depth = 0;
1547 let mut bracket_depth = 0;
1548 let mut in_block = false;
1549 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1551 debug!("recover_stmt_ loop {:?}", self.token);
1552 match self.token.kind {
1553 token::OpenDelim(token::DelimToken::Brace) => {
1556 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1561 token::OpenDelim(token::DelimToken::Bracket) => {
1565 token::CloseDelim(token::DelimToken::Brace) => {
1566 if brace_depth == 0 {
1567 debug!("recover_stmt_ return - close delim {:?}", self.token);
1572 if in_block && bracket_depth == 0 && brace_depth == 0 {
1573 debug!("recover_stmt_ return - block end {:?}", self.token);
1577 token::CloseDelim(token::DelimToken::Bracket) => {
1579 if bracket_depth < 0 {
1585 debug!("recover_stmt_ return - Eof");
1590 if break_on_semi == SemiColonMode::Break
1592 && bracket_depth == 0
1594 debug!("recover_stmt_ return - Semi");
1599 if break_on_semi == SemiColonMode::Comma
1601 && bracket_depth == 0 =>
1603 debug!("recover_stmt_ return - Semi");
1611 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1612 if self.eat_keyword(kw::In) {
1613 // a common typo: `for _ in in bar {}`
1614 self.struct_span_err(self.prev_token.span, "expected iterable, found keyword `in`")
1615 .span_suggestion_short(
1616 in_span.until(self.prev_token.span),
1617 "remove the duplicated `in`",
1619 Applicability::MachineApplicable,
1625 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1626 if let token::DocComment(..) = self.token.kind {
1627 self.struct_span_err(
1629 "documentation comments cannot be applied to a function parameter's type",
1631 .span_label(self.token.span, "doc comments are not allowed here")
1634 } else if self.token == token::Pound
1635 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Bracket))
1637 let lo = self.token.span;
1638 // Skip every token until next possible arg.
1639 while self.token != token::CloseDelim(token::Bracket) {
1642 let sp = lo.to(self.token.span);
1644 self.struct_span_err(sp, "attributes cannot be applied to a function parameter's type")
1645 .span_label(sp, "attributes are not allowed here")
1650 pub(super) fn parameter_without_type(
1652 err: &mut Diagnostic,
1656 ) -> Option<Ident> {
1657 // If we find a pattern followed by an identifier, it could be an (incorrect)
1658 // C-style parameter declaration.
1659 if self.check_ident()
1660 && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseDelim(token::Paren))
1662 // `fn foo(String s) {}`
1663 let ident = self.parse_ident().unwrap();
1664 let span = pat.span.with_hi(ident.span.hi());
1666 err.span_suggestion(
1668 "declare the type after the parameter binding",
1669 String::from("<identifier>: <type>"),
1670 Applicability::HasPlaceholders,
1673 } else if require_name
1674 && (self.token == token::Comma
1675 || self.token == token::Lt
1676 || self.token == token::CloseDelim(token::Paren))
1678 let rfc_note = "anonymous parameters are removed in the 2018 edition (see RFC 1685)";
1680 let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
1682 PatKind::Ident(_, ident, _) => (
1684 "self: ".to_string(),
1685 ": TypeName".to_string(),
1687 pat.span.shrink_to_lo(),
1688 pat.span.shrink_to_hi(),
1689 pat.span.shrink_to_lo(),
1691 // Also catches `fn foo(&a)`.
1692 PatKind::Ref(ref inner_pat, mutab)
1693 if matches!(inner_pat.clone().into_inner().kind, PatKind::Ident(..)) =>
1695 match inner_pat.clone().into_inner().kind {
1696 PatKind::Ident(_, ident, _) => {
1697 let mutab = mutab.prefix_str();
1700 "self: ".to_string(),
1701 format!("{}: &{}TypeName", ident, mutab),
1703 pat.span.shrink_to_lo(),
1705 pat.span.shrink_to_lo(),
1708 _ => unreachable!(),
1712 // Otherwise, try to get a type and emit a suggestion.
1713 if let Some(ty) = pat.to_ty() {
1714 err.span_suggestion_verbose(
1716 "explicitly ignore the parameter name",
1717 format!("_: {}", pprust::ty_to_string(&ty)),
1718 Applicability::MachineApplicable,
1727 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1729 err.span_suggestion(
1731 "if this is a `self` type, give it a parameter name",
1733 Applicability::MaybeIncorrect,
1736 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
1737 // `fn foo(HashMap: TypeName<u32>)`.
1738 if self.token != token::Lt {
1739 err.span_suggestion(
1741 "if this is a parameter name, give it a type",
1743 Applicability::HasPlaceholders,
1746 err.span_suggestion(
1748 "if this is a type, explicitly ignore the parameter name",
1750 Applicability::MachineApplicable,
1754 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
1755 return if self.token == token::Lt { None } else { Some(ident) };
1760 pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
1761 let pat = self.parse_pat_no_top_alt(Some("argument name"))?;
1762 self.expect(&token::Colon)?;
1763 let ty = self.parse_ty()?;
1769 "patterns aren't allowed in methods without bodies",
1771 .span_suggestion_short(
1773 "give this argument a name or use an underscore to ignore it",
1775 Applicability::MachineApplicable,
1779 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1781 P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID, tokens: None });
1785 pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
1786 let sp = param.pat.span;
1787 param.ty.kind = TyKind::Err;
1788 self.struct_span_err(sp, "unexpected `self` parameter in function")
1789 .span_label(sp, "must be the first parameter of an associated function")
1794 pub(super) fn consume_block(
1796 delim: token::DelimToken,
1797 consume_close: ConsumeClosingDelim,
1799 let mut brace_depth = 0;
1801 if self.eat(&token::OpenDelim(delim)) {
1803 } else if self.check(&token::CloseDelim(delim)) {
1804 if brace_depth == 0 {
1805 if let ConsumeClosingDelim::Yes = consume_close {
1806 // Some of the callers of this method expect to be able to parse the
1807 // closing delimiter themselves, so we leave it alone. Otherwise we advance
1817 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
1825 pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1826 let (span, msg) = match (&self.token.kind, self.subparser_name) {
1827 (&token::Eof, Some(origin)) => {
1828 let sp = self.sess.source_map().next_point(self.prev_token.span);
1829 (sp, format!("expected expression, found end of {}", origin))
1833 format!("expected expression, found {}", super::token_descr(&self.token),),
1836 let mut err = self.struct_span_err(span, &msg);
1837 let sp = self.sess.source_map().start_point(self.token.span);
1838 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
1839 self.sess.expr_parentheses_needed(&mut err, *sp);
1841 err.span_label(span, "expected expression");
1847 mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
1848 // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
1849 modifier: &[(token::TokenKind, i64)],
1852 if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
1855 if self.token.kind == token::Eof {
1862 /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
1864 /// This is necessary because at this point we don't know whether we parsed a function with
1865 /// anonymous parameters or a function with names but no types. In order to minimize
1866 /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
1867 /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
1868 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
1869 /// we deduplicate them to not complain about duplicated parameter names.
1870 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
1871 let mut seen_inputs = FxHashSet::default();
1872 for input in fn_inputs.iter_mut() {
1873 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
1874 (&input.pat.kind, &input.ty.kind)
1880 if let Some(ident) = opt_ident {
1881 if seen_inputs.contains(&ident) {
1882 input.pat.kind = PatKind::Wild;
1884 seen_inputs.insert(ident);
1889 /// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
1890 /// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
1891 /// like the user has forgotten them.
1892 pub fn handle_ambiguous_unbraced_const_arg(
1894 args: &mut Vec<AngleBracketedArg>,
1895 ) -> PResult<'a, bool> {
1896 // If we haven't encountered a closing `>`, then the argument is malformed.
1897 // It's likely that the user has written a const expression without enclosing it
1898 // in braces, so we try to recover here.
1899 let arg = args.pop().unwrap();
1900 // FIXME: for some reason using `unexpected` or `expected_one_of_not_found` has
1901 // adverse side-effects to subsequent errors and seems to advance the parser.
1902 // We are causing this error here exclusively in case that a `const` expression
1903 // could be recovered from the current parser state, even if followed by more
1904 // arguments after a comma.
1905 let mut err = self.struct_span_err(
1907 &format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
1909 err.span_label(self.token.span, "expected one of `,` or `>`");
1910 match self.recover_const_arg(arg.span(), err) {
1912 args.push(AngleBracketedArg::Arg(arg));
1913 if self.eat(&token::Comma) {
1914 return Ok(true); // Continue
1919 // We will emit a more generic error later.
1923 return Ok(false); // Don't continue.
1926 /// Attempt to parse a generic const argument that has not been enclosed in braces.
1927 /// There are a limited number of expressions that are permitted without being encoded
1930 /// - Single-segment paths (i.e. standalone generic const parameters).
1931 /// All other expressions that can be parsed will emit an error suggesting the expression be
1932 /// wrapped in braces.
1933 pub fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
1934 let start = self.token.span;
1935 let expr = self.parse_expr_res(Restrictions::CONST_EXPR, None).map_err(|mut err| {
1937 start.shrink_to_lo(),
1938 "while parsing a const generic argument starting here",
1942 if !self.expr_is_valid_const_arg(&expr) {
1943 self.struct_span_err(
1945 "expressions must be enclosed in braces to be used as const generic \
1948 .multipart_suggestion(
1949 "enclose the `const` expression in braces",
1951 (expr.span.shrink_to_lo(), "{ ".to_string()),
1952 (expr.span.shrink_to_hi(), " }".to_string()),
1954 Applicability::MachineApplicable,
1961 fn recover_const_param_decl(&mut self, ty_generics: Option<&Generics>) -> Option<GenericArg> {
1962 let snapshot = self.clone();
1963 let param = match self.parse_const_param(vec![]) {
1972 self.struct_span_err(param.span(), "unexpected `const` parameter declaration");
1973 err.span_label(param.span(), "expected a `const` expression, not a parameter declaration");
1974 if let (Some(generics), Ok(snippet)) =
1975 (ty_generics, self.sess.source_map().span_to_snippet(param.span()))
1977 let (span, sugg) = match &generics.params[..] {
1978 [] => (generics.span, format!("<{}>", snippet)),
1979 [.., generic] => (generic.span().shrink_to_hi(), format!(", {}", snippet)),
1981 err.multipart_suggestion(
1982 "`const` parameters must be declared for the `impl`",
1983 vec![(span, sugg), (param.span(), param.ident.to_string())],
1984 Applicability::MachineApplicable,
1987 let value = self.mk_expr_err(param.span());
1989 Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }))
1992 pub fn recover_const_param_declaration(
1994 ty_generics: Option<&Generics>,
1995 ) -> PResult<'a, Option<GenericArg>> {
1996 // We have to check for a few different cases.
1997 if let Some(arg) = self.recover_const_param_decl(ty_generics) {
1998 return Ok(Some(arg));
2001 // We haven't consumed `const` yet.
2002 let start = self.token.span;
2003 self.bump(); // `const`
2005 // Detect and recover from the old, pre-RFC2000 syntax for const generics.
2007 .struct_span_err(start, "expected lifetime, type, or constant, found keyword `const`");
2008 if self.check_const_arg() {
2009 err.span_suggestion_verbose(
2010 start.until(self.token.span),
2011 "the `const` keyword is only needed in the definition of the type",
2013 Applicability::MaybeIncorrect,
2016 Ok(Some(GenericArg::Const(self.parse_const_arg()?)))
2018 let after_kw_const = self.token.span;
2019 self.recover_const_arg(after_kw_const, err).map(Some)
2023 /// Try to recover from possible generic const argument without `{` and `}`.
2025 /// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
2026 /// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
2027 /// if we think that that the resulting expression would be well formed.
2028 pub fn recover_const_arg(
2031 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2032 ) -> PResult<'a, GenericArg> {
2033 let is_op_or_dot = AssocOp::from_token(&self.token)
2035 if let AssocOp::Greater
2037 | AssocOp::ShiftRight
2038 | AssocOp::GreaterEqual
2039 // Don't recover from `foo::<bar = baz>`, because this could be an attempt to
2040 // assign a value to a defaulted generic parameter.
2042 | AssocOp::AssignOp(_) = op
2050 || self.token.kind == TokenKind::Dot;
2051 // This will be true when a trait object type `Foo +` or a path which was a `const fn` with
2052 // type params has been parsed.
2054 matches!(self.prev_token.kind, token::BinOp(token::Plus | token::Shr) | token::Gt);
2055 if !is_op_or_dot && !was_op {
2056 // We perform these checks and early return to avoid taking a snapshot unnecessarily.
2059 let snapshot = self.clone();
2063 match self.parse_expr_res(Restrictions::CONST_EXPR, None) {
2065 // Find a mistake like `MyTrait<Assoc == S::Assoc>`.
2066 if token::EqEq == snapshot.token.kind {
2067 err.span_suggestion(
2068 snapshot.token.span,
2069 "if you meant to use an associated type binding, replace `==` with `=`",
2071 Applicability::MaybeIncorrect,
2073 let value = self.mk_expr_err(start.to(expr.span));
2075 return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
2076 } else if token::Comma == self.token.kind || self.token.kind.should_end_const_arg()
2078 // Avoid the following output by checking that we consumed a full const arg:
2079 // help: expressions must be enclosed in braces to be used as const generic
2082 // LL | let sr: Vec<{ (u32, _, _) = vec![] };
2084 return Ok(self.dummy_const_arg_needs_braces(err, start.to(expr.span)));
2095 /// Creates a dummy const argument, and reports that the expression must be enclosed in braces
2096 pub fn dummy_const_arg_needs_braces(
2098 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2101 err.multipart_suggestion(
2102 "expressions must be enclosed in braces to be used as const generic \
2104 vec![(span.shrink_to_lo(), "{ ".to_string()), (span.shrink_to_hi(), " }".to_string())],
2105 Applicability::MaybeIncorrect,
2107 let value = self.mk_expr_err(span);
2109 GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })
2112 /// Get the diagnostics for the cases where `move async` is found.
2114 /// `move_async_span` starts at the 'm' of the move keyword and ends with the 'c' of the async keyword
2115 pub(super) fn incorrect_move_async_order_found(
2117 move_async_span: Span,
2118 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2120 self.struct_span_err(move_async_span, "the order of `move` and `async` is incorrect");
2121 err.span_suggestion_verbose(
2123 "try switching the order",
2124 "async move".to_owned(),
2125 Applicability::MaybeIncorrect,
2130 /// Some special error handling for the "top-level" patterns in a match arm,
2131 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2132 crate fn maybe_recover_colon_colon_in_pat_typo(
2134 mut first_pat: P<Pat>,
2138 if RecoverColon::Yes != ra || token::Colon != self.token.kind {
2141 if !matches!(first_pat.kind, PatKind::Ident(_, _, None) | PatKind::Path(..))
2142 || !self.look_ahead(1, |token| token.is_ident() && !token.is_reserved_ident())
2146 // The pattern looks like it might be a path with a `::` -> `:` typo:
2147 // `match foo { bar:baz => {} }`
2148 let span = self.token.span;
2149 // We only emit "unexpected `:`" error here if we can successfully parse the
2150 // whole pattern correctly in that case.
2151 let snapshot = self.clone();
2153 // Create error for "unexpected `:`".
2154 match self.expected_one_of_not_found(&[], &[]) {
2156 self.bump(); // Skip the `:`.
2157 match self.parse_pat_no_top_alt(expected) {
2159 // Carry on as if we had not done anything, callers will emit a
2160 // reasonable error.
2166 // We've parsed the rest of the pattern.
2167 let new_span = first_pat.span.to(pat.span);
2168 let mut show_sugg = false;
2169 // Try to construct a recovered pattern.
2170 match &mut pat.kind {
2171 PatKind::Struct(qself @ None, path, ..)
2172 | PatKind::TupleStruct(qself @ None, path, _)
2173 | PatKind::Path(qself @ None, path) => match &first_pat.kind {
2174 PatKind::Ident(_, ident, _) => {
2175 path.segments.insert(0, PathSegment::from_ident(*ident));
2176 path.span = new_span;
2180 PatKind::Path(old_qself, old_path) => {
2181 path.segments = old_path
2185 .chain(take(&mut path.segments))
2187 path.span = new_span;
2188 *qself = old_qself.clone();
2194 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
2195 match &first_pat.kind {
2196 PatKind::Ident(_, old_ident, _) => {
2197 let path = PatKind::Path(
2202 PathSegment::from_ident(*old_ident),
2203 PathSegment::from_ident(*ident),
2208 first_pat = self.mk_pat(new_span, path);
2211 PatKind::Path(old_qself, old_path) => {
2212 let mut segments = old_path.segments.clone();
2213 segments.push(PathSegment::from_ident(*ident));
2214 let path = PatKind::Path(
2216 Path { span: new_span, segments, tokens: None },
2218 first_pat = self.mk_pat(new_span, path);
2227 err.span_suggestion(
2229 "maybe write a path separator here",
2231 Applicability::MaybeIncorrect,
2234 first_pat = self.mk_pat(new_span, PatKind::Wild);
2241 // Carry on as if we had not done anything. This should be unreachable.
2248 crate fn maybe_recover_unexpected_block_label(&mut self) -> bool {
2249 let Some(label) = self.eat_label().filter(|_| {
2250 self.eat(&token::Colon) && self.token.kind == token::OpenDelim(token::Brace)
2254 let span = label.ident.span.to(self.prev_token.span);
2255 let mut err = self.struct_span_err(span, "block label not supported here");
2256 err.span_label(span, "not supported here");
2257 err.tool_only_span_suggestion(
2258 label.ident.span.until(self.token.span),
2259 "remove this block label",
2261 Applicability::MachineApplicable,
2267 /// Some special error handling for the "top-level" patterns in a match arm,
2268 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2269 crate fn maybe_recover_unexpected_comma(
2273 rt: CommaRecoveryMode,
2274 ) -> PResult<'a, ()> {
2275 if rc == RecoverComma::No || self.token != token::Comma {
2279 // An unexpected comma after a top-level pattern is a clue that the
2280 // user (perhaps more accustomed to some other language) forgot the
2281 // parentheses in what should have been a tuple pattern; return a
2282 // suggestion-enhanced error here rather than choking on the comma later.
2283 let comma_span = self.token.span;
2285 if let Err(err) = self.skip_pat_list() {
2286 // We didn't expect this to work anyway; we just wanted to advance to the
2287 // end of the comma-sequence so we know the span to suggest parenthesizing.
2290 let seq_span = lo.to(self.prev_token.span);
2291 let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
2292 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
2293 err.multipart_suggestion(
2295 "try adding parentheses to match on a tuple{}",
2296 if let CommaRecoveryMode::LikelyTuple = rt { "" } else { "..." },
2299 (seq_span.shrink_to_lo(), "(".to_string()),
2300 (seq_span.shrink_to_hi(), ")".to_string()),
2302 Applicability::MachineApplicable,
2304 if let CommaRecoveryMode::EitherTupleOrPipe = rt {
2305 err.span_suggestion(
2307 "...or a vertical bar to match on multiple alternatives",
2308 seq_snippet.replace(',', " |"),
2309 Applicability::MachineApplicable,
2316 /// Parse and throw away a parenthesized comma separated
2317 /// sequence of patterns until `)` is reached.
2318 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
2319 while !self.check(&token::CloseDelim(token::Paren)) {
2320 self.parse_pat_no_top_alt(None)?;
2321 if !self.eat(&token::Comma) {