1 use super::ty::AllowPlus;
3 use super::{BlockMode, Parser, PathStyle, Restrictions, SemiColonMode, SeqSep, TokenExpectType};
7 use rustc_ast::token::{self, Lit, LitKind, TokenKind};
8 use rustc_ast::util::parser::AssocOp;
9 use rustc_ast::{AngleBracketedArg, AngleBracketedArgs, AnonConst, AttrVec};
10 use rustc_ast::{BinOpKind, BindingMode, Block, BlockCheckMode, Expr, ExprKind, GenericArg, Item};
11 use rustc_ast::{ItemKind, Mutability, Param, Pat, PatKind, Path, PathSegment, QSelf, Ty, TyKind};
12 use rustc_ast_pretty::pprust;
13 use rustc_data_structures::fx::FxHashSet;
14 use rustc_errors::{pluralize, struct_span_err};
15 use rustc_errors::{Applicability, DiagnosticBuilder, Handler, PResult};
16 use rustc_span::source_map::Spanned;
17 use rustc_span::symbol::{kw, Ident};
18 use rustc_span::{MultiSpan, Span, SpanSnippetError, DUMMY_SP};
20 use tracing::{debug, trace};
22 const TURBOFISH_SUGGESTION_STR: &str =
23 "use `::<...>` instead of `<...>` to specify type or const arguments";
25 /// Creates a placeholder argument.
26 pub(super) fn dummy_arg(ident: Ident) -> Param {
28 id: ast::DUMMY_NODE_ID,
29 kind: PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None),
33 let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID, tokens: None };
35 attrs: AttrVec::default(),
36 id: ast::DUMMY_NODE_ID,
40 is_placeholder: false,
49 fn span_err(self, sp: impl Into<MultiSpan>, handler: &Handler) -> DiagnosticBuilder<'_> {
51 Error::UselessDocComment => {
52 let mut err = struct_span_err!(
56 "found a documentation comment that doesn't document anything",
59 "doc comments must come before what they document, maybe a comment was \
68 pub(super) trait RecoverQPath: Sized + 'static {
69 const PATH_STYLE: PathStyle = PathStyle::Expr;
70 fn to_ty(&self) -> Option<P<Ty>>;
71 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
74 impl RecoverQPath for Ty {
75 const PATH_STYLE: PathStyle = PathStyle::Type;
76 fn to_ty(&self) -> Option<P<Ty>> {
79 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
82 kind: TyKind::Path(qself, path),
83 id: ast::DUMMY_NODE_ID,
89 impl RecoverQPath for Pat {
90 fn to_ty(&self) -> Option<P<Ty>> {
93 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
96 kind: PatKind::Path(qself, path),
97 id: ast::DUMMY_NODE_ID,
103 impl RecoverQPath for Expr {
104 fn to_ty(&self) -> Option<P<Ty>> {
107 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
110 kind: ExprKind::Path(qself, path),
111 attrs: AttrVec::new(),
112 id: ast::DUMMY_NODE_ID,
118 /// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
119 crate enum ConsumeClosingDelim {
124 #[derive(Clone, Copy)]
125 pub enum AttemptLocalParseRecovery {
130 impl AttemptLocalParseRecovery {
131 pub fn yes(&self) -> bool {
133 AttemptLocalParseRecovery::Yes => true,
134 AttemptLocalParseRecovery::No => false,
138 pub fn no(&self) -> bool {
140 AttemptLocalParseRecovery::Yes => false,
141 AttemptLocalParseRecovery::No => true,
146 impl<'a> Parser<'a> {
147 pub(super) fn span_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
148 err.span_err(sp, self.diagnostic())
151 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
152 self.sess.span_diagnostic.struct_span_err(sp, m)
155 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
156 self.sess.span_diagnostic.span_bug(sp, m)
159 pub(super) fn diagnostic(&self) -> &'a Handler {
160 &self.sess.span_diagnostic
163 pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
164 self.sess.source_map().span_to_snippet(span)
167 pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
168 let mut err = self.struct_span_err(
170 &format!("expected identifier, found {}", super::token_descr(&self.token)),
172 let valid_follow = &[
178 TokenKind::OpenDelim(token::DelimToken::Brace),
179 TokenKind::OpenDelim(token::DelimToken::Paren),
180 TokenKind::CloseDelim(token::DelimToken::Brace),
181 TokenKind::CloseDelim(token::DelimToken::Paren),
183 match self.token.ident() {
185 if ident.is_raw_guess()
186 && self.look_ahead(1, |t| valid_follow.contains(&t.kind)) =>
190 "you can escape reserved keywords to use them as identifiers",
191 format!("r#{}", ident.name),
192 Applicability::MaybeIncorrect,
197 if let Some(token_descr) = super::token_descr_opt(&self.token) {
198 err.span_label(self.token.span, format!("expected identifier, found {}", token_descr));
200 err.span_label(self.token.span, "expected identifier");
201 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
206 Applicability::MachineApplicable,
213 pub(super) fn expected_one_of_not_found(
215 edible: &[TokenKind],
216 inedible: &[TokenKind],
217 ) -> PResult<'a, bool /* recovered */> {
218 debug!("expected_one_of_not_found(edible: {:?}, inedible: {:?})", edible, inedible);
219 fn tokens_to_string(tokens: &[TokenType]) -> String {
220 let mut i = tokens.iter();
221 // This might be a sign we need a connect method on `Iterator`.
222 let b = i.next().map_or_else(String::new, |t| t.to_string());
223 i.enumerate().fold(b, |mut b, (i, a)| {
224 if tokens.len() > 2 && i == tokens.len() - 2 {
226 } else if tokens.len() == 2 && i == tokens.len() - 2 {
231 b.push_str(&a.to_string());
236 let mut expected = edible
238 .map(|x| TokenType::Token(x.clone()))
239 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
240 .chain(self.expected_tokens.iter().cloned())
241 .collect::<Vec<_>>();
242 expected.sort_by_cached_key(|x| x.to_string());
245 let sm = self.sess.source_map();
246 let msg = format!("expected `;`, found {}", super::token_descr(&self.token));
247 let appl = Applicability::MachineApplicable;
248 if expected.contains(&TokenType::Token(token::Semi)) {
249 if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
250 // Likely inside a macro, can't provide meaningful suggestions.
251 } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
252 // The current token is in the same line as the prior token, not recoverable.
253 } else if [token::Comma, token::Colon].contains(&self.token.kind)
254 && self.prev_token.kind == token::CloseDelim(token::Paren)
256 // Likely typo: The current token is on a new line and is expected to be
257 // `.`, `;`, `?`, or an operator after a close delimiter token.
259 // let a = std::process::Command::new("echo")
263 // https://github.com/rust-lang/rust/issues/72253
264 } else if self.look_ahead(1, |t| {
265 t == &token::CloseDelim(token::Brace)
266 || t.can_begin_expr() && t.kind != token::Colon
267 }) && [token::Comma, token::Colon].contains(&self.token.kind)
269 // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is
270 // either `,` or `:`, and the next token could either start a new statement or is a
271 // block close. For example:
276 let sp = self.prev_token.span;
277 self.struct_span_err(sp, &msg)
278 .span_suggestion_short(sp, "change this to `;`", ";".to_string(), appl)
281 } else if self.look_ahead(0, |t| {
282 t == &token::CloseDelim(token::Brace)
284 t.can_begin_expr() && t != &token::Semi && t != &token::Pound
285 // Avoid triggering with too many trailing `#` in raw string.
288 // Missing semicolon typo. This is triggered if the next token could either start a
289 // new statement or is a block close. For example:
293 let sp = self.prev_token.span.shrink_to_hi();
294 self.struct_span_err(sp, &msg)
295 .span_label(self.token.span, "unexpected token")
296 .span_suggestion_short(sp, "add `;` here", ";".to_string(), appl)
302 let expect = tokens_to_string(&expected[..]);
303 let actual = super::token_descr(&self.token);
304 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
305 let short_expect = if expected.len() > 6 {
306 format!("{} possible tokens", expected.len())
311 format!("expected one of {}, found {}", expect, actual),
312 (self.prev_token.span.shrink_to_hi(), format!("expected one of {}", short_expect)),
314 } else if expected.is_empty() {
316 format!("unexpected token: {}", actual),
317 (self.prev_token.span, "unexpected token after this".to_string()),
321 format!("expected {}, found {}", expect, actual),
322 (self.prev_token.span.shrink_to_hi(), format!("expected {}", expect)),
325 self.last_unexpected_token_span = Some(self.token.span);
326 let mut err = self.struct_span_err(self.token.span, &msg_exp);
328 // Add suggestion for a missing closing angle bracket if '>' is included in expected_tokens
329 // there are unclosed angle brackets
330 if self.unmatched_angle_bracket_count > 0
331 && self.token.kind == TokenKind::Eq
332 && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Gt)))
334 err.span_label(self.prev_token.span, "maybe try to close unmatched angle bracket");
337 let sp = if self.token == token::Eof {
338 // This is EOF; don't want to point at the following char, but rather the last token.
343 match self.recover_closing_delimiter(
346 .filter_map(|tt| match tt {
347 TokenType::Token(t) => Some(t.clone()),
350 .collect::<Vec<_>>(),
355 return Ok(recovered);
359 if self.check_too_many_raw_str_terminators(&mut err) {
363 if self.prev_token.span == DUMMY_SP {
364 // Account for macro context where the previous span might not be
365 // available to avoid incorrect output (#54841).
366 err.span_label(self.token.span, label_exp);
367 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
368 // When the spans are in the same line, it means that the only content between
369 // them is whitespace, point at the found token in that case:
371 // X | () => { syntax error };
372 // | ^^^^^ expected one of 8 possible tokens here
374 // instead of having:
376 // X | () => { syntax error };
377 // | -^^^^^ unexpected token
379 // | expected one of 8 possible tokens here
380 err.span_label(self.token.span, label_exp);
382 err.span_label(sp, label_exp);
383 err.span_label(self.token.span, "unexpected token");
385 self.maybe_annotate_with_ascription(&mut err, false);
389 fn check_too_many_raw_str_terminators(&mut self, err: &mut DiagnosticBuilder<'_>) -> bool {
390 match (&self.prev_token.kind, &self.token.kind) {
392 TokenKind::Literal(Lit {
393 kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
398 err.set_primary_message("too many `#` when terminating raw string");
401 "remove the extra `#`",
403 Applicability::MachineApplicable,
405 err.note(&format!("the raw string started with {} `#`s", n_hashes));
412 pub fn maybe_suggest_struct_literal(
416 ) -> Option<PResult<'a, P<Block>>> {
417 if self.token.is_ident() && self.look_ahead(1, |t| t == &token::Colon) {
418 // We might be having a struct literal where people forgot to include the path:
422 let mut snapshot = self.clone();
424 Path { segments: vec![], span: self.prev_token.span.shrink_to_lo(), tokens: None };
425 let struct_expr = snapshot.parse_struct_expr(None, path, AttrVec::new(), false);
426 let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No);
427 return Some(match (struct_expr, block_tail) {
428 (Ok(expr), Err(mut err)) => {
429 // We have encountered the following:
434 // fn foo() -> Foo { Path {
438 self.struct_span_err(expr.span, "struct literal body without path")
439 .multipart_suggestion(
440 "you might have forgotten to add the struct literal inside the block",
442 (expr.span.shrink_to_lo(), "{ SomeStruct ".to_string()),
443 (expr.span.shrink_to_hi(), " }".to_string()),
445 Applicability::MaybeIncorrect,
449 let mut tail = self.mk_block(
450 vec![self.mk_stmt_err(expr.span)],
452 lo.to(self.prev_token.span),
454 tail.could_be_bare_literal = true;
457 (Err(mut err), Ok(tail)) => {
458 // We have a block tail that contains a somehow valid type ascription expr.
462 (Err(mut snapshot_err), Err(err)) => {
463 // We don't know what went wrong, emit the normal error.
464 snapshot_err.cancel();
465 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
468 (Ok(_), Ok(mut tail)) => {
469 tail.could_be_bare_literal = true;
477 pub fn maybe_annotate_with_ascription(
479 err: &mut DiagnosticBuilder<'_>,
480 maybe_expected_semicolon: bool,
482 if let Some((sp, likely_path)) = self.last_type_ascription.take() {
483 let sm = self.sess.source_map();
484 let next_pos = sm.lookup_char_pos(self.token.span.lo());
485 let op_pos = sm.lookup_char_pos(sp.hi());
487 let allow_unstable = self.sess.unstable_features.is_nightly_build();
492 "maybe write a path separator here",
495 Applicability::MaybeIncorrect
497 Applicability::MachineApplicable
500 self.sess.type_ascription_path_suggestions.borrow_mut().insert(sp);
501 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
504 "try using a semicolon",
506 Applicability::MaybeIncorrect,
508 } else if allow_unstable {
509 err.span_label(sp, "tried to parse a type due to this type ascription");
511 err.span_label(sp, "tried to parse a type due to this");
514 // Give extra information about type ascription only if it's a nightly compiler.
516 "`#![feature(type_ascription)]` lets you annotate an expression with a type: \
520 // Avoid giving too much info when it was likely an unrelated typo.
522 "see issue #23416 <https://github.com/rust-lang/rust/issues/23416> \
523 for more information",
530 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
531 /// passes through any errors encountered. Used for error recovery.
532 pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
533 if let Err(ref mut err) =
534 self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
535 Ok(p.parse_token_tree())
542 /// This function checks if there are trailing angle brackets and produces
543 /// a diagnostic to suggest removing them.
545 /// ```ignore (diagnostic)
546 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
547 /// ^^ help: remove extra angle brackets
550 /// If `true` is returned, then trailing brackets were recovered, tokens were consumed
551 /// up until one of the tokens in 'end' was encountered, and an error was emitted.
552 pub(super) fn check_trailing_angle_brackets(
554 segment: &PathSegment,
557 // This function is intended to be invoked after parsing a path segment where there are two
560 // 1. A specific token is expected after the path segment.
561 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
562 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
563 // 2. No specific token is expected after the path segment.
564 // eg. `x.foo` (field access)
566 // This function is called after parsing `.foo` and before parsing the token `end` (if
567 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
570 // We only care about trailing angle brackets if we previously parsed angle bracket
571 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
572 // removed in this case:
574 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
576 // This case is particularly tricky as we won't notice it just looking at the tokens -
577 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
578 // have already been parsed):
580 // `x.foo::<u32>>>(3)`
581 let parsed_angle_bracket_args =
582 segment.args.as_ref().map_or(false, |args| args.is_angle_bracketed());
585 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
586 parsed_angle_bracket_args,
588 if !parsed_angle_bracket_args {
592 // Keep the span at the start so we can highlight the sequence of `>` characters to be
594 let lo = self.token.span;
596 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
597 // (since we might have the field access case and the characters we're eating are
598 // actual operators and not trailing characters - ie `x.foo >> 3`).
599 let mut position = 0;
601 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
602 // many of each (so we can correctly pluralize our error messages) and continue to
604 let mut number_of_shr = 0;
605 let mut number_of_gt = 0;
606 while self.look_ahead(position, |t| {
607 trace!("check_trailing_angle_brackets: t={:?}", t);
608 if *t == token::BinOp(token::BinOpToken::Shr) {
611 } else if *t == token::Gt {
621 // If we didn't find any trailing `>` characters, then we have nothing to error about.
623 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
624 number_of_gt, number_of_shr,
626 if number_of_gt < 1 && number_of_shr < 1 {
630 // Finally, double check that we have our end token as otherwise this is the
632 if self.look_ahead(position, |t| {
633 trace!("check_trailing_angle_brackets: t={:?}", t);
634 end.contains(&&t.kind)
636 // Eat from where we started until the end token so that parsing can continue
637 // as if we didn't have those extra angle brackets.
638 self.eat_to_tokens(end);
639 let span = lo.until(self.token.span);
641 let total_num_of_gt = number_of_gt + number_of_shr * 2;
642 self.struct_span_err(
644 &format!("unmatched angle bracket{}", pluralize!(total_num_of_gt)),
648 &format!("remove extra angle bracket{}", pluralize!(total_num_of_gt)),
650 Applicability::MachineApplicable,
658 /// Check if a method call with an intended turbofish has been written without surrounding
660 pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
661 if token::ModSep == self.token.kind && segment.args.is_none() {
662 let snapshot = self.clone();
664 let lo = self.token.span;
665 match self.parse_angle_args() {
667 let span = lo.to(self.prev_token.span);
668 // Detect trailing `>` like in `x.collect::Vec<_>>()`.
669 let mut trailing_span = self.prev_token.span.shrink_to_hi();
670 while self.token.kind == token::BinOp(token::Shr)
671 || self.token.kind == token::Gt
673 trailing_span = trailing_span.to(self.token.span);
676 if self.token.kind == token::OpenDelim(token::Paren) {
677 // Recover from bad turbofish: `foo.collect::Vec<_>()`.
678 let args = AngleBracketedArgs { args, span }.into();
681 self.struct_span_err(
683 "generic parameters without surrounding angle brackets",
685 .multipart_suggestion(
686 "surround the type parameters with angle brackets",
688 (span.shrink_to_lo(), "<".to_string()),
689 (trailing_span, ">".to_string()),
691 Applicability::MachineApplicable,
695 // This doesn't look like an invalid turbofish, can't recover parse state.
700 // We couldn't parse generic parameters, unlikely to be a turbofish. Rely on
701 // generic parse error instead.
709 /// When writing a turbofish with multiple type parameters missing the leading `::`, we will
710 /// encounter a parse error when encountering the first `,`.
711 pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
713 mut e: DiagnosticBuilder<'a>,
715 ) -> PResult<'a, ()> {
716 if let ExprKind::Binary(binop, _, _) = &expr.kind {
717 if let ast::BinOpKind::Lt = binop.node {
718 if self.eat(&token::Comma) {
719 let x = self.parse_seq_to_before_end(
721 SeqSep::trailing_allowed(token::Comma),
722 |p| p.parse_generic_arg(),
725 Ok((_, _, false)) => {
726 if self.eat(&token::Gt) {
727 match self.parse_expr() {
729 e.span_suggestion_verbose(
730 binop.span.shrink_to_lo(),
731 TURBOFISH_SUGGESTION_STR,
733 Applicability::MaybeIncorrect,
737 self.mk_expr_err(expr.span.to(self.prev_token.span));
757 /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
758 /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
759 /// parenthesising the leftmost comparison.
760 fn attempt_chained_comparison_suggestion(
762 err: &mut DiagnosticBuilder<'_>,
764 outer_op: &Spanned<AssocOp>,
765 ) -> bool /* advanced the cursor */ {
766 if let ExprKind::Binary(op, ref l1, ref r1) = inner_op.kind {
767 if let ExprKind::Field(_, ident) = l1.kind {
768 if ident.as_str().parse::<i32>().is_err() && !matches!(r1.kind, ExprKind::Lit(_)) {
769 // The parser has encountered `foo.bar<baz`, the likelihood of the turbofish
770 // suggestion being the only one to apply is high.
774 let mut enclose = |left: Span, right: Span| {
775 err.multipart_suggestion(
776 "parenthesize the comparison",
778 (left.shrink_to_lo(), "(".to_string()),
779 (right.shrink_to_hi(), ")".to_string()),
781 Applicability::MaybeIncorrect,
784 return match (op.node, &outer_op.node) {
786 (BinOpKind::Eq, AssocOp::Equal) |
787 // `x < y < z` and friends.
788 (BinOpKind::Lt, AssocOp::Less | AssocOp::LessEqual) |
789 (BinOpKind::Le, AssocOp::LessEqual | AssocOp::Less) |
790 // `x > y > z` and friends.
791 (BinOpKind::Gt, AssocOp::Greater | AssocOp::GreaterEqual) |
792 (BinOpKind::Ge, AssocOp::GreaterEqual | AssocOp::Greater) => {
793 let expr_to_str = |e: &Expr| {
794 self.span_to_snippet(e.span)
795 .unwrap_or_else(|_| pprust::expr_to_string(&e))
797 err.span_suggestion_verbose(
798 inner_op.span.shrink_to_hi(),
799 "split the comparison into two",
800 format!(" && {}", expr_to_str(&r1)),
801 Applicability::MaybeIncorrect,
803 false // Keep the current parse behavior, where the AST is `(x < y) < z`.
806 (BinOpKind::Eq, AssocOp::Less | AssocOp::LessEqual | AssocOp::Greater | AssocOp::GreaterEqual) => {
807 // Consume `z`/outer-op-rhs.
808 let snapshot = self.clone();
809 match self.parse_expr() {
811 // We are sure that outer-op-rhs could be consumed, the suggestion is
813 enclose(r1.span, r2.span);
816 Err(mut expr_err) => {
824 (BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge, AssocOp::Equal) => {
825 let snapshot = self.clone();
826 // At this point it is always valid to enclose the lhs in parentheses, no
827 // further checks are necessary.
828 match self.parse_expr() {
830 enclose(l1.span, r1.span);
833 Err(mut expr_err) => {
846 /// Produces an error if comparison operators are chained (RFC #558).
847 /// We only need to check the LHS, not the RHS, because all comparison ops have same
848 /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
850 /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
851 /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
854 /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
855 /// associative we can infer that we have:
864 pub(super) fn check_no_chained_comparison(
867 outer_op: &Spanned<AssocOp>,
868 ) -> PResult<'a, Option<P<Expr>>> {
870 outer_op.node.is_comparison(),
871 "check_no_chained_comparison: {:?} is not comparison",
876 |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err, AttrVec::new())));
878 match inner_op.kind {
879 ExprKind::Binary(op, ref l1, ref r1) if op.node.is_comparison() => {
880 let mut err = self.struct_span_err(
881 vec![op.span, self.prev_token.span],
882 "comparison operators cannot be chained",
885 let suggest = |err: &mut DiagnosticBuilder<'_>| {
886 err.span_suggestion_verbose(
887 op.span.shrink_to_lo(),
888 TURBOFISH_SUGGESTION_STR,
890 Applicability::MaybeIncorrect,
894 // Include `<` to provide this recommendation even in a case like
895 // `Foo<Bar<Baz<Qux, ()>>>`
896 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Less
897 || outer_op.node == AssocOp::Greater
899 if outer_op.node == AssocOp::Less {
900 let snapshot = self.clone();
902 // So far we have parsed `foo<bar<`, consume the rest of the type args.
904 [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
905 self.consume_tts(1, &modifiers[..]);
907 if !&[token::OpenDelim(token::Paren), token::ModSep]
908 .contains(&self.token.kind)
910 // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
911 // parser and bail out.
912 *self = snapshot.clone();
915 return if token::ModSep == self.token.kind {
916 // We have some certainty that this was a bad turbofish at this point.
920 let snapshot = self.clone();
923 // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
924 match self.parse_expr() {
926 // 99% certain that the suggestion is correct, continue parsing.
928 // FIXME: actually check that the two expressions in the binop are
929 // paths and resynthesize new fn call expression instead of using
930 // `ExprKind::Err` placeholder.
931 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
933 Err(mut expr_err) => {
935 // Not entirely sure now, but we bubble the error up with the
941 } else if token::OpenDelim(token::Paren) == self.token.kind {
942 // We have high certainty that this was a bad turbofish at this point.
945 // Consume the fn call arguments.
946 match self.consume_fn_args() {
950 // FIXME: actually check that the two expressions in the binop are
951 // paths and resynthesize new fn call expression instead of using
952 // `ExprKind::Err` placeholder.
953 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
957 if !matches!(l1.kind, ExprKind::Lit(_))
958 && !matches!(r1.kind, ExprKind::Lit(_))
960 // All we know is that this is `foo < bar >` and *nothing* else. Try to
961 // be helpful, but don't attempt to recover.
962 err.help(TURBOFISH_SUGGESTION_STR);
963 err.help("or use `(...)` if you meant to specify fn arguments");
966 // If it looks like a genuine attempt to chain operators (as opposed to a
967 // misformatted turbofish, for instance), suggest a correct form.
968 if self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op)
971 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
973 // These cases cause too many knock-down errors, bail out (#61329).
979 self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
982 return mk_err_expr(self, inner_op.span.to(self.prev_token.span));
990 fn consume_fn_args(&mut self) -> Result<(), ()> {
991 let snapshot = self.clone();
994 // Consume the fn call arguments.
996 [(token::OpenDelim(token::Paren), 1), (token::CloseDelim(token::Paren), -1)];
997 self.consume_tts(1, &modifiers[..]);
999 if self.token.kind == token::Eof {
1000 // Not entirely sure that what we consumed were fn arguments, rollback.
1004 // 99% certain that the suggestion is correct, continue parsing.
1009 pub(super) fn maybe_report_ambiguous_plus(
1011 allow_plus: AllowPlus,
1012 impl_dyn_multi: bool,
1015 if matches!(allow_plus, AllowPlus::No) && impl_dyn_multi {
1016 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1017 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1020 "use parentheses to disambiguate",
1022 Applicability::MachineApplicable,
1028 pub(super) fn maybe_recover_from_bad_type_plus(
1030 allow_plus: AllowPlus,
1032 ) -> PResult<'a, ()> {
1033 // Do not add `+` to expected tokens.
1034 if matches!(allow_plus, AllowPlus::No) || !self.token.is_like_plus() {
1039 let bounds = self.parse_generic_bounds(None)?;
1040 let sum_span = ty.span.to(self.prev_token.span);
1042 let mut err = struct_span_err!(
1043 self.sess.span_diagnostic,
1046 "expected a path on the left-hand side of `+`, not `{}`",
1047 pprust::ty_to_string(ty)
1051 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1052 let sum_with_parens = pprust::to_string(|s| {
1054 s.print_opt_lifetime(lifetime);
1055 s.print_mutability(mut_ty.mutbl, false);
1057 s.print_type(&mut_ty.ty);
1058 s.print_type_bounds(" +", &bounds);
1061 err.span_suggestion(
1063 "try adding parentheses",
1065 Applicability::MachineApplicable,
1068 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1069 err.span_label(sum_span, "perhaps you forgot parentheses?");
1072 err.span_label(sum_span, "expected a path");
1079 /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
1080 /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
1081 /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
1082 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
1085 allow_recovery: bool,
1086 ) -> PResult<'a, P<T>> {
1087 // Do not add `::` to expected tokens.
1088 if allow_recovery && self.token == token::ModSep {
1089 if let Some(ty) = base.to_ty() {
1090 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1096 /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
1097 /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
1098 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
1102 ) -> PResult<'a, P<T>> {
1103 self.expect(&token::ModSep)?;
1105 let mut path = ast::Path { segments: Vec::new(), span: DUMMY_SP, tokens: None };
1106 self.parse_path_segments(&mut path.segments, T::PATH_STYLE)?;
1107 path.span = ty_span.to(self.prev_token.span);
1109 let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
1110 self.struct_span_err(path.span, "missing angle brackets in associated item path")
1112 // This is a best-effort recovery.
1115 format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
1116 Applicability::MaybeIncorrect,
1120 let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
1121 Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path)))
1124 pub(super) fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
1125 if self.eat(&token::Semi) {
1126 let mut err = self.struct_span_err(self.prev_token.span, "expected item, found `;`");
1127 err.span_suggestion_short(
1128 self.prev_token.span,
1129 "remove this semicolon",
1131 Applicability::MachineApplicable,
1133 if !items.is_empty() {
1134 let previous_item = &items[items.len() - 1];
1135 let previous_item_kind_name = match previous_item.kind {
1136 // Say "braced struct" because tuple-structs and
1137 // braceless-empty-struct declarations do take a semicolon.
1138 ItemKind::Struct(..) => Some("braced struct"),
1139 ItemKind::Enum(..) => Some("enum"),
1140 ItemKind::Trait(..) => Some("trait"),
1141 ItemKind::Union(..) => Some("union"),
1144 if let Some(name) = previous_item_kind_name {
1145 err.help(&format!("{} declarations are not followed by a semicolon", name));
1155 /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
1156 /// closing delimiter.
1157 pub(super) fn unexpected_try_recover(
1160 ) -> PResult<'a, bool /* recovered */> {
1161 let token_str = pprust::token_kind_to_string(t);
1162 let this_token_str = super::token_descr(&self.token);
1163 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1164 // Point at the end of the macro call when reaching end of macro arguments.
1165 (token::Eof, Some(_)) => {
1166 let sp = self.sess.source_map().next_point(self.prev_token.span);
1169 // We don't want to point at the following span after DUMMY_SP.
1170 // This happens when the parser finds an empty TokenStream.
1171 _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
1172 // EOF, don't want to point at the following char, but rather the last token.
1173 (token::Eof, None) => (self.prev_token.span, self.token.span),
1174 _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
1177 "expected `{}`, found {}",
1179 match (&self.token.kind, self.subparser_name) {
1180 (token::Eof, Some(origin)) => format!("end of {}", origin),
1181 _ => this_token_str,
1184 let mut err = self.struct_span_err(sp, &msg);
1185 let label_exp = format!("expected `{}`", token_str);
1186 match self.recover_closing_delimiter(&[t.clone()], err) {
1189 return Ok(recovered);
1192 let sm = self.sess.source_map();
1193 if !sm.is_multiline(prev_sp.until(sp)) {
1194 // When the spans are in the same line, it means that the only content
1195 // between them is whitespace, point only at the found token.
1196 err.span_label(sp, label_exp);
1198 err.span_label(prev_sp, label_exp);
1199 err.span_label(sp, "unexpected token");
1204 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1205 if self.eat(&token::Semi) {
1208 self.expect(&token::Semi).map(drop) // Error unconditionally
1211 /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
1212 /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
1213 pub(super) fn recover_incorrect_await_syntax(
1218 ) -> PResult<'a, P<Expr>> {
1219 let (hi, expr, is_question) = if self.token == token::Not {
1220 // Handle `await!(<expr>)`.
1221 self.recover_await_macro()?
1223 self.recover_await_prefix(await_sp)?
1225 let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
1226 let kind = match expr.kind {
1227 // Avoid knock-down errors as we don't know whether to interpret this as `foo().await?`
1228 // or `foo()?.await` (the very reason we went with postfix syntax 😅).
1229 ExprKind::Try(_) => ExprKind::Err,
1230 _ => ExprKind::Await(expr),
1232 let expr = self.mk_expr(lo.to(sp), kind, attrs);
1233 self.maybe_recover_from_bad_qpath(expr, true)
1236 fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1237 self.expect(&token::Not)?;
1238 self.expect(&token::OpenDelim(token::Paren))?;
1239 let expr = self.parse_expr()?;
1240 self.expect(&token::CloseDelim(token::Paren))?;
1241 Ok((self.prev_token.span, expr, false))
1244 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
1245 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
1246 let expr = if self.token == token::OpenDelim(token::Brace) {
1247 // Handle `await { <expr> }`.
1248 // This needs to be handled separately from the next arm to avoid
1249 // interpreting `await { <expr> }?` as `<expr>?.await`.
1250 self.parse_block_expr(None, self.token.span, BlockCheckMode::Default, AttrVec::new())
1254 .map_err(|mut err| {
1255 err.span_label(await_sp, "while parsing this incorrect await expression");
1258 Ok((expr.span, expr, is_question))
1261 fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
1263 self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr));
1264 let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" });
1266 let app = match expr.kind {
1267 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
1268 _ => Applicability::MachineApplicable,
1270 self.struct_span_err(sp, "incorrect use of `await`")
1271 .span_suggestion(sp, "`await` is a postfix operation", suggestion, app)
1276 /// If encountering `future.await()`, consumes and emits an error.
1277 pub(super) fn recover_from_await_method_call(&mut self) {
1278 if self.token == token::OpenDelim(token::Paren)
1279 && self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren))
1282 let lo = self.token.span;
1284 let sp = lo.to(self.token.span);
1286 self.struct_span_err(sp, "incorrect use of `await`")
1289 "`await` is not a method call, remove the parentheses",
1291 Applicability::MachineApplicable,
1297 pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, P<Expr>> {
1298 let is_try = self.token.is_keyword(kw::Try);
1299 let is_questionmark = self.look_ahead(1, |t| t == &token::Not); //check for !
1300 let is_open = self.look_ahead(2, |t| t == &token::OpenDelim(token::Paren)); //check for (
1302 if is_try && is_questionmark && is_open {
1303 let lo = self.token.span;
1304 self.bump(); //remove try
1305 self.bump(); //remove !
1306 let try_span = lo.to(self.token.span); //we take the try!( span
1307 self.bump(); //remove (
1308 let is_empty = self.token == token::CloseDelim(token::Paren); //check if the block is empty
1309 self.consume_block(token::Paren, ConsumeClosingDelim::No); //eat the block
1310 let hi = self.token.span;
1311 self.bump(); //remove )
1312 let mut err = self.struct_span_err(lo.to(hi), "use of deprecated `try` macro");
1313 err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
1314 let prefix = if is_empty { "" } else { "alternatively, " };
1316 err.multipart_suggestion(
1317 "you can use the `?` operator instead",
1318 vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
1319 Applicability::MachineApplicable,
1322 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);
1324 Ok(self.mk_expr_err(lo.to(hi)))
1326 Err(self.expected_expression_found()) // The user isn't trying to invoke the try! macro
1330 /// Recovers a situation like `for ( $pat in $expr )`
1331 /// and suggest writing `for $pat in $expr` instead.
1333 /// This should be called before parsing the `$block`.
1334 pub(super) fn recover_parens_around_for_head(
1338 begin_paren: Option<Span>,
1340 match (&self.token.kind, begin_paren) {
1341 (token::CloseDelim(token::Paren), Some(begin_par_sp)) => {
1345 // Remove the `(` from the span of the pattern:
1346 .span_to_snippet(pat.span.trim_start(begin_par_sp).unwrap())
1347 .unwrap_or_else(|_| pprust::pat_to_string(&pat));
1349 self.struct_span_err(self.prev_token.span, "unexpected closing `)`")
1350 .span_label(begin_par_sp, "opening `(`")
1352 begin_par_sp.to(self.prev_token.span),
1353 "remove parenthesis in `for` loop",
1354 format!("{} in {}", pat_str, pprust::expr_to_string(&expr)),
1355 // With e.g. `for (x) in y)` this would replace `(x) in y)`
1356 // with `x) in y)` which is syntactically invalid.
1357 // However, this is prevented before we get here.
1358 Applicability::MachineApplicable,
1362 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1363 pat.and_then(|pat| match pat.kind {
1364 PatKind::Paren(pat) => pat,
1372 pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1373 (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1374 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1375 || self.token.is_ident() &&
1376 matches!(node, ast::ExprKind::Path(..) | ast::ExprKind::Field(..)) &&
1377 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
1378 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren))
1379 || self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) // `foo:bar {`
1380 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar::<baz`
1381 self.look_ahead(2, |t| t == &token::Lt) &&
1382 self.look_ahead(3, |t| t.is_ident())
1383 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
1384 self.look_ahead(2, |t| t.is_ident())
1385 || self.look_ahead(1, |t| t == &token::ModSep)
1386 && (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
1387 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1390 pub(super) fn recover_seq_parse_error(
1392 delim: token::DelimToken,
1394 result: PResult<'a, P<Expr>>,
1400 // Recover from parse error, callers expect the closing delim to be consumed.
1401 self.consume_block(delim, ConsumeClosingDelim::Yes);
1402 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err, AttrVec::new())
1407 pub(super) fn recover_closing_delimiter(
1409 tokens: &[TokenKind],
1410 mut err: DiagnosticBuilder<'a>,
1411 ) -> PResult<'a, bool> {
1413 // We want to use the last closing delim that would apply.
1414 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1415 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1416 && Some(self.token.span) > unmatched.unclosed_span
1423 // Recover and assume that the detected unclosed delimiter was meant for
1424 // this location. Emit the diagnostic and act as if the delimiter was
1425 // present for the parser's sake.
1427 // Don't attempt to recover from this unclosed delimiter more than once.
1428 let unmatched = self.unclosed_delims.remove(pos);
1429 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1430 if unmatched.found_delim.is_none() {
1431 // We encountered `Eof`, set this fact here to avoid complaining about missing
1432 // `fn main()` when we found place to suggest the closing brace.
1433 *self.sess.reached_eof.borrow_mut() = true;
1436 // We want to suggest the inclusion of the closing delimiter where it makes
1437 // the most sense, which is immediately after the last token:
1442 // | help: `)` may belong here
1444 // unclosed delimiter
1445 if let Some(sp) = unmatched.unclosed_span {
1446 let mut primary_span: Vec<Span> =
1447 err.span.primary_spans().iter().cloned().collect();
1448 primary_span.push(sp);
1449 let mut primary_span: MultiSpan = primary_span.into();
1450 for span_label in err.span.span_labels() {
1451 if let Some(label) = span_label.label {
1452 primary_span.push_span_label(span_label.span, label);
1455 err.set_span(primary_span);
1456 err.span_label(sp, "unclosed delimiter");
1458 // Backticks should be removed to apply suggestions.
1459 let mut delim = delim.to_string();
1460 delim.retain(|c| c != '`');
1461 err.span_suggestion_short(
1462 self.prev_token.span.shrink_to_hi(),
1463 &format!("`{}` may belong here", delim),
1465 Applicability::MaybeIncorrect,
1467 if unmatched.found_delim.is_none() {
1468 // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1469 // errors which would be emitted elsewhere in the parser and let other error
1470 // recovery consume the rest of the file.
1474 self.expected_tokens.clear(); // Reduce the number of errors.
1482 /// Eats tokens until we can be relatively sure we reached the end of the
1483 /// statement. This is something of a best-effort heuristic.
1485 /// We terminate when we find an unmatched `}` (without consuming it).
1486 pub(super) fn recover_stmt(&mut self) {
1487 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1490 /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1491 /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1492 /// approximate -- it can mean we break too early due to macros, but that
1493 /// should only lead to sub-optimal recovery, not inaccurate parsing).
1495 /// If `break_on_block` is `Break`, then we will stop consuming tokens
1496 /// after finding (and consuming) a brace-delimited block.
1497 pub(super) fn recover_stmt_(
1499 break_on_semi: SemiColonMode,
1500 break_on_block: BlockMode,
1502 let mut brace_depth = 0;
1503 let mut bracket_depth = 0;
1504 let mut in_block = false;
1505 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1507 debug!("recover_stmt_ loop {:?}", self.token);
1508 match self.token.kind {
1509 token::OpenDelim(token::DelimToken::Brace) => {
1512 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1517 token::OpenDelim(token::DelimToken::Bracket) => {
1521 token::CloseDelim(token::DelimToken::Brace) => {
1522 if brace_depth == 0 {
1523 debug!("recover_stmt_ return - close delim {:?}", self.token);
1528 if in_block && bracket_depth == 0 && brace_depth == 0 {
1529 debug!("recover_stmt_ return - block end {:?}", self.token);
1533 token::CloseDelim(token::DelimToken::Bracket) => {
1535 if bracket_depth < 0 {
1541 debug!("recover_stmt_ return - Eof");
1546 if break_on_semi == SemiColonMode::Break
1548 && bracket_depth == 0
1550 debug!("recover_stmt_ return - Semi");
1555 if break_on_semi == SemiColonMode::Comma
1557 && bracket_depth == 0 =>
1559 debug!("recover_stmt_ return - Semi");
1567 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1568 if self.eat_keyword(kw::In) {
1569 // a common typo: `for _ in in bar {}`
1570 self.struct_span_err(self.prev_token.span, "expected iterable, found keyword `in`")
1571 .span_suggestion_short(
1572 in_span.until(self.prev_token.span),
1573 "remove the duplicated `in`",
1575 Applicability::MachineApplicable,
1581 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1582 if let token::DocComment(..) = self.token.kind {
1583 self.struct_span_err(
1585 "documentation comments cannot be applied to a function parameter's type",
1587 .span_label(self.token.span, "doc comments are not allowed here")
1590 } else if self.token == token::Pound
1591 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Bracket))
1593 let lo = self.token.span;
1594 // Skip every token until next possible arg.
1595 while self.token != token::CloseDelim(token::Bracket) {
1598 let sp = lo.to(self.token.span);
1600 self.struct_span_err(sp, "attributes cannot be applied to a function parameter's type")
1601 .span_label(sp, "attributes are not allowed here")
1606 pub(super) fn parameter_without_type(
1608 err: &mut DiagnosticBuilder<'_>,
1612 ) -> Option<Ident> {
1613 // If we find a pattern followed by an identifier, it could be an (incorrect)
1614 // C-style parameter declaration.
1615 if self.check_ident()
1616 && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseDelim(token::Paren))
1618 // `fn foo(String s) {}`
1619 let ident = self.parse_ident().unwrap();
1620 let span = pat.span.with_hi(ident.span.hi());
1622 err.span_suggestion(
1624 "declare the type after the parameter binding",
1625 String::from("<identifier>: <type>"),
1626 Applicability::HasPlaceholders,
1629 } else if require_name
1630 && (self.token == token::Comma
1631 || self.token == token::Lt
1632 || self.token == token::CloseDelim(token::Paren))
1634 let rfc_note = "anonymous parameters are removed in the 2018 edition (see RFC 1685)";
1636 let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
1638 PatKind::Ident(_, ident, _) => (
1640 "self: ".to_string(),
1641 ": TypeName".to_string(),
1643 pat.span.shrink_to_lo(),
1644 pat.span.shrink_to_hi(),
1645 pat.span.shrink_to_lo(),
1647 // Also catches `fn foo(&a)`.
1648 PatKind::Ref(ref inner_pat, mutab)
1649 if matches!(inner_pat.clone().into_inner().kind, PatKind::Ident(..)) =>
1651 match inner_pat.clone().into_inner().kind {
1652 PatKind::Ident(_, ident, _) => {
1653 let mutab = mutab.prefix_str();
1656 "self: ".to_string(),
1657 format!("{}: &{}TypeName", ident, mutab),
1659 pat.span.shrink_to_lo(),
1661 pat.span.shrink_to_lo(),
1664 _ => unreachable!(),
1668 // Otherwise, try to get a type and emit a suggestion.
1669 if let Some(ty) = pat.to_ty() {
1670 err.span_suggestion_verbose(
1672 "explicitly ignore the parameter name",
1673 format!("_: {}", pprust::ty_to_string(&ty)),
1674 Applicability::MachineApplicable,
1683 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1685 err.span_suggestion(
1687 "if this is a `self` type, give it a parameter name",
1689 Applicability::MaybeIncorrect,
1692 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
1693 // `fn foo(HashMap: TypeName<u32>)`.
1694 if self.token != token::Lt {
1695 err.span_suggestion(
1697 "if this is a parameter name, give it a type",
1699 Applicability::HasPlaceholders,
1702 err.span_suggestion(
1704 "if this is a type, explicitly ignore the parameter name",
1706 Applicability::MachineApplicable,
1710 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
1711 return if self.token == token::Lt { None } else { Some(ident) };
1716 pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
1717 let pat = self.parse_pat_no_top_alt(Some("argument name"))?;
1718 self.expect(&token::Colon)?;
1719 let ty = self.parse_ty()?;
1725 "patterns aren't allowed in methods without bodies",
1727 .span_suggestion_short(
1729 "give this argument a name or use an underscore to ignore it",
1731 Applicability::MachineApplicable,
1735 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1737 P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID, tokens: None });
1741 pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
1742 let sp = param.pat.span;
1743 param.ty.kind = TyKind::Err;
1744 self.struct_span_err(sp, "unexpected `self` parameter in function")
1745 .span_label(sp, "must be the first parameter of an associated function")
1750 pub(super) fn consume_block(
1752 delim: token::DelimToken,
1753 consume_close: ConsumeClosingDelim,
1755 let mut brace_depth = 0;
1757 if self.eat(&token::OpenDelim(delim)) {
1759 } else if self.check(&token::CloseDelim(delim)) {
1760 if brace_depth == 0 {
1761 if let ConsumeClosingDelim::Yes = consume_close {
1762 // Some of the callers of this method expect to be able to parse the
1763 // closing delimiter themselves, so we leave it alone. Otherwise we advance
1773 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
1781 pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a> {
1782 let (span, msg) = match (&self.token.kind, self.subparser_name) {
1783 (&token::Eof, Some(origin)) => {
1784 let sp = self.sess.source_map().next_point(self.prev_token.span);
1785 (sp, format!("expected expression, found end of {}", origin))
1789 format!("expected expression, found {}", super::token_descr(&self.token),),
1792 let mut err = self.struct_span_err(span, &msg);
1793 let sp = self.sess.source_map().start_point(self.token.span);
1794 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
1795 self.sess.expr_parentheses_needed(&mut err, *sp);
1797 err.span_label(span, "expected expression");
1803 mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
1804 // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
1805 modifier: &[(token::TokenKind, i64)],
1808 if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
1811 if self.token.kind == token::Eof {
1818 /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
1820 /// This is necessary because at this point we don't know whether we parsed a function with
1821 /// anonymous parameters or a function with names but no types. In order to minimize
1822 /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
1823 /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
1824 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
1825 /// we deduplicate them to not complain about duplicated parameter names.
1826 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
1827 let mut seen_inputs = FxHashSet::default();
1828 for input in fn_inputs.iter_mut() {
1829 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
1830 (&input.pat.kind, &input.ty.kind)
1836 if let Some(ident) = opt_ident {
1837 if seen_inputs.contains(&ident) {
1838 input.pat.kind = PatKind::Wild;
1840 seen_inputs.insert(ident);
1845 /// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
1846 /// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
1847 /// like the user has forgotten them.
1848 pub fn handle_ambiguous_unbraced_const_arg(
1850 args: &mut Vec<AngleBracketedArg>,
1851 ) -> PResult<'a, bool> {
1852 // If we haven't encountered a closing `>`, then the argument is malformed.
1853 // It's likely that the user has written a const expression without enclosing it
1854 // in braces, so we try to recover here.
1855 let arg = args.pop().unwrap();
1856 // FIXME: for some reason using `unexpected` or `expected_one_of_not_found` has
1857 // adverse side-effects to subsequent errors and seems to advance the parser.
1858 // We are causing this error here exclusively in case that a `const` expression
1859 // could be recovered from the current parser state, even if followed by more
1860 // arguments after a comma.
1861 let mut err = self.struct_span_err(
1863 &format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
1865 err.span_label(self.token.span, "expected one of `,` or `>`");
1866 match self.recover_const_arg(arg.span(), err) {
1868 args.push(AngleBracketedArg::Arg(arg));
1869 if self.eat(&token::Comma) {
1870 return Ok(true); // Continue
1875 // We will emit a more generic error later.
1879 return Ok(false); // Don't continue.
1882 /// Attempt to parse a generic const argument that has not been enclosed in braces.
1883 /// There are a limited number of expressions that are permitted without being encoded
1886 /// - Single-segment paths (i.e. standalone generic const parameters).
1887 /// All other expressions that can be parsed will emit an error suggesting the expression be
1888 /// wrapped in braces.
1889 pub fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
1890 let start = self.token.span;
1891 let expr = self.parse_expr_res(Restrictions::CONST_EXPR, None).map_err(|mut err| {
1893 start.shrink_to_lo(),
1894 "while parsing a const generic argument starting here",
1898 if !self.expr_is_valid_const_arg(&expr) {
1899 self.struct_span_err(
1901 "expressions must be enclosed in braces to be used as const generic \
1904 .multipart_suggestion(
1905 "enclose the `const` expression in braces",
1907 (expr.span.shrink_to_lo(), "{ ".to_string()),
1908 (expr.span.shrink_to_hi(), " }".to_string()),
1910 Applicability::MachineApplicable,
1917 /// Try to recover from possible generic const argument without `{` and `}`.
1919 /// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
1920 /// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
1921 /// if we think that that the resulting expression would be well formed.
1922 pub fn recover_const_arg(
1925 mut err: DiagnosticBuilder<'a>,
1926 ) -> PResult<'a, GenericArg> {
1927 let is_op = AssocOp::from_token(&self.token)
1929 if let AssocOp::Greater
1931 | AssocOp::ShiftRight
1932 | AssocOp::GreaterEqual
1933 // Don't recover from `foo::<bar = baz>`, because this could be an attempt to
1934 // assign a value to a defaulted generic parameter.
1936 | AssocOp::AssignOp(_) = op
1944 // This will be true when a trait object type `Foo +` or a path which was a `const fn` with
1945 // type params has been parsed.
1947 matches!(self.prev_token.kind, token::BinOp(token::Plus | token::Shr) | token::Gt);
1948 if !is_op && !was_op {
1949 // We perform these checks and early return to avoid taking a snapshot unnecessarily.
1952 let snapshot = self.clone();
1956 match self.parse_expr_res(Restrictions::CONST_EXPR, None) {
1958 if token::Comma == self.token.kind || self.token.kind.should_end_const_arg() {
1959 // Avoid the following output by checking that we consumed a full const arg:
1960 // help: expressions must be enclosed in braces to be used as const generic
1963 // LL | let sr: Vec<{ (u32, _, _) = vec![] };
1965 err.multipart_suggestion(
1966 "expressions must be enclosed in braces to be used as const generic \
1969 (start.shrink_to_lo(), "{ ".to_string()),
1970 (expr.span.shrink_to_hi(), " }".to_string()),
1972 Applicability::MaybeIncorrect,
1974 let value = self.mk_expr_err(start.to(expr.span));
1976 return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
1987 /// Get the diagnostics for the cases where `move async` is found.
1989 /// `move_async_span` starts at the 'm' of the move keyword and ends with the 'c' of the async keyword
1990 pub(super) fn incorrect_move_async_order_found(
1992 move_async_span: Span,
1993 ) -> DiagnosticBuilder<'a> {
1995 self.struct_span_err(move_async_span, "the order of `move` and `async` is incorrect");
1996 err.span_suggestion_verbose(
1998 "try switching the order",
1999 "async move".to_owned(),
2000 Applicability::MaybeIncorrect,