1 use super::pat::Expected;
2 use super::ty::{AllowPlus, IsAsCast};
4 BlockMode, Parser, PathStyle, RecoverColon, RecoverComma, Restrictions, SemiColonMode, SeqSep,
5 TokenExpectType, TokenType,
10 use rustc_ast::token::{self, Lit, LitKind, TokenKind};
11 use rustc_ast::util::parser::AssocOp;
13 AngleBracketedArg, AngleBracketedArgs, AnonConst, AttrVec, BinOpKind, BindingMode, Block,
14 BlockCheckMode, Expr, ExprKind, GenericArg, Generics, Item, ItemKind, Mutability, Param, Pat,
15 PatKind, Path, PathSegment, QSelf, Ty, TyKind,
17 use rustc_ast_pretty::pprust;
18 use rustc_data_structures::fx::FxHashSet;
19 use rustc_errors::{pluralize, struct_span_err};
20 use rustc_errors::{Applicability, DiagnosticBuilder, Handler, PResult};
21 use rustc_span::source_map::Spanned;
22 use rustc_span::symbol::{kw, Ident};
23 use rustc_span::{MultiSpan, Span, SpanSnippetError, DUMMY_SP};
27 use tracing::{debug, trace};
29 const TURBOFISH_SUGGESTION_STR: &str =
30 "use `::<...>` instead of `<...>` to specify type or const arguments";
32 /// Creates a placeholder argument.
33 pub(super) fn dummy_arg(ident: Ident) -> Param {
35 id: ast::DUMMY_NODE_ID,
36 kind: PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None),
40 let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID, tokens: None };
42 attrs: AttrVec::default(),
43 id: ast::DUMMY_NODE_ID,
47 is_placeholder: false,
56 fn span_err(self, sp: impl Into<MultiSpan>, handler: &Handler) -> DiagnosticBuilder<'_> {
58 Error::UselessDocComment => {
59 let mut err = struct_span_err!(
63 "found a documentation comment that doesn't document anything",
66 "doc comments must come before what they document, maybe a comment was \
75 pub(super) trait RecoverQPath: Sized + 'static {
76 const PATH_STYLE: PathStyle = PathStyle::Expr;
77 fn to_ty(&self) -> Option<P<Ty>>;
78 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
81 impl RecoverQPath for Ty {
82 const PATH_STYLE: PathStyle = PathStyle::Type;
83 fn to_ty(&self) -> Option<P<Ty>> {
86 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
89 kind: TyKind::Path(qself, path),
90 id: ast::DUMMY_NODE_ID,
96 impl RecoverQPath for Pat {
97 fn to_ty(&self) -> Option<P<Ty>> {
100 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
103 kind: PatKind::Path(qself, path),
104 id: ast::DUMMY_NODE_ID,
110 impl RecoverQPath for Expr {
111 fn to_ty(&self) -> Option<P<Ty>> {
114 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
117 kind: ExprKind::Path(qself, path),
118 attrs: AttrVec::new(),
119 id: ast::DUMMY_NODE_ID,
125 /// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
126 crate enum ConsumeClosingDelim {
131 #[derive(Clone, Copy)]
132 pub enum AttemptLocalParseRecovery {
137 impl AttemptLocalParseRecovery {
138 pub fn yes(&self) -> bool {
140 AttemptLocalParseRecovery::Yes => true,
141 AttemptLocalParseRecovery::No => false,
145 pub fn no(&self) -> bool {
147 AttemptLocalParseRecovery::Yes => false,
148 AttemptLocalParseRecovery::No => true,
153 impl<'a> Parser<'a> {
154 pub(super) fn span_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
155 err.span_err(sp, self.diagnostic())
158 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
159 self.sess.span_diagnostic.struct_span_err(sp, m)
162 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
163 self.sess.span_diagnostic.span_bug(sp, m)
166 pub(super) fn diagnostic(&self) -> &'a Handler {
167 &self.sess.span_diagnostic
170 pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
171 self.sess.source_map().span_to_snippet(span)
174 pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
175 let mut err = self.struct_span_err(
177 &format!("expected identifier, found {}", super::token_descr(&self.token)),
179 let valid_follow = &[
185 TokenKind::OpenDelim(token::DelimToken::Brace),
186 TokenKind::OpenDelim(token::DelimToken::Paren),
187 TokenKind::CloseDelim(token::DelimToken::Brace),
188 TokenKind::CloseDelim(token::DelimToken::Paren),
190 match self.token.ident() {
192 if ident.is_raw_guess()
193 && self.look_ahead(1, |t| valid_follow.contains(&t.kind)) =>
197 "you can escape reserved keywords to use them as identifiers",
198 format!("r#{}", ident.name),
199 Applicability::MaybeIncorrect,
204 if let Some(token_descr) = super::token_descr_opt(&self.token) {
205 err.span_label(self.token.span, format!("expected identifier, found {}", token_descr));
207 err.span_label(self.token.span, "expected identifier");
208 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
213 Applicability::MachineApplicable,
220 pub(super) fn expected_one_of_not_found(
222 edible: &[TokenKind],
223 inedible: &[TokenKind],
224 ) -> PResult<'a, bool /* recovered */> {
225 debug!("expected_one_of_not_found(edible: {:?}, inedible: {:?})", edible, inedible);
226 fn tokens_to_string(tokens: &[TokenType]) -> String {
227 let mut i = tokens.iter();
228 // This might be a sign we need a connect method on `Iterator`.
229 let b = i.next().map_or_else(String::new, |t| t.to_string());
230 i.enumerate().fold(b, |mut b, (i, a)| {
231 if tokens.len() > 2 && i == tokens.len() - 2 {
233 } else if tokens.len() == 2 && i == tokens.len() - 2 {
238 b.push_str(&a.to_string());
243 let mut expected = edible
245 .map(|x| TokenType::Token(x.clone()))
246 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
247 .chain(self.expected_tokens.iter().cloned())
248 .collect::<Vec<_>>();
249 expected.sort_by_cached_key(|x| x.to_string());
252 let sm = self.sess.source_map();
253 let msg = format!("expected `;`, found {}", super::token_descr(&self.token));
254 let appl = Applicability::MachineApplicable;
255 if expected.contains(&TokenType::Token(token::Semi)) {
256 if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
257 // Likely inside a macro, can't provide meaningful suggestions.
258 } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
259 // The current token is in the same line as the prior token, not recoverable.
260 } else if [token::Comma, token::Colon].contains(&self.token.kind)
261 && self.prev_token.kind == token::CloseDelim(token::Paren)
263 // Likely typo: The current token is on a new line and is expected to be
264 // `.`, `;`, `?`, or an operator after a close delimiter token.
266 // let a = std::process::Command::new("echo")
270 // https://github.com/rust-lang/rust/issues/72253
271 } else if self.look_ahead(1, |t| {
272 t == &token::CloseDelim(token::Brace)
273 || t.can_begin_expr() && t.kind != token::Colon
274 }) && [token::Comma, token::Colon].contains(&self.token.kind)
276 // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is
277 // either `,` or `:`, and the next token could either start a new statement or is a
278 // block close. For example:
283 let sp = self.prev_token.span;
284 self.struct_span_err(sp, &msg)
285 .span_suggestion_short(sp, "change this to `;`", ";".to_string(), appl)
288 } else if self.look_ahead(0, |t| {
289 t == &token::CloseDelim(token::Brace)
291 t.can_begin_expr() && t != &token::Semi && t != &token::Pound
292 // Avoid triggering with too many trailing `#` in raw string.
295 // Missing semicolon typo. This is triggered if the next token could either start a
296 // new statement or is a block close. For example:
300 let sp = self.prev_token.span.shrink_to_hi();
301 self.struct_span_err(sp, &msg)
302 .span_label(self.token.span, "unexpected token")
303 .span_suggestion_short(sp, "add `;` here", ";".to_string(), appl)
309 let expect = tokens_to_string(&expected);
310 let actual = super::token_descr(&self.token);
311 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
312 let short_expect = if expected.len() > 6 {
313 format!("{} possible tokens", expected.len())
318 format!("expected one of {}, found {}", expect, actual),
319 (self.prev_token.span.shrink_to_hi(), format!("expected one of {}", short_expect)),
321 } else if expected.is_empty() {
323 format!("unexpected token: {}", actual),
324 (self.prev_token.span, "unexpected token after this".to_string()),
328 format!("expected {}, found {}", expect, actual),
329 (self.prev_token.span.shrink_to_hi(), format!("expected {}", expect)),
332 self.last_unexpected_token_span = Some(self.token.span);
333 let mut err = self.struct_span_err(self.token.span, &msg_exp);
335 // Add suggestion for a missing closing angle bracket if '>' is included in expected_tokens
336 // there are unclosed angle brackets
337 if self.unmatched_angle_bracket_count > 0
338 && self.token.kind == TokenKind::Eq
339 && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Gt)))
341 err.span_label(self.prev_token.span, "maybe try to close unmatched angle bracket");
344 let sp = if self.token == token::Eof {
345 // This is EOF; don't want to point at the following char, but rather the last token.
350 match self.recover_closing_delimiter(
353 .filter_map(|tt| match tt {
354 TokenType::Token(t) => Some(t.clone()),
357 .collect::<Vec<_>>(),
362 return Ok(recovered);
366 if self.check_too_many_raw_str_terminators(&mut err) {
370 if self.prev_token.span == DUMMY_SP {
371 // Account for macro context where the previous span might not be
372 // available to avoid incorrect output (#54841).
373 err.span_label(self.token.span, label_exp);
374 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
375 // When the spans are in the same line, it means that the only content between
376 // them is whitespace, point at the found token in that case:
378 // X | () => { syntax error };
379 // | ^^^^^ expected one of 8 possible tokens here
381 // instead of having:
383 // X | () => { syntax error };
384 // | -^^^^^ unexpected token
386 // | expected one of 8 possible tokens here
387 err.span_label(self.token.span, label_exp);
389 err.span_label(sp, label_exp);
390 err.span_label(self.token.span, "unexpected token");
392 self.maybe_annotate_with_ascription(&mut err, false);
396 fn check_too_many_raw_str_terminators(&mut self, err: &mut DiagnosticBuilder<'_>) -> bool {
397 match (&self.prev_token.kind, &self.token.kind) {
399 TokenKind::Literal(Lit {
400 kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
405 err.set_primary_message("too many `#` when terminating raw string");
408 "remove the extra `#`",
410 Applicability::MachineApplicable,
412 err.note(&format!("the raw string started with {} `#`s", n_hashes));
419 pub fn maybe_suggest_struct_literal(
423 ) -> Option<PResult<'a, P<Block>>> {
424 if self.token.is_ident() && self.look_ahead(1, |t| t == &token::Colon) {
425 // We might be having a struct literal where people forgot to include the path:
429 let mut snapshot = self.clone();
431 Path { segments: vec![], span: self.prev_token.span.shrink_to_lo(), tokens: None };
432 let struct_expr = snapshot.parse_struct_expr(None, path, AttrVec::new(), false);
433 let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No);
434 return Some(match (struct_expr, block_tail) {
435 (Ok(expr), Err(mut err)) => {
436 // We have encountered the following:
441 // fn foo() -> Foo { Path {
445 self.struct_span_err(expr.span, "struct literal body without path")
446 .multipart_suggestion(
447 "you might have forgotten to add the struct literal inside the block",
449 (expr.span.shrink_to_lo(), "{ SomeStruct ".to_string()),
450 (expr.span.shrink_to_hi(), " }".to_string()),
452 Applicability::MaybeIncorrect,
456 let mut tail = self.mk_block(
457 vec![self.mk_stmt_err(expr.span)],
459 lo.to(self.prev_token.span),
461 tail.could_be_bare_literal = true;
464 (Err(mut err), Ok(tail)) => {
465 // We have a block tail that contains a somehow valid type ascription expr.
469 (Err(mut snapshot_err), Err(err)) => {
470 // We don't know what went wrong, emit the normal error.
471 snapshot_err.cancel();
472 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
475 (Ok(_), Ok(mut tail)) => {
476 tail.could_be_bare_literal = true;
484 pub fn maybe_annotate_with_ascription(
486 err: &mut DiagnosticBuilder<'_>,
487 maybe_expected_semicolon: bool,
489 if let Some((sp, likely_path)) = self.last_type_ascription.take() {
490 let sm = self.sess.source_map();
491 let next_pos = sm.lookup_char_pos(self.token.span.lo());
492 let op_pos = sm.lookup_char_pos(sp.hi());
494 let allow_unstable = self.sess.unstable_features.is_nightly_build();
499 "maybe write a path separator here",
502 Applicability::MaybeIncorrect
504 Applicability::MachineApplicable
507 self.sess.type_ascription_path_suggestions.borrow_mut().insert(sp);
508 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
511 "try using a semicolon",
513 Applicability::MaybeIncorrect,
515 } else if allow_unstable {
516 err.span_label(sp, "tried to parse a type due to this type ascription");
518 err.span_label(sp, "tried to parse a type due to this");
521 // Give extra information about type ascription only if it's a nightly compiler.
523 "`#![feature(type_ascription)]` lets you annotate an expression with a type: \
527 // Avoid giving too much info when it was likely an unrelated typo.
529 "see issue #23416 <https://github.com/rust-lang/rust/issues/23416> \
530 for more information",
537 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
538 /// passes through any errors encountered. Used for error recovery.
539 pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
540 if let Err(ref mut err) =
541 self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
542 Ok(p.parse_token_tree())
549 /// This function checks if there are trailing angle brackets and produces
550 /// a diagnostic to suggest removing them.
552 /// ```ignore (diagnostic)
553 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
554 /// ^^ help: remove extra angle brackets
557 /// If `true` is returned, then trailing brackets were recovered, tokens were consumed
558 /// up until one of the tokens in 'end' was encountered, and an error was emitted.
559 pub(super) fn check_trailing_angle_brackets(
561 segment: &PathSegment,
564 // This function is intended to be invoked after parsing a path segment where there are two
567 // 1. A specific token is expected after the path segment.
568 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
569 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
570 // 2. No specific token is expected after the path segment.
571 // eg. `x.foo` (field access)
573 // This function is called after parsing `.foo` and before parsing the token `end` (if
574 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
577 // We only care about trailing angle brackets if we previously parsed angle bracket
578 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
579 // removed in this case:
581 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
583 // This case is particularly tricky as we won't notice it just looking at the tokens -
584 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
585 // have already been parsed):
587 // `x.foo::<u32>>>(3)`
588 let parsed_angle_bracket_args =
589 segment.args.as_ref().map_or(false, |args| args.is_angle_bracketed());
592 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
593 parsed_angle_bracket_args,
595 if !parsed_angle_bracket_args {
599 // Keep the span at the start so we can highlight the sequence of `>` characters to be
601 let lo = self.token.span;
603 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
604 // (since we might have the field access case and the characters we're eating are
605 // actual operators and not trailing characters - ie `x.foo >> 3`).
606 let mut position = 0;
608 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
609 // many of each (so we can correctly pluralize our error messages) and continue to
611 let mut number_of_shr = 0;
612 let mut number_of_gt = 0;
613 while self.look_ahead(position, |t| {
614 trace!("check_trailing_angle_brackets: t={:?}", t);
615 if *t == token::BinOp(token::BinOpToken::Shr) {
618 } else if *t == token::Gt {
628 // If we didn't find any trailing `>` characters, then we have nothing to error about.
630 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
631 number_of_gt, number_of_shr,
633 if number_of_gt < 1 && number_of_shr < 1 {
637 // Finally, double check that we have our end token as otherwise this is the
639 if self.look_ahead(position, |t| {
640 trace!("check_trailing_angle_brackets: t={:?}", t);
641 end.contains(&&t.kind)
643 // Eat from where we started until the end token so that parsing can continue
644 // as if we didn't have those extra angle brackets.
645 self.eat_to_tokens(end);
646 let span = lo.until(self.token.span);
648 let total_num_of_gt = number_of_gt + number_of_shr * 2;
649 self.struct_span_err(
651 &format!("unmatched angle bracket{}", pluralize!(total_num_of_gt)),
655 &format!("remove extra angle bracket{}", pluralize!(total_num_of_gt)),
657 Applicability::MachineApplicable,
665 /// Check if a method call with an intended turbofish has been written without surrounding
667 pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
668 if token::ModSep == self.token.kind && segment.args.is_none() {
669 let snapshot = self.clone();
671 let lo = self.token.span;
672 match self.parse_angle_args(None) {
674 let span = lo.to(self.prev_token.span);
675 // Detect trailing `>` like in `x.collect::Vec<_>>()`.
676 let mut trailing_span = self.prev_token.span.shrink_to_hi();
677 while self.token.kind == token::BinOp(token::Shr)
678 || self.token.kind == token::Gt
680 trailing_span = trailing_span.to(self.token.span);
683 if self.token.kind == token::OpenDelim(token::Paren) {
684 // Recover from bad turbofish: `foo.collect::Vec<_>()`.
685 let args = AngleBracketedArgs { args, span }.into();
688 self.struct_span_err(
690 "generic parameters without surrounding angle brackets",
692 .multipart_suggestion(
693 "surround the type parameters with angle brackets",
695 (span.shrink_to_lo(), "<".to_string()),
696 (trailing_span, ">".to_string()),
698 Applicability::MachineApplicable,
702 // This doesn't look like an invalid turbofish, can't recover parse state.
707 // We couldn't parse generic parameters, unlikely to be a turbofish. Rely on
708 // generic parse error instead.
716 /// When writing a turbofish with multiple type parameters missing the leading `::`, we will
717 /// encounter a parse error when encountering the first `,`.
718 pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
720 mut e: DiagnosticBuilder<'a>,
722 ) -> PResult<'a, ()> {
723 if let ExprKind::Binary(binop, _, _) = &expr.kind {
724 if let ast::BinOpKind::Lt = binop.node {
725 if self.eat(&token::Comma) {
726 let x = self.parse_seq_to_before_end(
728 SeqSep::trailing_allowed(token::Comma),
729 |p| p.parse_generic_arg(None),
732 Ok((_, _, false)) => {
733 if self.eat(&token::Gt) {
734 match self.parse_expr() {
736 e.span_suggestion_verbose(
737 binop.span.shrink_to_lo(),
738 TURBOFISH_SUGGESTION_STR,
740 Applicability::MaybeIncorrect,
744 self.mk_expr_err(expr.span.to(self.prev_token.span));
764 /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
765 /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
766 /// parenthesising the leftmost comparison.
767 fn attempt_chained_comparison_suggestion(
769 err: &mut DiagnosticBuilder<'_>,
771 outer_op: &Spanned<AssocOp>,
772 ) -> bool /* advanced the cursor */ {
773 if let ExprKind::Binary(op, ref l1, ref r1) = inner_op.kind {
774 if let ExprKind::Field(_, ident) = l1.kind {
775 if ident.as_str().parse::<i32>().is_err() && !matches!(r1.kind, ExprKind::Lit(_)) {
776 // The parser has encountered `foo.bar<baz`, the likelihood of the turbofish
777 // suggestion being the only one to apply is high.
781 let mut enclose = |left: Span, right: Span| {
782 err.multipart_suggestion(
783 "parenthesize the comparison",
785 (left.shrink_to_lo(), "(".to_string()),
786 (right.shrink_to_hi(), ")".to_string()),
788 Applicability::MaybeIncorrect,
791 return match (op.node, &outer_op.node) {
793 (BinOpKind::Eq, AssocOp::Equal) |
794 // `x < y < z` and friends.
795 (BinOpKind::Lt, AssocOp::Less | AssocOp::LessEqual) |
796 (BinOpKind::Le, AssocOp::LessEqual | AssocOp::Less) |
797 // `x > y > z` and friends.
798 (BinOpKind::Gt, AssocOp::Greater | AssocOp::GreaterEqual) |
799 (BinOpKind::Ge, AssocOp::GreaterEqual | AssocOp::Greater) => {
800 let expr_to_str = |e: &Expr| {
801 self.span_to_snippet(e.span)
802 .unwrap_or_else(|_| pprust::expr_to_string(&e))
804 err.span_suggestion_verbose(
805 inner_op.span.shrink_to_hi(),
806 "split the comparison into two",
807 format!(" && {}", expr_to_str(&r1)),
808 Applicability::MaybeIncorrect,
810 false // Keep the current parse behavior, where the AST is `(x < y) < z`.
813 (BinOpKind::Eq, AssocOp::Less | AssocOp::LessEqual | AssocOp::Greater | AssocOp::GreaterEqual) => {
814 // Consume `z`/outer-op-rhs.
815 let snapshot = self.clone();
816 match self.parse_expr() {
818 // We are sure that outer-op-rhs could be consumed, the suggestion is
820 enclose(r1.span, r2.span);
823 Err(mut expr_err) => {
831 (BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge, AssocOp::Equal) => {
832 let snapshot = self.clone();
833 // At this point it is always valid to enclose the lhs in parentheses, no
834 // further checks are necessary.
835 match self.parse_expr() {
837 enclose(l1.span, r1.span);
840 Err(mut expr_err) => {
853 /// Produces an error if comparison operators are chained (RFC #558).
854 /// We only need to check the LHS, not the RHS, because all comparison ops have same
855 /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
857 /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
858 /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
861 /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
862 /// associative we can infer that we have:
871 pub(super) fn check_no_chained_comparison(
874 outer_op: &Spanned<AssocOp>,
875 ) -> PResult<'a, Option<P<Expr>>> {
877 outer_op.node.is_comparison(),
878 "check_no_chained_comparison: {:?} is not comparison",
883 |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err, AttrVec::new())));
885 match inner_op.kind {
886 ExprKind::Binary(op, ref l1, ref r1) if op.node.is_comparison() => {
887 let mut err = self.struct_span_err(
888 vec![op.span, self.prev_token.span],
889 "comparison operators cannot be chained",
892 let suggest = |err: &mut DiagnosticBuilder<'_>| {
893 err.span_suggestion_verbose(
894 op.span.shrink_to_lo(),
895 TURBOFISH_SUGGESTION_STR,
897 Applicability::MaybeIncorrect,
901 // Include `<` to provide this recommendation even in a case like
902 // `Foo<Bar<Baz<Qux, ()>>>`
903 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Less
904 || outer_op.node == AssocOp::Greater
906 if outer_op.node == AssocOp::Less {
907 let snapshot = self.clone();
909 // So far we have parsed `foo<bar<`, consume the rest of the type args.
911 [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
912 self.consume_tts(1, &modifiers);
914 if !&[token::OpenDelim(token::Paren), token::ModSep]
915 .contains(&self.token.kind)
917 // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
918 // parser and bail out.
919 *self = snapshot.clone();
922 return if token::ModSep == self.token.kind {
923 // We have some certainty that this was a bad turbofish at this point.
927 let snapshot = self.clone();
930 // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
931 match self.parse_expr() {
933 // 99% certain that the suggestion is correct, continue parsing.
935 // FIXME: actually check that the two expressions in the binop are
936 // paths and resynthesize new fn call expression instead of using
937 // `ExprKind::Err` placeholder.
938 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
940 Err(mut expr_err) => {
942 // Not entirely sure now, but we bubble the error up with the
948 } else if token::OpenDelim(token::Paren) == self.token.kind {
949 // We have high certainty that this was a bad turbofish at this point.
952 // Consume the fn call arguments.
953 match self.consume_fn_args() {
957 // FIXME: actually check that the two expressions in the binop are
958 // paths and resynthesize new fn call expression instead of using
959 // `ExprKind::Err` placeholder.
960 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
964 if !matches!(l1.kind, ExprKind::Lit(_))
965 && !matches!(r1.kind, ExprKind::Lit(_))
967 // All we know is that this is `foo < bar >` and *nothing* else. Try to
968 // be helpful, but don't attempt to recover.
969 err.help(TURBOFISH_SUGGESTION_STR);
970 err.help("or use `(...)` if you meant to specify fn arguments");
973 // If it looks like a genuine attempt to chain operators (as opposed to a
974 // misformatted turbofish, for instance), suggest a correct form.
975 if self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op)
978 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
980 // These cases cause too many knock-down errors, bail out (#61329).
986 self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
989 return mk_err_expr(self, inner_op.span.to(self.prev_token.span));
997 fn consume_fn_args(&mut self) -> Result<(), ()> {
998 let snapshot = self.clone();
1001 // Consume the fn call arguments.
1003 [(token::OpenDelim(token::Paren), 1), (token::CloseDelim(token::Paren), -1)];
1004 self.consume_tts(1, &modifiers);
1006 if self.token.kind == token::Eof {
1007 // Not entirely sure that what we consumed were fn arguments, rollback.
1011 // 99% certain that the suggestion is correct, continue parsing.
1016 pub(super) fn maybe_report_ambiguous_plus(
1018 allow_plus: AllowPlus,
1019 impl_dyn_multi: bool,
1022 if matches!(allow_plus, AllowPlus::No) && impl_dyn_multi {
1023 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1024 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1027 "use parentheses to disambiguate",
1029 Applicability::MachineApplicable,
1035 /// Swift lets users write `Ty?` to mean `Option<Ty>`. Parse the construct and recover from it.
1036 pub(super) fn maybe_recover_from_question_mark(
1039 is_as_cast: IsAsCast,
1041 if let IsAsCast::Yes = is_as_cast {
1044 if self.token == token::Question {
1046 self.struct_span_err(self.prev_token.span, "invalid `?` in type")
1047 .span_label(self.prev_token.span, "`?` is only allowed on expressions, not types")
1048 .multipart_suggestion(
1049 "if you meant to express that the type might not contain a value, use the `Option` wrapper type",
1051 (ty.span.shrink_to_lo(), "Option<".to_string()),
1052 (self.prev_token.span, ">".to_string()),
1054 Applicability::MachineApplicable,
1057 self.mk_ty(ty.span.to(self.prev_token.span), TyKind::Err)
1063 pub(super) fn maybe_recover_from_bad_type_plus(
1065 allow_plus: AllowPlus,
1067 ) -> PResult<'a, ()> {
1068 // Do not add `+` to expected tokens.
1069 if matches!(allow_plus, AllowPlus::No) || !self.token.is_like_plus() {
1074 let bounds = self.parse_generic_bounds(None)?;
1075 let sum_span = ty.span.to(self.prev_token.span);
1077 let mut err = struct_span_err!(
1078 self.sess.span_diagnostic,
1081 "expected a path on the left-hand side of `+`, not `{}`",
1082 pprust::ty_to_string(ty)
1086 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1087 let sum_with_parens = pprust::to_string(|s| {
1089 s.print_opt_lifetime(lifetime);
1090 s.print_mutability(mut_ty.mutbl, false);
1092 s.print_type(&mut_ty.ty);
1093 s.print_type_bounds(" +", &bounds);
1096 err.span_suggestion(
1098 "try adding parentheses",
1100 Applicability::MachineApplicable,
1103 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1104 err.span_label(sum_span, "perhaps you forgot parentheses?");
1107 err.span_label(sum_span, "expected a path");
1114 /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
1115 /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
1116 /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
1117 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
1120 allow_recovery: bool,
1121 ) -> PResult<'a, P<T>> {
1122 // Do not add `::` to expected tokens.
1123 if allow_recovery && self.token == token::ModSep {
1124 if let Some(ty) = base.to_ty() {
1125 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1131 /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
1132 /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
1133 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
1137 ) -> PResult<'a, P<T>> {
1138 self.expect(&token::ModSep)?;
1140 let mut path = ast::Path { segments: Vec::new(), span: DUMMY_SP, tokens: None };
1141 self.parse_path_segments(&mut path.segments, T::PATH_STYLE, None)?;
1142 path.span = ty_span.to(self.prev_token.span);
1144 let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
1145 self.struct_span_err(path.span, "missing angle brackets in associated item path")
1147 // This is a best-effort recovery.
1150 format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
1151 Applicability::MaybeIncorrect,
1155 let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
1156 Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path)))
1159 pub fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
1160 if self.token.kind == TokenKind::Semi {
1162 let mut err = self.struct_span_err(self.prev_token.span, "expected item, found `;`");
1163 err.span_suggestion_short(
1164 self.prev_token.span,
1165 "remove this semicolon",
1167 Applicability::MachineApplicable,
1169 if !items.is_empty() {
1170 let previous_item = &items[items.len() - 1];
1171 let previous_item_kind_name = match previous_item.kind {
1172 // Say "braced struct" because tuple-structs and
1173 // braceless-empty-struct declarations do take a semicolon.
1174 ItemKind::Struct(..) => Some("braced struct"),
1175 ItemKind::Enum(..) => Some("enum"),
1176 ItemKind::Trait(..) => Some("trait"),
1177 ItemKind::Union(..) => Some("union"),
1180 if let Some(name) = previous_item_kind_name {
1181 err.help(&format!("{} declarations are not followed by a semicolon", name));
1191 /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
1192 /// closing delimiter.
1193 pub(super) fn unexpected_try_recover(
1196 ) -> PResult<'a, bool /* recovered */> {
1197 let token_str = pprust::token_kind_to_string(t);
1198 let this_token_str = super::token_descr(&self.token);
1199 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1200 // Point at the end of the macro call when reaching end of macro arguments.
1201 (token::Eof, Some(_)) => {
1202 let sp = self.sess.source_map().next_point(self.prev_token.span);
1205 // We don't want to point at the following span after DUMMY_SP.
1206 // This happens when the parser finds an empty TokenStream.
1207 _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
1208 // EOF, don't want to point at the following char, but rather the last token.
1209 (token::Eof, None) => (self.prev_token.span, self.token.span),
1210 _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
1213 "expected `{}`, found {}",
1215 match (&self.token.kind, self.subparser_name) {
1216 (token::Eof, Some(origin)) => format!("end of {}", origin),
1217 _ => this_token_str,
1220 let mut err = self.struct_span_err(sp, &msg);
1221 let label_exp = format!("expected `{}`", token_str);
1222 match self.recover_closing_delimiter(&[t.clone()], err) {
1225 return Ok(recovered);
1228 let sm = self.sess.source_map();
1229 if !sm.is_multiline(prev_sp.until(sp)) {
1230 // When the spans are in the same line, it means that the only content
1231 // between them is whitespace, point only at the found token.
1232 err.span_label(sp, label_exp);
1234 err.span_label(prev_sp, label_exp);
1235 err.span_label(sp, "unexpected token");
1240 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1241 if self.eat(&token::Semi) {
1244 self.expect(&token::Semi).map(drop) // Error unconditionally
1247 /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
1248 /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
1249 pub(super) fn recover_incorrect_await_syntax(
1254 ) -> PResult<'a, P<Expr>> {
1255 let (hi, expr, is_question) = if self.token == token::Not {
1256 // Handle `await!(<expr>)`.
1257 self.recover_await_macro()?
1259 self.recover_await_prefix(await_sp)?
1261 let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
1262 let kind = match expr.kind {
1263 // Avoid knock-down errors as we don't know whether to interpret this as `foo().await?`
1264 // or `foo()?.await` (the very reason we went with postfix syntax 😅).
1265 ExprKind::Try(_) => ExprKind::Err,
1266 _ => ExprKind::Await(expr),
1268 let expr = self.mk_expr(lo.to(sp), kind, attrs);
1269 self.maybe_recover_from_bad_qpath(expr, true)
1272 fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1273 self.expect(&token::Not)?;
1274 self.expect(&token::OpenDelim(token::Paren))?;
1275 let expr = self.parse_expr()?;
1276 self.expect(&token::CloseDelim(token::Paren))?;
1277 Ok((self.prev_token.span, expr, false))
1280 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
1281 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
1282 let expr = if self.token == token::OpenDelim(token::Brace) {
1283 // Handle `await { <expr> }`.
1284 // This needs to be handled separately from the next arm to avoid
1285 // interpreting `await { <expr> }?` as `<expr>?.await`.
1286 self.parse_block_expr(None, self.token.span, BlockCheckMode::Default, AttrVec::new())
1290 .map_err(|mut err| {
1291 err.span_label(await_sp, "while parsing this incorrect await expression");
1294 Ok((expr.span, expr, is_question))
1297 fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
1299 self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr));
1300 let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" });
1302 let app = match expr.kind {
1303 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
1304 _ => Applicability::MachineApplicable,
1306 self.struct_span_err(sp, "incorrect use of `await`")
1307 .span_suggestion(sp, "`await` is a postfix operation", suggestion, app)
1312 /// If encountering `future.await()`, consumes and emits an error.
1313 pub(super) fn recover_from_await_method_call(&mut self) {
1314 if self.token == token::OpenDelim(token::Paren)
1315 && self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren))
1318 let lo = self.token.span;
1320 let sp = lo.to(self.token.span);
1322 self.struct_span_err(sp, "incorrect use of `await`")
1325 "`await` is not a method call, remove the parentheses",
1327 Applicability::MachineApplicable,
1333 pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, P<Expr>> {
1334 let is_try = self.token.is_keyword(kw::Try);
1335 let is_questionmark = self.look_ahead(1, |t| t == &token::Not); //check for !
1336 let is_open = self.look_ahead(2, |t| t == &token::OpenDelim(token::Paren)); //check for (
1338 if is_try && is_questionmark && is_open {
1339 let lo = self.token.span;
1340 self.bump(); //remove try
1341 self.bump(); //remove !
1342 let try_span = lo.to(self.token.span); //we take the try!( span
1343 self.bump(); //remove (
1344 let is_empty = self.token == token::CloseDelim(token::Paren); //check if the block is empty
1345 self.consume_block(token::Paren, ConsumeClosingDelim::No); //eat the block
1346 let hi = self.token.span;
1347 self.bump(); //remove )
1348 let mut err = self.struct_span_err(lo.to(hi), "use of deprecated `try` macro");
1349 err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
1350 let prefix = if is_empty { "" } else { "alternatively, " };
1352 err.multipart_suggestion(
1353 "you can use the `?` operator instead",
1354 vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
1355 Applicability::MachineApplicable,
1358 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);
1360 Ok(self.mk_expr_err(lo.to(hi)))
1362 Err(self.expected_expression_found()) // The user isn't trying to invoke the try! macro
1366 /// Recovers a situation like `for ( $pat in $expr )`
1367 /// and suggest writing `for $pat in $expr` instead.
1369 /// This should be called before parsing the `$block`.
1370 pub(super) fn recover_parens_around_for_head(
1373 begin_paren: Option<Span>,
1375 match (&self.token.kind, begin_paren) {
1376 (token::CloseDelim(token::Paren), Some(begin_par_sp)) => {
1379 self.struct_span_err(
1380 MultiSpan::from_spans(vec![begin_par_sp, self.prev_token.span]),
1381 "unexpected parentheses surrounding `for` loop head",
1383 .multipart_suggestion(
1384 "remove parentheses in `for` loop",
1385 vec![(begin_par_sp, String::new()), (self.prev_token.span, String::new())],
1386 // With e.g. `for (x) in y)` this would replace `(x) in y)`
1387 // with `x) in y)` which is syntactically invalid.
1388 // However, this is prevented before we get here.
1389 Applicability::MachineApplicable,
1393 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1394 pat.and_then(|pat| match pat.kind {
1395 PatKind::Paren(pat) => pat,
1403 pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1404 (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1405 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1406 || self.token.is_ident() &&
1407 matches!(node, ast::ExprKind::Path(..) | ast::ExprKind::Field(..)) &&
1408 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
1409 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren))
1410 || self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) // `foo:bar {`
1411 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar::<baz`
1412 self.look_ahead(2, |t| t == &token::Lt) &&
1413 self.look_ahead(3, |t| t.is_ident())
1414 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
1415 self.look_ahead(2, |t| t.is_ident())
1416 || self.look_ahead(1, |t| t == &token::ModSep)
1417 && (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
1418 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1421 pub(super) fn recover_seq_parse_error(
1423 delim: token::DelimToken,
1425 result: PResult<'a, P<Expr>>,
1431 // Recover from parse error, callers expect the closing delim to be consumed.
1432 self.consume_block(delim, ConsumeClosingDelim::Yes);
1433 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err, AttrVec::new())
1438 pub(super) fn recover_closing_delimiter(
1440 tokens: &[TokenKind],
1441 mut err: DiagnosticBuilder<'a>,
1442 ) -> PResult<'a, bool> {
1444 // We want to use the last closing delim that would apply.
1445 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1446 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1447 && Some(self.token.span) > unmatched.unclosed_span
1454 // Recover and assume that the detected unclosed delimiter was meant for
1455 // this location. Emit the diagnostic and act as if the delimiter was
1456 // present for the parser's sake.
1458 // Don't attempt to recover from this unclosed delimiter more than once.
1459 let unmatched = self.unclosed_delims.remove(pos);
1460 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1461 if unmatched.found_delim.is_none() {
1462 // We encountered `Eof`, set this fact here to avoid complaining about missing
1463 // `fn main()` when we found place to suggest the closing brace.
1464 *self.sess.reached_eof.borrow_mut() = true;
1467 // We want to suggest the inclusion of the closing delimiter where it makes
1468 // the most sense, which is immediately after the last token:
1473 // | help: `)` may belong here
1475 // unclosed delimiter
1476 if let Some(sp) = unmatched.unclosed_span {
1477 let mut primary_span: Vec<Span> =
1478 err.span.primary_spans().iter().cloned().collect();
1479 primary_span.push(sp);
1480 let mut primary_span: MultiSpan = primary_span.into();
1481 for span_label in err.span.span_labels() {
1482 if let Some(label) = span_label.label {
1483 primary_span.push_span_label(span_label.span, label);
1486 err.set_span(primary_span);
1487 err.span_label(sp, "unclosed delimiter");
1489 // Backticks should be removed to apply suggestions.
1490 let mut delim = delim.to_string();
1491 delim.retain(|c| c != '`');
1492 err.span_suggestion_short(
1493 self.prev_token.span.shrink_to_hi(),
1494 &format!("`{}` may belong here", delim),
1496 Applicability::MaybeIncorrect,
1498 if unmatched.found_delim.is_none() {
1499 // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1500 // errors which would be emitted elsewhere in the parser and let other error
1501 // recovery consume the rest of the file.
1505 self.expected_tokens.clear(); // Reduce the number of errors.
1513 /// Eats tokens until we can be relatively sure we reached the end of the
1514 /// statement. This is something of a best-effort heuristic.
1516 /// We terminate when we find an unmatched `}` (without consuming it).
1517 pub(super) fn recover_stmt(&mut self) {
1518 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1521 /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1522 /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1523 /// approximate -- it can mean we break too early due to macros, but that
1524 /// should only lead to sub-optimal recovery, not inaccurate parsing).
1526 /// If `break_on_block` is `Break`, then we will stop consuming tokens
1527 /// after finding (and consuming) a brace-delimited block.
1528 pub(super) fn recover_stmt_(
1530 break_on_semi: SemiColonMode,
1531 break_on_block: BlockMode,
1533 let mut brace_depth = 0;
1534 let mut bracket_depth = 0;
1535 let mut in_block = false;
1536 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1538 debug!("recover_stmt_ loop {:?}", self.token);
1539 match self.token.kind {
1540 token::OpenDelim(token::DelimToken::Brace) => {
1543 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1548 token::OpenDelim(token::DelimToken::Bracket) => {
1552 token::CloseDelim(token::DelimToken::Brace) => {
1553 if brace_depth == 0 {
1554 debug!("recover_stmt_ return - close delim {:?}", self.token);
1559 if in_block && bracket_depth == 0 && brace_depth == 0 {
1560 debug!("recover_stmt_ return - block end {:?}", self.token);
1564 token::CloseDelim(token::DelimToken::Bracket) => {
1566 if bracket_depth < 0 {
1572 debug!("recover_stmt_ return - Eof");
1577 if break_on_semi == SemiColonMode::Break
1579 && bracket_depth == 0
1581 debug!("recover_stmt_ return - Semi");
1586 if break_on_semi == SemiColonMode::Comma
1588 && bracket_depth == 0 =>
1590 debug!("recover_stmt_ return - Semi");
1598 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1599 if self.eat_keyword(kw::In) {
1600 // a common typo: `for _ in in bar {}`
1601 self.struct_span_err(self.prev_token.span, "expected iterable, found keyword `in`")
1602 .span_suggestion_short(
1603 in_span.until(self.prev_token.span),
1604 "remove the duplicated `in`",
1606 Applicability::MachineApplicable,
1612 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1613 if let token::DocComment(..) = self.token.kind {
1614 self.struct_span_err(
1616 "documentation comments cannot be applied to a function parameter's type",
1618 .span_label(self.token.span, "doc comments are not allowed here")
1621 } else if self.token == token::Pound
1622 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Bracket))
1624 let lo = self.token.span;
1625 // Skip every token until next possible arg.
1626 while self.token != token::CloseDelim(token::Bracket) {
1629 let sp = lo.to(self.token.span);
1631 self.struct_span_err(sp, "attributes cannot be applied to a function parameter's type")
1632 .span_label(sp, "attributes are not allowed here")
1637 pub(super) fn parameter_without_type(
1639 err: &mut DiagnosticBuilder<'_>,
1643 ) -> Option<Ident> {
1644 // If we find a pattern followed by an identifier, it could be an (incorrect)
1645 // C-style parameter declaration.
1646 if self.check_ident()
1647 && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseDelim(token::Paren))
1649 // `fn foo(String s) {}`
1650 let ident = self.parse_ident().unwrap();
1651 let span = pat.span.with_hi(ident.span.hi());
1653 err.span_suggestion(
1655 "declare the type after the parameter binding",
1656 String::from("<identifier>: <type>"),
1657 Applicability::HasPlaceholders,
1660 } else if require_name
1661 && (self.token == token::Comma
1662 || self.token == token::Lt
1663 || self.token == token::CloseDelim(token::Paren))
1665 let rfc_note = "anonymous parameters are removed in the 2018 edition (see RFC 1685)";
1667 let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
1669 PatKind::Ident(_, ident, _) => (
1671 "self: ".to_string(),
1672 ": TypeName".to_string(),
1674 pat.span.shrink_to_lo(),
1675 pat.span.shrink_to_hi(),
1676 pat.span.shrink_to_lo(),
1678 // Also catches `fn foo(&a)`.
1679 PatKind::Ref(ref inner_pat, mutab)
1680 if matches!(inner_pat.clone().into_inner().kind, PatKind::Ident(..)) =>
1682 match inner_pat.clone().into_inner().kind {
1683 PatKind::Ident(_, ident, _) => {
1684 let mutab = mutab.prefix_str();
1687 "self: ".to_string(),
1688 format!("{}: &{}TypeName", ident, mutab),
1690 pat.span.shrink_to_lo(),
1692 pat.span.shrink_to_lo(),
1695 _ => unreachable!(),
1699 // Otherwise, try to get a type and emit a suggestion.
1700 if let Some(ty) = pat.to_ty() {
1701 err.span_suggestion_verbose(
1703 "explicitly ignore the parameter name",
1704 format!("_: {}", pprust::ty_to_string(&ty)),
1705 Applicability::MachineApplicable,
1714 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1716 err.span_suggestion(
1718 "if this is a `self` type, give it a parameter name",
1720 Applicability::MaybeIncorrect,
1723 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
1724 // `fn foo(HashMap: TypeName<u32>)`.
1725 if self.token != token::Lt {
1726 err.span_suggestion(
1728 "if this is a parameter name, give it a type",
1730 Applicability::HasPlaceholders,
1733 err.span_suggestion(
1735 "if this is a type, explicitly ignore the parameter name",
1737 Applicability::MachineApplicable,
1741 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
1742 return if self.token == token::Lt { None } else { Some(ident) };
1747 pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
1748 let pat = self.parse_pat_no_top_alt(Some("argument name"))?;
1749 self.expect(&token::Colon)?;
1750 let ty = self.parse_ty()?;
1756 "patterns aren't allowed in methods without bodies",
1758 .span_suggestion_short(
1760 "give this argument a name or use an underscore to ignore it",
1762 Applicability::MachineApplicable,
1766 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1768 P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID, tokens: None });
1772 pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
1773 let sp = param.pat.span;
1774 param.ty.kind = TyKind::Err;
1775 self.struct_span_err(sp, "unexpected `self` parameter in function")
1776 .span_label(sp, "must be the first parameter of an associated function")
1781 pub(super) fn consume_block(
1783 delim: token::DelimToken,
1784 consume_close: ConsumeClosingDelim,
1786 let mut brace_depth = 0;
1788 if self.eat(&token::OpenDelim(delim)) {
1790 } else if self.check(&token::CloseDelim(delim)) {
1791 if brace_depth == 0 {
1792 if let ConsumeClosingDelim::Yes = consume_close {
1793 // Some of the callers of this method expect to be able to parse the
1794 // closing delimiter themselves, so we leave it alone. Otherwise we advance
1804 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
1812 pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a> {
1813 let (span, msg) = match (&self.token.kind, self.subparser_name) {
1814 (&token::Eof, Some(origin)) => {
1815 let sp = self.sess.source_map().next_point(self.prev_token.span);
1816 (sp, format!("expected expression, found end of {}", origin))
1820 format!("expected expression, found {}", super::token_descr(&self.token),),
1823 let mut err = self.struct_span_err(span, &msg);
1824 let sp = self.sess.source_map().start_point(self.token.span);
1825 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
1826 self.sess.expr_parentheses_needed(&mut err, *sp);
1828 err.span_label(span, "expected expression");
1834 mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
1835 // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
1836 modifier: &[(token::TokenKind, i64)],
1839 if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
1842 if self.token.kind == token::Eof {
1849 /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
1851 /// This is necessary because at this point we don't know whether we parsed a function with
1852 /// anonymous parameters or a function with names but no types. In order to minimize
1853 /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
1854 /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
1855 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
1856 /// we deduplicate them to not complain about duplicated parameter names.
1857 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
1858 let mut seen_inputs = FxHashSet::default();
1859 for input in fn_inputs.iter_mut() {
1860 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
1861 (&input.pat.kind, &input.ty.kind)
1867 if let Some(ident) = opt_ident {
1868 if seen_inputs.contains(&ident) {
1869 input.pat.kind = PatKind::Wild;
1871 seen_inputs.insert(ident);
1876 /// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
1877 /// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
1878 /// like the user has forgotten them.
1879 pub fn handle_ambiguous_unbraced_const_arg(
1881 args: &mut Vec<AngleBracketedArg>,
1882 ) -> PResult<'a, bool> {
1883 // If we haven't encountered a closing `>`, then the argument is malformed.
1884 // It's likely that the user has written a const expression without enclosing it
1885 // in braces, so we try to recover here.
1886 let arg = args.pop().unwrap();
1887 // FIXME: for some reason using `unexpected` or `expected_one_of_not_found` has
1888 // adverse side-effects to subsequent errors and seems to advance the parser.
1889 // We are causing this error here exclusively in case that a `const` expression
1890 // could be recovered from the current parser state, even if followed by more
1891 // arguments after a comma.
1892 let mut err = self.struct_span_err(
1894 &format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
1896 err.span_label(self.token.span, "expected one of `,` or `>`");
1897 match self.recover_const_arg(arg.span(), err) {
1899 args.push(AngleBracketedArg::Arg(arg));
1900 if self.eat(&token::Comma) {
1901 return Ok(true); // Continue
1906 // We will emit a more generic error later.
1910 return Ok(false); // Don't continue.
1913 /// Attempt to parse a generic const argument that has not been enclosed in braces.
1914 /// There are a limited number of expressions that are permitted without being encoded
1917 /// - Single-segment paths (i.e. standalone generic const parameters).
1918 /// All other expressions that can be parsed will emit an error suggesting the expression be
1919 /// wrapped in braces.
1920 pub fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
1921 let start = self.token.span;
1922 let expr = self.parse_expr_res(Restrictions::CONST_EXPR, None).map_err(|mut err| {
1924 start.shrink_to_lo(),
1925 "while parsing a const generic argument starting here",
1929 if !self.expr_is_valid_const_arg(&expr) {
1930 self.struct_span_err(
1932 "expressions must be enclosed in braces to be used as const generic \
1935 .multipart_suggestion(
1936 "enclose the `const` expression in braces",
1938 (expr.span.shrink_to_lo(), "{ ".to_string()),
1939 (expr.span.shrink_to_hi(), " }".to_string()),
1941 Applicability::MachineApplicable,
1948 fn recover_const_param_decl(
1950 ty_generics: Option<&Generics>,
1951 ) -> PResult<'a, Option<GenericArg>> {
1952 let snapshot = self.clone();
1953 let param = match self.parse_const_param(vec![]) {
1962 self.struct_span_err(param.span(), "unexpected `const` parameter declaration");
1963 err.span_label(param.span(), "expected a `const` expression, not a parameter declaration");
1964 if let (Some(generics), Ok(snippet)) =
1965 (ty_generics, self.sess.source_map().span_to_snippet(param.span()))
1967 let (span, sugg) = match &generics.params[..] {
1968 [] => (generics.span, format!("<{}>", snippet)),
1969 [.., generic] => (generic.span().shrink_to_hi(), format!(", {}", snippet)),
1971 err.multipart_suggestion(
1972 "`const` parameters must be declared for the `impl`",
1973 vec![(span, sugg), (param.span(), param.ident.to_string())],
1974 Applicability::MachineApplicable,
1977 let value = self.mk_expr_err(param.span());
1979 return Ok(Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })));
1982 pub fn recover_const_param_declaration(
1984 ty_generics: Option<&Generics>,
1985 ) -> PResult<'a, Option<GenericArg>> {
1986 // We have to check for a few different cases.
1987 if let Ok(arg) = self.recover_const_param_decl(ty_generics) {
1991 // We haven't consumed `const` yet.
1992 let start = self.token.span;
1993 self.bump(); // `const`
1995 // Detect and recover from the old, pre-RFC2000 syntax for const generics.
1997 .struct_span_err(start, "expected lifetime, type, or constant, found keyword `const`");
1998 if self.check_const_arg() {
1999 err.span_suggestion_verbose(
2000 start.until(self.token.span),
2001 "the `const` keyword is only needed in the definition of the type",
2003 Applicability::MaybeIncorrect,
2006 Ok(Some(GenericArg::Const(self.parse_const_arg()?)))
2008 let after_kw_const = self.token.span;
2009 self.recover_const_arg(after_kw_const, err).map(Some)
2013 /// Try to recover from possible generic const argument without `{` and `}`.
2015 /// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
2016 /// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
2017 /// if we think that that the resulting expression would be well formed.
2018 pub fn recover_const_arg(
2021 mut err: DiagnosticBuilder<'a>,
2022 ) -> PResult<'a, GenericArg> {
2023 let is_op = AssocOp::from_token(&self.token)
2025 if let AssocOp::Greater
2027 | AssocOp::ShiftRight
2028 | AssocOp::GreaterEqual
2029 // Don't recover from `foo::<bar = baz>`, because this could be an attempt to
2030 // assign a value to a defaulted generic parameter.
2032 | AssocOp::AssignOp(_) = op
2040 // This will be true when a trait object type `Foo +` or a path which was a `const fn` with
2041 // type params has been parsed.
2043 matches!(self.prev_token.kind, token::BinOp(token::Plus | token::Shr) | token::Gt);
2044 if !is_op && !was_op {
2045 // We perform these checks and early return to avoid taking a snapshot unnecessarily.
2048 let snapshot = self.clone();
2052 match self.parse_expr_res(Restrictions::CONST_EXPR, None) {
2054 // Find a mistake like `MyTrait<Assoc == S::Assoc>`.
2055 if token::EqEq == snapshot.token.kind {
2056 err.span_suggestion(
2057 snapshot.token.span,
2058 "if you meant to use an associated type binding, replace `==` with `=`",
2060 Applicability::MaybeIncorrect,
2062 let value = self.mk_expr_err(start.to(expr.span));
2064 return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
2065 } else if token::Comma == self.token.kind || self.token.kind.should_end_const_arg()
2067 // Avoid the following output by checking that we consumed a full const arg:
2068 // help: expressions must be enclosed in braces to be used as const generic
2071 // LL | let sr: Vec<{ (u32, _, _) = vec![] };
2073 err.multipart_suggestion(
2074 "expressions must be enclosed in braces to be used as const generic \
2077 (start.shrink_to_lo(), "{ ".to_string()),
2078 (expr.span.shrink_to_hi(), " }".to_string()),
2080 Applicability::MaybeIncorrect,
2082 let value = self.mk_expr_err(start.to(expr.span));
2084 return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
2095 /// Get the diagnostics for the cases where `move async` is found.
2097 /// `move_async_span` starts at the 'm' of the move keyword and ends with the 'c' of the async keyword
2098 pub(super) fn incorrect_move_async_order_found(
2100 move_async_span: Span,
2101 ) -> DiagnosticBuilder<'a> {
2103 self.struct_span_err(move_async_span, "the order of `move` and `async` is incorrect");
2104 err.span_suggestion_verbose(
2106 "try switching the order",
2107 "async move".to_owned(),
2108 Applicability::MaybeIncorrect,
2113 /// Some special error handling for the "top-level" patterns in a match arm,
2114 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2115 crate fn maybe_recover_colon_colon_in_pat_typo(
2117 mut first_pat: P<Pat>,
2121 if RecoverColon::Yes != ra || token::Colon != self.token.kind {
2124 if !matches!(first_pat.kind, PatKind::Ident(_, _, None) | PatKind::Path(..))
2125 || !self.look_ahead(1, |token| token.is_ident() && !token.is_reserved_ident())
2129 // The pattern looks like it might be a path with a `::` -> `:` typo:
2130 // `match foo { bar:baz => {} }`
2131 let span = self.token.span;
2132 // We only emit "unexpected `:`" error here if we can successfully parse the
2133 // whole pattern correctly in that case.
2134 let snapshot = self.clone();
2136 // Create error for "unexpected `:`".
2137 match self.expected_one_of_not_found(&[], &[]) {
2139 self.bump(); // Skip the `:`.
2140 match self.parse_pat_no_top_alt(expected) {
2141 Err(mut inner_err) => {
2142 // Carry on as if we had not done anything, callers will emit a
2143 // reasonable error.
2149 // We've parsed the rest of the pattern.
2150 let new_span = first_pat.span.to(pat.span);
2151 let mut show_sugg = false;
2152 // Try to construct a recovered pattern.
2153 match &mut pat.kind {
2154 PatKind::Struct(qself @ None, path, ..)
2155 | PatKind::TupleStruct(qself @ None, path, _)
2156 | PatKind::Path(qself @ None, path) => match &first_pat.kind {
2157 PatKind::Ident(_, ident, _) => {
2158 path.segments.insert(0, PathSegment::from_ident(ident.clone()));
2159 path.span = new_span;
2163 PatKind::Path(old_qself, old_path) => {
2164 path.segments = old_path
2168 .chain(take(&mut path.segments))
2170 path.span = new_span;
2171 *qself = old_qself.clone();
2177 PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => {
2178 match &first_pat.kind {
2179 PatKind::Ident(_, old_ident, _) => {
2180 let path = PatKind::Path(
2185 PathSegment::from_ident(old_ident.clone()),
2186 PathSegment::from_ident(ident.clone()),
2191 first_pat = self.mk_pat(new_span, path);
2194 PatKind::Path(old_qself, old_path) => {
2195 let mut segments = old_path.segments.clone();
2196 segments.push(PathSegment::from_ident(ident.clone()));
2197 let path = PatKind::Path(
2199 Path { span: new_span, segments, tokens: None },
2201 first_pat = self.mk_pat(new_span, path);
2210 err.span_suggestion(
2212 "maybe write a path separator here",
2214 Applicability::MaybeIncorrect,
2217 first_pat = self.mk_pat(new_span, PatKind::Wild);
2224 // Carry on as if we had not done anything. This should be unreachable.
2231 /// Some special error handling for the "top-level" patterns in a match arm,
2232 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2233 crate fn maybe_recover_unexpected_comma(
2237 ) -> PResult<'a, ()> {
2238 if rc == RecoverComma::No || self.token != token::Comma {
2242 // An unexpected comma after a top-level pattern is a clue that the
2243 // user (perhaps more accustomed to some other language) forgot the
2244 // parentheses in what should have been a tuple pattern; return a
2245 // suggestion-enhanced error here rather than choking on the comma later.
2246 let comma_span = self.token.span;
2248 if let Err(mut err) = self.skip_pat_list() {
2249 // We didn't expect this to work anyway; we just wanted to advance to the
2250 // end of the comma-sequence so we know the span to suggest parenthesizing.
2253 let seq_span = lo.to(self.prev_token.span);
2254 let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
2255 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
2256 const MSG: &str = "try adding parentheses to match on a tuple...";
2258 err.span_suggestion(
2261 format!("({})", seq_snippet),
2262 Applicability::MachineApplicable,
2264 err.span_suggestion(
2266 "...or a vertical bar to match on multiple alternatives",
2267 seq_snippet.replace(',', " |"),
2268 Applicability::MachineApplicable,
2274 /// Parse and throw away a parenthesized comma separated
2275 /// sequence of patterns until `)` is reached.
2276 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
2277 while !self.check(&token::CloseDelim(token::Paren)) {
2278 self.parse_pat_no_top_alt(None)?;
2279 if !self.eat(&token::Comma) {