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,
450 vec![self.mk_stmt_err(expr.span)],
452 lo.to(self.prev_token.span),
455 (Err(mut err), Ok(tail)) => {
456 // We have a block tail that contains a somehow valid type ascription expr.
460 (Err(mut snapshot_err), Err(err)) => {
461 // We don't know what went wrong, emit the normal error.
462 snapshot_err.cancel();
463 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
466 (Ok(_), Ok(tail)) => Ok(tail),
472 pub fn maybe_annotate_with_ascription(
474 err: &mut DiagnosticBuilder<'_>,
475 maybe_expected_semicolon: bool,
477 if let Some((sp, likely_path)) = self.last_type_ascription.take() {
478 let sm = self.sess.source_map();
479 let next_pos = sm.lookup_char_pos(self.token.span.lo());
480 let op_pos = sm.lookup_char_pos(sp.hi());
482 let allow_unstable = self.sess.unstable_features.is_nightly_build();
487 "maybe write a path separator here",
490 Applicability::MaybeIncorrect
492 Applicability::MachineApplicable
495 self.sess.type_ascription_path_suggestions.borrow_mut().insert(sp);
496 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
499 "try using a semicolon",
501 Applicability::MaybeIncorrect,
503 } else if allow_unstable {
504 err.span_label(sp, "tried to parse a type due to this type ascription");
506 err.span_label(sp, "tried to parse a type due to this");
509 // Give extra information about type ascription only if it's a nightly compiler.
511 "`#![feature(type_ascription)]` lets you annotate an expression with a type: \
515 // Avoid giving too much info when it was likely an unrelated typo.
517 "see issue #23416 <https://github.com/rust-lang/rust/issues/23416> \
518 for more information",
525 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
526 /// passes through any errors encountered. Used for error recovery.
527 pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
528 if let Err(ref mut err) =
529 self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
530 Ok(p.parse_token_tree())
537 /// This function checks if there are trailing angle brackets and produces
538 /// a diagnostic to suggest removing them.
540 /// ```ignore (diagnostic)
541 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
542 /// ^^ help: remove extra angle brackets
545 /// If `true` is returned, then trailing brackets were recovered, tokens were consumed
546 /// up until one of the tokens in 'end' was encountered, and an error was emitted.
547 pub(super) fn check_trailing_angle_brackets(
549 segment: &PathSegment,
552 // This function is intended to be invoked after parsing a path segment where there are two
555 // 1. A specific token is expected after the path segment.
556 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
557 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
558 // 2. No specific token is expected after the path segment.
559 // eg. `x.foo` (field access)
561 // This function is called after parsing `.foo` and before parsing the token `end` (if
562 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
565 // We only care about trailing angle brackets if we previously parsed angle bracket
566 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
567 // removed in this case:
569 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
571 // This case is particularly tricky as we won't notice it just looking at the tokens -
572 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
573 // have already been parsed):
575 // `x.foo::<u32>>>(3)`
576 let parsed_angle_bracket_args =
577 segment.args.as_ref().map_or(false, |args| args.is_angle_bracketed());
580 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
581 parsed_angle_bracket_args,
583 if !parsed_angle_bracket_args {
587 // Keep the span at the start so we can highlight the sequence of `>` characters to be
589 let lo = self.token.span;
591 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
592 // (since we might have the field access case and the characters we're eating are
593 // actual operators and not trailing characters - ie `x.foo >> 3`).
594 let mut position = 0;
596 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
597 // many of each (so we can correctly pluralize our error messages) and continue to
599 let mut number_of_shr = 0;
600 let mut number_of_gt = 0;
601 while self.look_ahead(position, |t| {
602 trace!("check_trailing_angle_brackets: t={:?}", t);
603 if *t == token::BinOp(token::BinOpToken::Shr) {
606 } else if *t == token::Gt {
616 // If we didn't find any trailing `>` characters, then we have nothing to error about.
618 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
619 number_of_gt, number_of_shr,
621 if number_of_gt < 1 && number_of_shr < 1 {
625 // Finally, double check that we have our end token as otherwise this is the
627 if self.look_ahead(position, |t| {
628 trace!("check_trailing_angle_brackets: t={:?}", t);
629 end.contains(&&t.kind)
631 // Eat from where we started until the end token so that parsing can continue
632 // as if we didn't have those extra angle brackets.
633 self.eat_to_tokens(end);
634 let span = lo.until(self.token.span);
636 let total_num_of_gt = number_of_gt + number_of_shr * 2;
637 self.struct_span_err(
639 &format!("unmatched angle bracket{}", pluralize!(total_num_of_gt)),
643 &format!("remove extra angle bracket{}", pluralize!(total_num_of_gt)),
645 Applicability::MachineApplicable,
653 /// Check if a method call with an intended turbofish has been written without surrounding
655 pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
656 if token::ModSep == self.token.kind && segment.args.is_none() {
657 let snapshot = self.clone();
659 let lo = self.token.span;
660 match self.parse_angle_args() {
662 let span = lo.to(self.prev_token.span);
663 // Detect trailing `>` like in `x.collect::Vec<_>>()`.
664 let mut trailing_span = self.prev_token.span.shrink_to_hi();
665 while self.token.kind == token::BinOp(token::Shr)
666 || self.token.kind == token::Gt
668 trailing_span = trailing_span.to(self.token.span);
671 if self.token.kind == token::OpenDelim(token::Paren) {
672 // Recover from bad turbofish: `foo.collect::Vec<_>()`.
673 let args = AngleBracketedArgs { args, span }.into();
676 self.struct_span_err(
678 "generic parameters without surrounding angle brackets",
680 .multipart_suggestion(
681 "surround the type parameters with angle brackets",
683 (span.shrink_to_lo(), "<".to_string()),
684 (trailing_span, ">".to_string()),
686 Applicability::MachineApplicable,
690 // This doesn't look like an invalid turbofish, can't recover parse state.
695 // We couldn't parse generic parameters, unlikely to be a turbofish. Rely on
696 // generic parse error instead.
704 /// When writing a turbofish with multiple type parameters missing the leading `::`, we will
705 /// encounter a parse error when encountering the first `,`.
706 pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
708 mut e: DiagnosticBuilder<'a>,
710 ) -> PResult<'a, ()> {
711 if let ExprKind::Binary(binop, _, _) = &expr.kind {
712 if let ast::BinOpKind::Lt = binop.node {
713 if self.eat(&token::Comma) {
714 let x = self.parse_seq_to_before_end(
716 SeqSep::trailing_allowed(token::Comma),
717 |p| p.parse_generic_arg(),
720 Ok((_, _, false)) => {
721 if self.eat(&token::Gt) {
722 match self.parse_expr() {
724 e.span_suggestion_verbose(
725 binop.span.shrink_to_lo(),
726 TURBOFISH_SUGGESTION_STR,
728 Applicability::MaybeIncorrect,
732 self.mk_expr_err(expr.span.to(self.prev_token.span));
752 /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
753 /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
754 /// parenthesising the leftmost comparison.
755 fn attempt_chained_comparison_suggestion(
757 err: &mut DiagnosticBuilder<'_>,
759 outer_op: &Spanned<AssocOp>,
760 ) -> bool /* advanced the cursor */ {
761 if let ExprKind::Binary(op, ref l1, ref r1) = inner_op.kind {
762 if let ExprKind::Field(_, ident) = l1.kind {
763 if ident.as_str().parse::<i32>().is_err() && !matches!(r1.kind, ExprKind::Lit(_)) {
764 // The parser has encountered `foo.bar<baz`, the likelihood of the turbofish
765 // suggestion being the only one to apply is high.
769 let mut enclose = |left: Span, right: Span| {
770 err.multipart_suggestion(
771 "parenthesize the comparison",
773 (left.shrink_to_lo(), "(".to_string()),
774 (right.shrink_to_hi(), ")".to_string()),
776 Applicability::MaybeIncorrect,
779 return match (op.node, &outer_op.node) {
781 (BinOpKind::Eq, AssocOp::Equal) |
782 // `x < y < z` and friends.
783 (BinOpKind::Lt, AssocOp::Less | AssocOp::LessEqual) |
784 (BinOpKind::Le, AssocOp::LessEqual | AssocOp::Less) |
785 // `x > y > z` and friends.
786 (BinOpKind::Gt, AssocOp::Greater | AssocOp::GreaterEqual) |
787 (BinOpKind::Ge, AssocOp::GreaterEqual | AssocOp::Greater) => {
788 let expr_to_str = |e: &Expr| {
789 self.span_to_snippet(e.span)
790 .unwrap_or_else(|_| pprust::expr_to_string(&e))
792 err.span_suggestion_verbose(
793 inner_op.span.shrink_to_hi(),
794 "split the comparison into two",
795 format!(" && {}", expr_to_str(&r1)),
796 Applicability::MaybeIncorrect,
798 false // Keep the current parse behavior, where the AST is `(x < y) < z`.
801 (BinOpKind::Eq, AssocOp::Less | AssocOp::LessEqual | AssocOp::Greater | AssocOp::GreaterEqual) => {
802 // Consume `z`/outer-op-rhs.
803 let snapshot = self.clone();
804 match self.parse_expr() {
806 // We are sure that outer-op-rhs could be consumed, the suggestion is
808 enclose(r1.span, r2.span);
811 Err(mut expr_err) => {
819 (BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge, AssocOp::Equal) => {
820 let snapshot = self.clone();
821 // At this point it is always valid to enclose the lhs in parentheses, no
822 // further checks are necessary.
823 match self.parse_expr() {
825 enclose(l1.span, r1.span);
828 Err(mut expr_err) => {
841 /// Produces an error if comparison operators are chained (RFC #558).
842 /// We only need to check the LHS, not the RHS, because all comparison ops have same
843 /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
845 /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
846 /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
849 /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
850 /// associative we can infer that we have:
859 pub(super) fn check_no_chained_comparison(
862 outer_op: &Spanned<AssocOp>,
863 ) -> PResult<'a, Option<P<Expr>>> {
865 outer_op.node.is_comparison(),
866 "check_no_chained_comparison: {:?} is not comparison",
871 |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err, AttrVec::new())));
873 match inner_op.kind {
874 ExprKind::Binary(op, ref l1, ref r1) if op.node.is_comparison() => {
875 let mut err = self.struct_span_err(
876 vec![op.span, self.prev_token.span],
877 "comparison operators cannot be chained",
880 let suggest = |err: &mut DiagnosticBuilder<'_>| {
881 err.span_suggestion_verbose(
882 op.span.shrink_to_lo(),
883 TURBOFISH_SUGGESTION_STR,
885 Applicability::MaybeIncorrect,
889 // Include `<` to provide this recommendation even in a case like
890 // `Foo<Bar<Baz<Qux, ()>>>`
891 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Less
892 || outer_op.node == AssocOp::Greater
894 if outer_op.node == AssocOp::Less {
895 let snapshot = self.clone();
897 // So far we have parsed `foo<bar<`, consume the rest of the type args.
899 [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
900 self.consume_tts(1, &modifiers[..]);
902 if !&[token::OpenDelim(token::Paren), token::ModSep]
903 .contains(&self.token.kind)
905 // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
906 // parser and bail out.
907 *self = snapshot.clone();
910 return if token::ModSep == self.token.kind {
911 // We have some certainty that this was a bad turbofish at this point.
915 let snapshot = self.clone();
918 // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
919 match self.parse_expr() {
921 // 99% certain that the suggestion is correct, continue parsing.
923 // FIXME: actually check that the two expressions in the binop are
924 // paths and resynthesize new fn call expression instead of using
925 // `ExprKind::Err` placeholder.
926 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
928 Err(mut expr_err) => {
930 // Not entirely sure now, but we bubble the error up with the
936 } else if token::OpenDelim(token::Paren) == self.token.kind {
937 // We have high certainty that this was a bad turbofish at this point.
940 // Consume the fn call arguments.
941 match self.consume_fn_args() {
945 // FIXME: actually check that the two expressions in the binop are
946 // paths and resynthesize new fn call expression instead of using
947 // `ExprKind::Err` placeholder.
948 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
952 if !matches!(l1.kind, ExprKind::Lit(_))
953 && !matches!(r1.kind, ExprKind::Lit(_))
955 // All we know is that this is `foo < bar >` and *nothing* else. Try to
956 // be helpful, but don't attempt to recover.
957 err.help(TURBOFISH_SUGGESTION_STR);
958 err.help("or use `(...)` if you meant to specify fn arguments");
961 // If it looks like a genuine attempt to chain operators (as opposed to a
962 // misformatted turbofish, for instance), suggest a correct form.
963 if self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op)
966 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
968 // These cases cause too many knock-down errors, bail out (#61329).
974 self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
977 return mk_err_expr(self, inner_op.span.to(self.prev_token.span));
985 fn consume_fn_args(&mut self) -> Result<(), ()> {
986 let snapshot = self.clone();
989 // Consume the fn call arguments.
991 [(token::OpenDelim(token::Paren), 1), (token::CloseDelim(token::Paren), -1)];
992 self.consume_tts(1, &modifiers[..]);
994 if self.token.kind == token::Eof {
995 // Not entirely sure that what we consumed were fn arguments, rollback.
999 // 99% certain that the suggestion is correct, continue parsing.
1004 pub(super) fn maybe_report_ambiguous_plus(
1006 allow_plus: AllowPlus,
1007 impl_dyn_multi: bool,
1010 if matches!(allow_plus, AllowPlus::No) && impl_dyn_multi {
1011 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1012 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1015 "use parentheses to disambiguate",
1017 Applicability::MachineApplicable,
1023 pub(super) fn maybe_recover_from_bad_type_plus(
1025 allow_plus: AllowPlus,
1027 ) -> PResult<'a, ()> {
1028 // Do not add `+` to expected tokens.
1029 if matches!(allow_plus, AllowPlus::No) || !self.token.is_like_plus() {
1034 let bounds = self.parse_generic_bounds(None)?;
1035 let sum_span = ty.span.to(self.prev_token.span);
1037 let mut err = struct_span_err!(
1038 self.sess.span_diagnostic,
1041 "expected a path on the left-hand side of `+`, not `{}`",
1042 pprust::ty_to_string(ty)
1046 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1047 let sum_with_parens = pprust::to_string(|s| {
1049 s.print_opt_lifetime(lifetime);
1050 s.print_mutability(mut_ty.mutbl, false);
1052 s.print_type(&mut_ty.ty);
1053 s.print_type_bounds(" +", &bounds);
1056 err.span_suggestion(
1058 "try adding parentheses",
1060 Applicability::MachineApplicable,
1063 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1064 err.span_label(sum_span, "perhaps you forgot parentheses?");
1067 err.span_label(sum_span, "expected a path");
1074 /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
1075 /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
1076 /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
1077 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
1080 allow_recovery: bool,
1081 ) -> PResult<'a, P<T>> {
1082 // Do not add `::` to expected tokens.
1083 if allow_recovery && self.token == token::ModSep {
1084 if let Some(ty) = base.to_ty() {
1085 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1091 /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
1092 /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
1093 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
1097 ) -> PResult<'a, P<T>> {
1098 self.expect(&token::ModSep)?;
1100 let mut path = ast::Path { segments: Vec::new(), span: DUMMY_SP, tokens: None };
1101 self.parse_path_segments(&mut path.segments, T::PATH_STYLE)?;
1102 path.span = ty_span.to(self.prev_token.span);
1104 let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
1105 self.struct_span_err(path.span, "missing angle brackets in associated item path")
1107 // This is a best-effort recovery.
1110 format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
1111 Applicability::MaybeIncorrect,
1115 let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
1116 Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path)))
1119 pub(super) fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
1120 if self.eat(&token::Semi) {
1121 let mut err = self.struct_span_err(self.prev_token.span, "expected item, found `;`");
1122 err.span_suggestion_short(
1123 self.prev_token.span,
1124 "remove this semicolon",
1126 Applicability::MachineApplicable,
1128 if !items.is_empty() {
1129 let previous_item = &items[items.len() - 1];
1130 let previous_item_kind_name = match previous_item.kind {
1131 // Say "braced struct" because tuple-structs and
1132 // braceless-empty-struct declarations do take a semicolon.
1133 ItemKind::Struct(..) => Some("braced struct"),
1134 ItemKind::Enum(..) => Some("enum"),
1135 ItemKind::Trait(..) => Some("trait"),
1136 ItemKind::Union(..) => Some("union"),
1139 if let Some(name) = previous_item_kind_name {
1140 err.help(&format!("{} declarations are not followed by a semicolon", name));
1150 /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
1151 /// closing delimiter.
1152 pub(super) fn unexpected_try_recover(
1155 ) -> PResult<'a, bool /* recovered */> {
1156 let token_str = pprust::token_kind_to_string(t);
1157 let this_token_str = super::token_descr(&self.token);
1158 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1159 // Point at the end of the macro call when reaching end of macro arguments.
1160 (token::Eof, Some(_)) => {
1161 let sp = self.sess.source_map().next_point(self.prev_token.span);
1164 // We don't want to point at the following span after DUMMY_SP.
1165 // This happens when the parser finds an empty TokenStream.
1166 _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
1167 // EOF, don't want to point at the following char, but rather the last token.
1168 (token::Eof, None) => (self.prev_token.span, self.token.span),
1169 _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
1172 "expected `{}`, found {}",
1174 match (&self.token.kind, self.subparser_name) {
1175 (token::Eof, Some(origin)) => format!("end of {}", origin),
1176 _ => this_token_str,
1179 let mut err = self.struct_span_err(sp, &msg);
1180 let label_exp = format!("expected `{}`", token_str);
1181 match self.recover_closing_delimiter(&[t.clone()], err) {
1184 return Ok(recovered);
1187 let sm = self.sess.source_map();
1188 if !sm.is_multiline(prev_sp.until(sp)) {
1189 // When the spans are in the same line, it means that the only content
1190 // between them is whitespace, point only at the found token.
1191 err.span_label(sp, label_exp);
1193 err.span_label(prev_sp, label_exp);
1194 err.span_label(sp, "unexpected token");
1199 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1200 if self.eat(&token::Semi) {
1203 self.expect(&token::Semi).map(drop) // Error unconditionally
1206 /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
1207 /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
1208 pub(super) fn recover_incorrect_await_syntax(
1213 ) -> PResult<'a, P<Expr>> {
1214 let (hi, expr, is_question) = if self.token == token::Not {
1215 // Handle `await!(<expr>)`.
1216 self.recover_await_macro()?
1218 self.recover_await_prefix(await_sp)?
1220 let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
1221 let kind = match expr.kind {
1222 // Avoid knock-down errors as we don't know whether to interpret this as `foo().await?`
1223 // or `foo()?.await` (the very reason we went with postfix syntax 😅).
1224 ExprKind::Try(_) => ExprKind::Err,
1225 _ => ExprKind::Await(expr),
1227 let expr = self.mk_expr(lo.to(sp), kind, attrs);
1228 self.maybe_recover_from_bad_qpath(expr, true)
1231 fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1232 self.expect(&token::Not)?;
1233 self.expect(&token::OpenDelim(token::Paren))?;
1234 let expr = self.parse_expr()?;
1235 self.expect(&token::CloseDelim(token::Paren))?;
1236 Ok((self.prev_token.span, expr, false))
1239 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
1240 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
1241 let expr = if self.token == token::OpenDelim(token::Brace) {
1242 // Handle `await { <expr> }`.
1243 // This needs to be handled separately from the next arm to avoid
1244 // interpreting `await { <expr> }?` as `<expr>?.await`.
1245 self.parse_block_expr(None, self.token.span, BlockCheckMode::Default, AttrVec::new())
1249 .map_err(|mut err| {
1250 err.span_label(await_sp, "while parsing this incorrect await expression");
1253 Ok((expr.span, expr, is_question))
1256 fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
1258 self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr));
1259 let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" });
1261 let app = match expr.kind {
1262 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
1263 _ => Applicability::MachineApplicable,
1265 self.struct_span_err(sp, "incorrect use of `await`")
1266 .span_suggestion(sp, "`await` is a postfix operation", suggestion, app)
1271 /// If encountering `future.await()`, consumes and emits an error.
1272 pub(super) fn recover_from_await_method_call(&mut self) {
1273 if self.token == token::OpenDelim(token::Paren)
1274 && self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren))
1277 let lo = self.token.span;
1279 let sp = lo.to(self.token.span);
1281 self.struct_span_err(sp, "incorrect use of `await`")
1284 "`await` is not a method call, remove the parentheses",
1286 Applicability::MachineApplicable,
1292 pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, P<Expr>> {
1293 let is_try = self.token.is_keyword(kw::Try);
1294 let is_questionmark = self.look_ahead(1, |t| t == &token::Not); //check for !
1295 let is_open = self.look_ahead(2, |t| t == &token::OpenDelim(token::Paren)); //check for (
1297 if is_try && is_questionmark && is_open {
1298 let lo = self.token.span;
1299 self.bump(); //remove try
1300 self.bump(); //remove !
1301 let try_span = lo.to(self.token.span); //we take the try!( span
1302 self.bump(); //remove (
1303 let is_empty = self.token == token::CloseDelim(token::Paren); //check if the block is empty
1304 self.consume_block(token::Paren, ConsumeClosingDelim::No); //eat the block
1305 let hi = self.token.span;
1306 self.bump(); //remove )
1307 let mut err = self.struct_span_err(lo.to(hi), "use of deprecated `try` macro");
1308 err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
1309 let prefix = if is_empty { "" } else { "alternatively, " };
1311 err.multipart_suggestion(
1312 "you can use the `?` operator instead",
1313 vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
1314 Applicability::MachineApplicable,
1317 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);
1319 Ok(self.mk_expr_err(lo.to(hi)))
1321 Err(self.expected_expression_found()) // The user isn't trying to invoke the try! macro
1325 /// Recovers a situation like `for ( $pat in $expr )`
1326 /// and suggest writing `for $pat in $expr` instead.
1328 /// This should be called before parsing the `$block`.
1329 pub(super) fn recover_parens_around_for_head(
1333 begin_paren: Option<Span>,
1335 match (&self.token.kind, begin_paren) {
1336 (token::CloseDelim(token::Paren), Some(begin_par_sp)) => {
1340 // Remove the `(` from the span of the pattern:
1341 .span_to_snippet(pat.span.trim_start(begin_par_sp).unwrap())
1342 .unwrap_or_else(|_| pprust::pat_to_string(&pat));
1344 self.struct_span_err(self.prev_token.span, "unexpected closing `)`")
1345 .span_label(begin_par_sp, "opening `(`")
1347 begin_par_sp.to(self.prev_token.span),
1348 "remove parenthesis in `for` loop",
1349 format!("{} in {}", pat_str, pprust::expr_to_string(&expr)),
1350 // With e.g. `for (x) in y)` this would replace `(x) in y)`
1351 // with `x) in y)` which is syntactically invalid.
1352 // However, this is prevented before we get here.
1353 Applicability::MachineApplicable,
1357 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1358 pat.and_then(|pat| match pat.kind {
1359 PatKind::Paren(pat) => pat,
1367 pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1368 (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1369 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1370 || self.token.is_ident() &&
1371 matches!(node, ast::ExprKind::Path(..) | ast::ExprKind::Field(..)) &&
1372 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
1373 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren))
1374 || self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) // `foo:bar {`
1375 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar::<baz`
1376 self.look_ahead(2, |t| t == &token::Lt) &&
1377 self.look_ahead(3, |t| t.is_ident())
1378 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
1379 self.look_ahead(2, |t| t.is_ident())
1380 || self.look_ahead(1, |t| t == &token::ModSep)
1381 && (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
1382 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1385 pub(super) fn recover_seq_parse_error(
1387 delim: token::DelimToken,
1389 result: PResult<'a, P<Expr>>,
1395 // Recover from parse error, callers expect the closing delim to be consumed.
1396 self.consume_block(delim, ConsumeClosingDelim::Yes);
1397 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err, AttrVec::new())
1402 pub(super) fn recover_closing_delimiter(
1404 tokens: &[TokenKind],
1405 mut err: DiagnosticBuilder<'a>,
1406 ) -> PResult<'a, bool> {
1408 // We want to use the last closing delim that would apply.
1409 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1410 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1411 && Some(self.token.span) > unmatched.unclosed_span
1418 // Recover and assume that the detected unclosed delimiter was meant for
1419 // this location. Emit the diagnostic and act as if the delimiter was
1420 // present for the parser's sake.
1422 // Don't attempt to recover from this unclosed delimiter more than once.
1423 let unmatched = self.unclosed_delims.remove(pos);
1424 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1425 if unmatched.found_delim.is_none() {
1426 // We encountered `Eof`, set this fact here to avoid complaining about missing
1427 // `fn main()` when we found place to suggest the closing brace.
1428 *self.sess.reached_eof.borrow_mut() = true;
1431 // We want to suggest the inclusion of the closing delimiter where it makes
1432 // the most sense, which is immediately after the last token:
1437 // | help: `)` may belong here
1439 // unclosed delimiter
1440 if let Some(sp) = unmatched.unclosed_span {
1441 err.span_label(sp, "unclosed delimiter");
1443 // Backticks should be removed to apply suggestions.
1444 let mut delim = delim.to_string();
1445 delim.retain(|c| c != '`');
1446 err.span_suggestion_short(
1447 self.prev_token.span.shrink_to_hi(),
1448 &format!("`{}` may belong here", delim),
1450 Applicability::MaybeIncorrect,
1452 if unmatched.found_delim.is_none() {
1453 // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1454 // errors which would be emitted elsewhere in the parser and let other error
1455 // recovery consume the rest of the file.
1459 self.expected_tokens.clear(); // Reduce the number of errors.
1467 /// Eats tokens until we can be relatively sure we reached the end of the
1468 /// statement. This is something of a best-effort heuristic.
1470 /// We terminate when we find an unmatched `}` (without consuming it).
1471 pub(super) fn recover_stmt(&mut self) {
1472 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1475 /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1476 /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1477 /// approximate -- it can mean we break too early due to macros, but that
1478 /// should only lead to sub-optimal recovery, not inaccurate parsing).
1480 /// If `break_on_block` is `Break`, then we will stop consuming tokens
1481 /// after finding (and consuming) a brace-delimited block.
1482 pub(super) fn recover_stmt_(
1484 break_on_semi: SemiColonMode,
1485 break_on_block: BlockMode,
1487 let mut brace_depth = 0;
1488 let mut bracket_depth = 0;
1489 let mut in_block = false;
1490 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1492 debug!("recover_stmt_ loop {:?}", self.token);
1493 match self.token.kind {
1494 token::OpenDelim(token::DelimToken::Brace) => {
1497 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1502 token::OpenDelim(token::DelimToken::Bracket) => {
1506 token::CloseDelim(token::DelimToken::Brace) => {
1507 if brace_depth == 0 {
1508 debug!("recover_stmt_ return - close delim {:?}", self.token);
1513 if in_block && bracket_depth == 0 && brace_depth == 0 {
1514 debug!("recover_stmt_ return - block end {:?}", self.token);
1518 token::CloseDelim(token::DelimToken::Bracket) => {
1520 if bracket_depth < 0 {
1526 debug!("recover_stmt_ return - Eof");
1531 if break_on_semi == SemiColonMode::Break
1533 && bracket_depth == 0
1535 debug!("recover_stmt_ return - Semi");
1540 if break_on_semi == SemiColonMode::Comma
1542 && bracket_depth == 0 =>
1544 debug!("recover_stmt_ return - Semi");
1552 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1553 if self.eat_keyword(kw::In) {
1554 // a common typo: `for _ in in bar {}`
1555 self.struct_span_err(self.prev_token.span, "expected iterable, found keyword `in`")
1556 .span_suggestion_short(
1557 in_span.until(self.prev_token.span),
1558 "remove the duplicated `in`",
1560 Applicability::MachineApplicable,
1566 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1567 if let token::DocComment(..) = self.token.kind {
1568 self.struct_span_err(
1570 "documentation comments cannot be applied to a function parameter's type",
1572 .span_label(self.token.span, "doc comments are not allowed here")
1575 } else if self.token == token::Pound
1576 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Bracket))
1578 let lo = self.token.span;
1579 // Skip every token until next possible arg.
1580 while self.token != token::CloseDelim(token::Bracket) {
1583 let sp = lo.to(self.token.span);
1585 self.struct_span_err(sp, "attributes cannot be applied to a function parameter's type")
1586 .span_label(sp, "attributes are not allowed here")
1591 pub(super) fn parameter_without_type(
1593 err: &mut DiagnosticBuilder<'_>,
1597 ) -> Option<Ident> {
1598 // If we find a pattern followed by an identifier, it could be an (incorrect)
1599 // C-style parameter declaration.
1600 if self.check_ident()
1601 && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseDelim(token::Paren))
1603 // `fn foo(String s) {}`
1604 let ident = self.parse_ident().unwrap();
1605 let span = pat.span.with_hi(ident.span.hi());
1607 err.span_suggestion(
1609 "declare the type after the parameter binding",
1610 String::from("<identifier>: <type>"),
1611 Applicability::HasPlaceholders,
1614 } else if require_name
1615 && (self.token == token::Comma
1616 || self.token == token::Lt
1617 || self.token == token::CloseDelim(token::Paren))
1619 let rfc_note = "anonymous parameters are removed in the 2018 edition (see RFC 1685)";
1621 let (ident, self_sugg, param_sugg, type_sugg) = match pat.kind {
1622 PatKind::Ident(_, ident, _) => (
1624 format!("self: {}", ident),
1625 format!("{}: TypeName", ident),
1626 format!("_: {}", ident),
1628 // Also catches `fn foo(&a)`.
1629 PatKind::Ref(ref pat, mutab)
1630 if matches!(pat.clone().into_inner().kind, PatKind::Ident(..)) =>
1632 match pat.clone().into_inner().kind {
1633 PatKind::Ident(_, ident, _) => {
1634 let mutab = mutab.prefix_str();
1637 format!("self: &{}{}", mutab, ident),
1638 format!("{}: &{}TypeName", ident, mutab),
1639 format!("_: &{}{}", mutab, ident),
1642 _ => unreachable!(),
1646 // Otherwise, try to get a type and emit a suggestion.
1647 if let Some(ty) = pat.to_ty() {
1648 err.span_suggestion_verbose(
1650 "explicitly ignore the parameter name",
1651 format!("_: {}", pprust::ty_to_string(&ty)),
1652 Applicability::MachineApplicable,
1661 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1663 err.span_suggestion(
1665 "if this is a `self` type, give it a parameter name",
1667 Applicability::MaybeIncorrect,
1670 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
1671 // `fn foo(HashMap: TypeName<u32>)`.
1672 if self.token != token::Lt {
1673 err.span_suggestion(
1675 "if this is a parameter name, give it a type",
1677 Applicability::HasPlaceholders,
1680 err.span_suggestion(
1682 "if this is a type, explicitly ignore the parameter name",
1684 Applicability::MachineApplicable,
1688 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
1689 return if self.token == token::Lt { None } else { Some(ident) };
1694 pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
1695 let pat = self.parse_pat_no_top_alt(Some("argument name"))?;
1696 self.expect(&token::Colon)?;
1697 let ty = self.parse_ty()?;
1703 "patterns aren't allowed in methods without bodies",
1705 .span_suggestion_short(
1707 "give this argument a name or use an underscore to ignore it",
1709 Applicability::MachineApplicable,
1713 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1715 P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID, tokens: None });
1719 pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
1720 let sp = param.pat.span;
1721 param.ty.kind = TyKind::Err;
1722 self.struct_span_err(sp, "unexpected `self` parameter in function")
1723 .span_label(sp, "must be the first parameter of an associated function")
1728 pub(super) fn consume_block(
1730 delim: token::DelimToken,
1731 consume_close: ConsumeClosingDelim,
1733 let mut brace_depth = 0;
1735 if self.eat(&token::OpenDelim(delim)) {
1737 } else if self.check(&token::CloseDelim(delim)) {
1738 if brace_depth == 0 {
1739 if let ConsumeClosingDelim::Yes = consume_close {
1740 // Some of the callers of this method expect to be able to parse the
1741 // closing delimiter themselves, so we leave it alone. Otherwise we advance
1751 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
1759 pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a> {
1760 let (span, msg) = match (&self.token.kind, self.subparser_name) {
1761 (&token::Eof, Some(origin)) => {
1762 let sp = self.sess.source_map().next_point(self.prev_token.span);
1763 (sp, format!("expected expression, found end of {}", origin))
1767 format!("expected expression, found {}", super::token_descr(&self.token),),
1770 let mut err = self.struct_span_err(span, &msg);
1771 let sp = self.sess.source_map().start_point(self.token.span);
1772 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
1773 self.sess.expr_parentheses_needed(&mut err, *sp);
1775 err.span_label(span, "expected expression");
1781 mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
1782 // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
1783 modifier: &[(token::TokenKind, i64)],
1786 if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
1789 if self.token.kind == token::Eof {
1796 /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
1798 /// This is necessary because at this point we don't know whether we parsed a function with
1799 /// anonymous parameters or a function with names but no types. In order to minimize
1800 /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
1801 /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
1802 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
1803 /// we deduplicate them to not complain about duplicated parameter names.
1804 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
1805 let mut seen_inputs = FxHashSet::default();
1806 for input in fn_inputs.iter_mut() {
1807 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
1808 (&input.pat.kind, &input.ty.kind)
1814 if let Some(ident) = opt_ident {
1815 if seen_inputs.contains(&ident) {
1816 input.pat.kind = PatKind::Wild;
1818 seen_inputs.insert(ident);
1823 /// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
1824 /// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
1825 /// like the user has forgotten them.
1826 pub fn handle_ambiguous_unbraced_const_arg(
1828 args: &mut Vec<AngleBracketedArg>,
1829 ) -> PResult<'a, bool> {
1830 // If we haven't encountered a closing `>`, then the argument is malformed.
1831 // It's likely that the user has written a const expression without enclosing it
1832 // in braces, so we try to recover here.
1833 let arg = args.pop().unwrap();
1834 // FIXME: for some reason using `unexpected` or `expected_one_of_not_found` has
1835 // adverse side-effects to subsequent errors and seems to advance the parser.
1836 // We are causing this error here exclusively in case that a `const` expression
1837 // could be recovered from the current parser state, even if followed by more
1838 // arguments after a comma.
1839 let mut err = self.struct_span_err(
1841 &format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
1843 err.span_label(self.token.span, "expected one of `,` or `>`");
1844 match self.recover_const_arg(arg.span(), err) {
1846 args.push(AngleBracketedArg::Arg(arg));
1847 if self.eat(&token::Comma) {
1848 return Ok(true); // Continue
1853 // We will emit a more generic error later.
1857 return Ok(false); // Don't continue.
1860 /// Attempt to parse a generic const argument that has not been enclosed in braces.
1861 /// There are a limited number of expressions that are permitted without being encoded
1864 /// - Single-segment paths (i.e. standalone generic const parameters).
1865 /// All other expressions that can be parsed will emit an error suggesting the expression be
1866 /// wrapped in braces.
1867 pub fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
1868 let start = self.token.span;
1869 let expr = self.parse_expr_res(Restrictions::CONST_EXPR, None).map_err(|mut err| {
1871 start.shrink_to_lo(),
1872 "while parsing a const generic argument starting here",
1876 if !self.expr_is_valid_const_arg(&expr) {
1877 self.struct_span_err(
1879 "expressions must be enclosed in braces to be used as const generic \
1882 .multipart_suggestion(
1883 "enclose the `const` expression in braces",
1885 (expr.span.shrink_to_lo(), "{ ".to_string()),
1886 (expr.span.shrink_to_hi(), " }".to_string()),
1888 Applicability::MachineApplicable,
1895 /// Try to recover from possible generic const argument without `{` and `}`.
1897 /// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
1898 /// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
1899 /// if we think that that the resulting expression would be well formed.
1900 pub fn recover_const_arg(
1903 mut err: DiagnosticBuilder<'a>,
1904 ) -> PResult<'a, GenericArg> {
1905 let is_op = AssocOp::from_token(&self.token)
1907 if let AssocOp::Greater
1909 | AssocOp::ShiftRight
1910 | AssocOp::GreaterEqual
1911 // Don't recover from `foo::<bar = baz>`, because this could be an attempt to
1912 // assign a value to a defaulted generic parameter.
1914 | AssocOp::AssignOp(_) = op
1922 // This will be true when a trait object type `Foo +` or a path which was a `const fn` with
1923 // type params has been parsed.
1925 matches!(self.prev_token.kind, token::BinOp(token::Plus | token::Shr) | token::Gt);
1926 if !is_op && !was_op {
1927 // We perform these checks and early return to avoid taking a snapshot unnecessarily.
1930 let snapshot = self.clone();
1934 match self.parse_expr_res(Restrictions::CONST_EXPR, None) {
1936 if token::Comma == self.token.kind || self.token.kind.should_end_const_arg() {
1937 // Avoid the following output by checking that we consumed a full const arg:
1938 // help: expressions must be enclosed in braces to be used as const generic
1941 // LL | let sr: Vec<{ (u32, _, _) = vec![] };
1943 err.multipart_suggestion(
1944 "expressions must be enclosed in braces to be used as const generic \
1947 (start.shrink_to_lo(), "{ ".to_string()),
1948 (expr.span.shrink_to_hi(), " }".to_string()),
1950 Applicability::MaybeIncorrect,
1952 let value = self.mk_expr_err(start.to(expr.span));
1954 return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
1965 /// Get the diagnostics for the cases where `move async` is found.
1967 /// `move_async_span` starts at the 'm' of the move keyword and ends with the 'c' of the async keyword
1968 pub(super) fn incorrect_move_async_order_found(
1970 move_async_span: Span,
1971 ) -> DiagnosticBuilder<'a> {
1973 self.struct_span_err(move_async_span, "the order of `move` and `async` is incorrect");
1974 err.span_suggestion_verbose(
1976 "try switching the order",
1977 "async move".to_owned(),
1978 Applicability::MaybeIncorrect,