1 use super::{BlockMode, Parser, PathStyle, SemiColonMode, SeqSep, TokenExpectType, TokenType};
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_error_codes::*;
5 use rustc_errors::{pluralize, struct_span_err};
6 use rustc_errors::{Applicability, DiagnosticBuilder, Handler, PResult};
7 use rustc_span::symbol::kw;
8 use rustc_span::{MultiSpan, Span, SpanSnippetError, DUMMY_SP};
10 self, BinOpKind, BindingMode, BlockCheckMode, Expr, ExprKind, Ident, Item, Param,
12 use syntax::ast::{AttrVec, ItemKind, Mutability, Pat, PatKind, PathSegment, QSelf, Ty, TyKind};
13 use syntax::print::pprust;
15 use syntax::token::{self, token_can_begin_expr, TokenKind};
16 use syntax::util::parser::AssocOp;
18 use log::{debug, trace};
21 const TURBOFISH: &'static str = "use `::<...>` instead of `<...>` to specify type arguments";
23 /// Creates a placeholder argument.
24 pub(super) fn dummy_arg(ident: Ident) -> Param {
26 id: ast::DUMMY_NODE_ID,
27 kind: PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None),
30 let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID };
32 attrs: AttrVec::default(),
33 id: ast::DUMMY_NODE_ID,
37 is_placeholder: false,
42 FileNotFoundForModule {
45 secondary_path: String,
51 secondary_path: String,
54 InclusiveRangeWithNoEnd,
58 fn span_err(self, sp: impl Into<MultiSpan>, handler: &Handler) -> DiagnosticBuilder<'_> {
60 Error::FileNotFoundForModule {
66 let mut err = struct_span_err!(
70 "file not found for module `{}`",
74 "name the file either {} or {} inside the directory \"{}\"",
75 default_path, secondary_path, dir_path,
79 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
80 let mut err = struct_span_err!(
84 "file for module `{}` found at both {} and {}",
89 err.help("delete or rename one of them to remove the ambiguity");
92 Error::UselessDocComment => {
93 let mut err = struct_span_err!(
97 "found a documentation comment that doesn't document anything",
100 "doc comments must come before what they document, maybe a comment was \
101 intended with `//`?",
105 Error::InclusiveRangeWithNoEnd => {
106 let mut err = struct_span_err!(handler, sp, E0586, "inclusive range with no end",);
107 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
114 pub(super) trait RecoverQPath: Sized + 'static {
115 const PATH_STYLE: PathStyle = PathStyle::Expr;
116 fn to_ty(&self) -> Option<P<Ty>>;
117 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
120 impl RecoverQPath for Ty {
121 const PATH_STYLE: PathStyle = PathStyle::Type;
122 fn to_ty(&self) -> Option<P<Ty>> {
123 Some(P(self.clone()))
125 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
126 Self { span: path.span, kind: TyKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
130 impl RecoverQPath for Pat {
131 fn to_ty(&self) -> Option<P<Ty>> {
134 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
135 Self { span: path.span, kind: PatKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
139 impl RecoverQPath for Expr {
140 fn to_ty(&self) -> Option<P<Ty>> {
143 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
146 kind: ExprKind::Path(qself, path),
147 attrs: AttrVec::new(),
148 id: ast::DUMMY_NODE_ID,
153 /// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
154 crate enum ConsumeClosingDelim {
159 impl<'a> Parser<'a> {
160 pub(super) fn span_fatal_err<S: Into<MultiSpan>>(
164 ) -> DiagnosticBuilder<'a> {
165 err.span_err(sp, self.diagnostic())
168 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
169 self.sess.span_diagnostic.struct_span_err(sp, m)
172 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
173 self.sess.span_diagnostic.span_bug(sp, m)
176 pub(super) fn diagnostic(&self) -> &'a Handler {
177 &self.sess.span_diagnostic
180 pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
181 self.sess.source_map().span_to_snippet(span)
184 pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
185 let mut err = self.struct_span_err(
187 &format!("expected identifier, found {}", super::token_descr(&self.token)),
189 let valid_follow = &[
195 TokenKind::OpenDelim(token::DelimToken::Brace),
196 TokenKind::OpenDelim(token::DelimToken::Paren),
197 TokenKind::CloseDelim(token::DelimToken::Brace),
198 TokenKind::CloseDelim(token::DelimToken::Paren),
200 if let token::Ident(name, false) = self.token.kind {
201 if Ident::new(name, self.token.span).is_raw_guess()
202 && self.look_ahead(1, |t| valid_follow.contains(&t.kind))
206 "you can escape reserved keywords to use them as identifiers",
207 format!("r#{}", name),
208 Applicability::MaybeIncorrect,
212 if let Some(token_descr) = super::token_descr_opt(&self.token) {
213 err.span_label(self.token.span, format!("expected identifier, found {}", token_descr));
215 err.span_label(self.token.span, "expected identifier");
216 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
221 Applicability::MachineApplicable,
228 pub(super) fn expected_one_of_not_found(
230 edible: &[TokenKind],
231 inedible: &[TokenKind],
232 ) -> PResult<'a, bool /* recovered */> {
233 fn tokens_to_string(tokens: &[TokenType]) -> String {
234 let mut i = tokens.iter();
235 // This might be a sign we need a connect method on `Iterator`.
236 let b = i.next().map_or(String::new(), |t| t.to_string());
237 i.enumerate().fold(b, |mut b, (i, a)| {
238 if tokens.len() > 2 && i == tokens.len() - 2 {
240 } else if tokens.len() == 2 && i == tokens.len() - 2 {
245 b.push_str(&a.to_string());
250 let mut expected = edible
252 .map(|x| TokenType::Token(x.clone()))
253 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
254 .chain(self.expected_tokens.iter().cloned())
255 .collect::<Vec<_>>();
256 expected.sort_by_cached_key(|x| x.to_string());
258 let expect = tokens_to_string(&expected[..]);
259 let actual = super::token_descr(&self.token);
260 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
261 let short_expect = if expected.len() > 6 {
262 format!("{} possible tokens", expected.len())
267 format!("expected one of {}, found {}", expect, actual),
268 (self.prev_span.shrink_to_hi(), format!("expected one of {}", short_expect)),
270 } else if expected.is_empty() {
272 format!("unexpected token: {}", actual),
273 (self.prev_span, "unexpected token after this".to_string()),
277 format!("expected {}, found {}", expect, actual),
278 (self.prev_span.shrink_to_hi(), format!("expected {}", expect)),
281 self.last_unexpected_token_span = Some(self.token.span);
282 let mut err = self.struct_span_err(self.token.span, &msg_exp);
283 let sp = if self.token == token::Eof {
284 // This is EOF; don't want to point at the following char, but rather the last token.
289 match self.recover_closing_delimiter(
292 .filter_map(|tt| match tt {
293 TokenType::Token(t) => Some(t.clone()),
296 .collect::<Vec<_>>(),
301 return Ok(recovered);
305 let sm = self.sess.source_map();
306 if self.prev_span == DUMMY_SP {
307 // Account for macro context where the previous span might not be
308 // available to avoid incorrect output (#54841).
309 err.span_label(self.token.span, label_exp);
310 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
311 // When the spans are in the same line, it means that the only content between
312 // them is whitespace, point at the found token in that case:
314 // X | () => { syntax error };
315 // | ^^^^^ expected one of 8 possible tokens here
317 // instead of having:
319 // X | () => { syntax error };
320 // | -^^^^^ unexpected token
322 // | expected one of 8 possible tokens here
323 err.span_label(self.token.span, label_exp);
325 err.span_label(sp, label_exp);
326 err.span_label(self.token.span, "unexpected token");
328 self.maybe_annotate_with_ascription(&mut err, false);
332 pub fn maybe_annotate_with_ascription(
334 err: &mut DiagnosticBuilder<'_>,
335 maybe_expected_semicolon: bool,
337 if let Some((sp, likely_path)) = self.last_type_ascription.take() {
338 let sm = self.sess.source_map();
339 let next_pos = sm.lookup_char_pos(self.token.span.lo());
340 let op_pos = sm.lookup_char_pos(sp.hi());
342 let allow_unstable = self.sess.unstable_features.is_nightly_build();
347 "maybe write a path separator here",
350 Applicability::MaybeIncorrect
352 Applicability::MachineApplicable
355 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
358 "try using a semicolon",
360 Applicability::MaybeIncorrect,
362 } else if allow_unstable {
363 err.span_label(sp, "tried to parse a type due to this type ascription");
365 err.span_label(sp, "tried to parse a type due to this");
368 // Give extra information about type ascription only if it's a nightly compiler.
370 "`#![feature(type_ascription)]` lets you annotate an expression with a \
371 type: `<expr>: <type>`",
374 "for more information, see \
375 https://github.com/rust-lang/rust/issues/23416",
381 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
382 /// passes through any errors encountered. Used for error recovery.
383 pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
384 if let Err(ref mut err) =
385 self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
386 Ok(p.parse_token_tree())
393 /// This function checks if there are trailing angle brackets and produces
394 /// a diagnostic to suggest removing them.
396 /// ```ignore (diagnostic)
397 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
398 /// ^^ help: remove extra angle brackets
400 pub(super) fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: TokenKind) {
401 // This function is intended to be invoked after parsing a path segment where there are two
404 // 1. A specific token is expected after the path segment.
405 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
406 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
407 // 2. No specific token is expected after the path segment.
408 // eg. `x.foo` (field access)
410 // This function is called after parsing `.foo` and before parsing the token `end` (if
411 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
414 // We only care about trailing angle brackets if we previously parsed angle bracket
415 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
416 // removed in this case:
418 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
420 // This case is particularly tricky as we won't notice it just looking at the tokens -
421 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
422 // have already been parsed):
424 // `x.foo::<u32>>>(3)`
425 let parsed_angle_bracket_args =
426 segment.args.as_ref().map(|args| args.is_angle_bracketed()).unwrap_or(false);
429 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
430 parsed_angle_bracket_args,
432 if !parsed_angle_bracket_args {
436 // Keep the span at the start so we can highlight the sequence of `>` characters to be
438 let lo = self.token.span;
440 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
441 // (since we might have the field access case and the characters we're eating are
442 // actual operators and not trailing characters - ie `x.foo >> 3`).
443 let mut position = 0;
445 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
446 // many of each (so we can correctly pluralize our error messages) and continue to
448 let mut number_of_shr = 0;
449 let mut number_of_gt = 0;
450 while self.look_ahead(position, |t| {
451 trace!("check_trailing_angle_brackets: t={:?}", t);
452 if *t == token::BinOp(token::BinOpToken::Shr) {
455 } else if *t == token::Gt {
465 // If we didn't find any trailing `>` characters, then we have nothing to error about.
467 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
468 number_of_gt, number_of_shr,
470 if number_of_gt < 1 && number_of_shr < 1 {
474 // Finally, double check that we have our end token as otherwise this is the
476 if self.look_ahead(position, |t| {
477 trace!("check_trailing_angle_brackets: t={:?}", t);
480 // Eat from where we started until the end token so that parsing can continue
481 // as if we didn't have those extra angle brackets.
482 self.eat_to_tokens(&[&end]);
483 let span = lo.until(self.token.span);
485 let total_num_of_gt = number_of_gt + number_of_shr * 2;
486 self.struct_span_err(
488 &format!("unmatched angle bracket{}", pluralize!(total_num_of_gt)),
492 &format!("remove extra angle bracket{}", pluralize!(total_num_of_gt)),
494 Applicability::MachineApplicable,
500 /// Produces an error if comparison operators are chained (RFC #558).
501 /// We only need to check the LHS, not the RHS, because all comparison ops have same
502 /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
504 /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
505 /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
508 /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
509 /// associative we can infer that we have:
516 pub(super) fn check_no_chained_comparison(
520 ) -> PResult<'a, Option<P<Expr>>> {
522 outer_op.is_comparison(),
523 "check_no_chained_comparison: {:?} is not comparison",
528 |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err, AttrVec::new())));
531 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
532 // Respan to include both operators.
533 let op_span = op.span.to(self.prev_span);
535 .struct_span_err(op_span, "chained comparison operators require parentheses");
537 let suggest = |err: &mut DiagnosticBuilder<'_>| {
538 err.span_suggestion_verbose(
539 op_span.shrink_to_lo(),
542 Applicability::MaybeIncorrect,
546 if op.node == BinOpKind::Lt &&
547 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
548 *outer_op == AssocOp::Greater
549 // even in a case like the following:
551 // Foo<Bar<Baz<Qux, ()>>>
552 if *outer_op == AssocOp::Less {
553 let snapshot = self.clone();
555 // So far we have parsed `foo<bar<`, consume the rest of the type args.
557 [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
558 self.consume_tts(1, &modifiers[..]);
560 if !&[token::OpenDelim(token::Paren), token::ModSep]
561 .contains(&self.token.kind)
563 // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
564 // parser and bail out.
565 mem::replace(self, snapshot.clone());
568 return if token::ModSep == self.token.kind {
569 // We have some certainty that this was a bad turbofish at this point.
573 let snapshot = self.clone();
576 // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
577 match self.parse_expr() {
579 // 99% certain that the suggestion is correct, continue parsing.
581 // FIXME: actually check that the two expressions in the binop are
582 // paths and resynthesize new fn call expression instead of using
583 // `ExprKind::Err` placeholder.
584 mk_err_expr(self, lhs.span.to(self.prev_span))
586 Err(mut expr_err) => {
588 // Not entirely sure now, but we bubble the error up with the
590 mem::replace(self, snapshot);
594 } else if token::OpenDelim(token::Paren) == self.token.kind {
595 // We have high certainty that this was a bad turbofish at this point.
598 // Consume the fn call arguments.
599 match self.consume_fn_args() {
603 // FIXME: actually check that the two expressions in the binop are
604 // paths and resynthesize new fn call expression instead of using
605 // `ExprKind::Err` placeholder.
606 mk_err_expr(self, lhs.span.to(self.prev_span))
610 // All we know is that this is `foo < bar >` and *nothing* else. Try to
611 // be helpful, but don't attempt to recover.
613 err.help("or use `(...)` if you meant to specify fn arguments");
614 // These cases cause too many knock-down errors, bail out (#61329).
625 fn consume_fn_args(&mut self) -> Result<(), ()> {
626 let snapshot = self.clone();
629 // Consume the fn call arguments.
631 [(token::OpenDelim(token::Paren), 1), (token::CloseDelim(token::Paren), -1)];
632 self.consume_tts(1, &modifiers[..]);
634 if self.token.kind == token::Eof {
635 // Not entirely sure that what we consumed were fn arguments, rollback.
636 mem::replace(self, snapshot);
639 // 99% certain that the suggestion is correct, continue parsing.
644 pub(super) fn maybe_report_ambiguous_plus(
647 impl_dyn_multi: bool,
650 if !allow_plus && impl_dyn_multi {
651 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
652 self.struct_span_err(ty.span, "ambiguous `+` in a type")
655 "use parentheses to disambiguate",
657 Applicability::MachineApplicable,
663 pub(super) fn maybe_recover_from_bad_type_plus(
667 ) -> PResult<'a, ()> {
668 // Do not add `+` to expected tokens.
669 if !allow_plus || !self.token.is_like_plus() {
674 let bounds = self.parse_generic_bounds(None)?;
675 let sum_span = ty.span.to(self.prev_span);
677 let mut err = struct_span_err!(
678 self.sess.span_diagnostic,
681 "expected a path on the left-hand side of `+`, not `{}`",
682 pprust::ty_to_string(ty)
686 TyKind::Rptr(ref lifetime, ref mut_ty) => {
687 let sum_with_parens = pprust::to_string(|s| {
689 s.print_opt_lifetime(lifetime);
690 s.print_mutability(mut_ty.mutbl, false);
692 s.print_type(&mut_ty.ty);
693 s.print_type_bounds(" +", &bounds);
698 "try adding parentheses",
700 Applicability::MachineApplicable,
703 TyKind::Ptr(..) | TyKind::BareFn(..) => {
704 err.span_label(sum_span, "perhaps you forgot parentheses?");
707 err.span_label(sum_span, "expected a path");
714 /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
715 /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
716 /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
717 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
720 allow_recovery: bool,
721 ) -> PResult<'a, P<T>> {
722 // Do not add `::` to expected tokens.
723 if allow_recovery && self.token == token::ModSep {
724 if let Some(ty) = base.to_ty() {
725 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
731 /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
732 /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
733 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
737 ) -> PResult<'a, P<T>> {
738 self.expect(&token::ModSep)?;
740 let mut path = ast::Path { segments: Vec::new(), span: DUMMY_SP };
741 self.parse_path_segments(&mut path.segments, T::PATH_STYLE)?;
742 path.span = ty_span.to(self.prev_span);
744 let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
745 self.struct_span_err(path.span, "missing angle brackets in associated item path")
747 // This is a best-effort recovery.
750 format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
751 Applicability::MaybeIncorrect,
755 let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
756 Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path)))
759 pub(super) fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
760 if self.eat(&token::Semi) {
761 let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`");
762 err.span_suggestion_short(
764 "remove this semicolon",
766 Applicability::MachineApplicable,
768 if !items.is_empty() {
769 let previous_item = &items[items.len() - 1];
770 let previous_item_kind_name = match previous_item.kind {
771 // Say "braced struct" because tuple-structs and
772 // braceless-empty-struct declarations do take a semicolon.
773 ItemKind::Struct(..) => Some("braced struct"),
774 ItemKind::Enum(..) => Some("enum"),
775 ItemKind::Trait(..) => Some("trait"),
776 ItemKind::Union(..) => Some("union"),
779 if let Some(name) = previous_item_kind_name {
780 err.help(&format!("{} declarations are not followed by a semicolon", name));
790 /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
791 /// closing delimiter.
792 pub(super) fn unexpected_try_recover(
795 ) -> PResult<'a, bool /* recovered */> {
796 let token_str = pprust::token_kind_to_string(t);
797 let this_token_str = super::token_descr(&self.token);
798 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
799 // Point at the end of the macro call when reaching end of macro arguments.
800 (token::Eof, Some(_)) => {
801 let sp = self.sess.source_map().next_point(self.token.span);
804 // We don't want to point at the following span after DUMMY_SP.
805 // This happens when the parser finds an empty TokenStream.
806 _ if self.prev_span == DUMMY_SP => (self.token.span, self.token.span),
807 // EOF, don't want to point at the following char, but rather the last token.
808 (token::Eof, None) => (self.prev_span, self.token.span),
809 _ => (self.prev_span.shrink_to_hi(), self.token.span),
812 "expected `{}`, found {}",
814 match (&self.token.kind, self.subparser_name) {
815 (token::Eof, Some(origin)) => format!("end of {}", origin),
819 let mut err = self.struct_span_err(sp, &msg);
820 let label_exp = format!("expected `{}`", token_str);
821 match self.recover_closing_delimiter(&[t.clone()], err) {
824 return Ok(recovered);
827 let sm = self.sess.source_map();
828 if !sm.is_multiline(prev_sp.until(sp)) {
829 // When the spans are in the same line, it means that the only content
830 // between them is whitespace, point only at the found token.
831 err.span_label(sp, label_exp);
833 err.span_label(prev_sp, label_exp);
834 err.span_label(sp, "unexpected token");
839 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
840 if self.eat(&token::Semi) {
843 let sm = self.sess.source_map();
844 let msg = format!("expected `;`, found `{}`", super::token_descr(&self.token));
845 let appl = Applicability::MachineApplicable;
846 if self.token.span == DUMMY_SP || self.prev_span == DUMMY_SP {
847 // Likely inside a macro, can't provide meaninful suggestions.
848 return self.expect(&token::Semi).map(drop);
849 } else if !sm.is_multiline(self.prev_span.until(self.token.span)) {
850 // The current token is in the same line as the prior token, not recoverable.
851 } else if self.look_ahead(1, |t| {
852 t == &token::CloseDelim(token::Brace)
853 || token_can_begin_expr(t) && t.kind != token::Colon
854 }) && [token::Comma, token::Colon].contains(&self.token.kind)
856 // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is
857 // either `,` or `:`, and the next token could either start a new statement or is a
858 // block close. For example:
863 let sp = self.prev_span;
864 self.struct_span_err(sp, &msg)
865 .span_suggestion(sp, "change this to `;`", ";".to_string(), appl)
868 } else if self.look_ahead(0, |t| {
869 t == &token::CloseDelim(token::Brace)
871 token_can_begin_expr(t) && t != &token::Semi && t != &token::Pound
872 // Avoid triggering with too many trailing `#` in raw string.
875 // Missing semicolon typo. This is triggered if the next token could either start a
876 // new statement or is a block close. For example:
880 let sp = self.prev_span.shrink_to_hi();
881 self.struct_span_err(sp, &msg)
882 .span_label(self.token.span, "unexpected token")
883 .span_suggestion_short(sp, "add `;` here", ";".to_string(), appl)
887 self.expect(&token::Semi).map(drop) // Error unconditionally
890 pub(super) fn parse_semi_or_incorrect_foreign_fn_body(
894 ) -> PResult<'a, ()> {
895 if self.token != token::Semi {
896 // This might be an incorrect fn definition (#62109).
897 let parser_snapshot = self.clone();
898 match self.parse_inner_attrs_and_block() {
900 self.struct_span_err(ident.span, "incorrect `fn` inside `extern` block")
901 .span_label(ident.span, "can't have a body")
902 .span_label(body.span, "this body is invalid here")
905 "`extern` blocks define existing foreign functions and `fn`s \
906 inside of them cannot have a body",
909 "you might have meant to write a function accessible through ffi, \
910 which can be done by writing `extern fn` outside of the \
914 "for more information, visit \
915 https://doc.rust-lang.org/std/keyword.extern.html",
921 mem::replace(self, parser_snapshot);
931 /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
932 /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
933 pub(super) fn recover_incorrect_await_syntax(
938 ) -> PResult<'a, P<Expr>> {
939 let (hi, expr, is_question) = if self.token == token::Not {
940 // Handle `await!(<expr>)`.
941 self.recover_await_macro()?
943 self.recover_await_prefix(await_sp)?
945 let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
946 let expr = self.mk_expr(lo.to(sp), ExprKind::Await(expr), attrs);
947 self.maybe_recover_from_bad_qpath(expr, true)
950 fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
951 self.expect(&token::Not)?;
952 self.expect(&token::OpenDelim(token::Paren))?;
953 let expr = self.parse_expr()?;
954 self.expect(&token::CloseDelim(token::Paren))?;
955 Ok((self.prev_span, expr, false))
958 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
959 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
960 let expr = if self.token == token::OpenDelim(token::Brace) {
961 // Handle `await { <expr> }`.
962 // This needs to be handled separatedly from the next arm to avoid
963 // interpreting `await { <expr> }?` as `<expr>?.await`.
964 self.parse_block_expr(None, self.token.span, BlockCheckMode::Default, AttrVec::new())
969 err.span_label(await_sp, "while parsing this incorrect await expression");
972 Ok((expr.span, expr, is_question))
975 fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
977 self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr));
978 let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" });
980 let app = match expr.kind {
981 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
982 _ => Applicability::MachineApplicable,
984 self.struct_span_err(sp, "incorrect use of `await`")
985 .span_suggestion(sp, "`await` is a postfix operation", suggestion, app)
990 /// If encountering `future.await()`, consumes and emits an error.
991 pub(super) fn recover_from_await_method_call(&mut self) {
992 if self.token == token::OpenDelim(token::Paren)
993 && self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren))
996 let lo = self.token.span;
998 let sp = lo.to(self.token.span);
1000 self.struct_span_err(sp, "incorrect use of `await`")
1003 "`await` is not a method call, remove the parentheses",
1005 Applicability::MachineApplicable,
1011 /// Recovers a situation like `for ( $pat in $expr )`
1012 /// and suggest writing `for $pat in $expr` instead.
1014 /// This should be called before parsing the `$block`.
1015 pub(super) fn recover_parens_around_for_head(
1019 begin_paren: Option<Span>,
1021 match (&self.token.kind, begin_paren) {
1022 (token::CloseDelim(token::Paren), Some(begin_par_sp)) => {
1026 // Remove the `(` from the span of the pattern:
1027 .span_to_snippet(pat.span.trim_start(begin_par_sp).unwrap())
1028 .unwrap_or_else(|_| pprust::pat_to_string(&pat));
1030 self.struct_span_err(self.prev_span, "unexpected closing `)`")
1031 .span_label(begin_par_sp, "opening `(`")
1033 begin_par_sp.to(self.prev_span),
1034 "remove parenthesis in `for` loop",
1035 format!("{} in {}", pat_str, pprust::expr_to_string(&expr)),
1036 // With e.g. `for (x) in y)` this would replace `(x) in y)`
1037 // with `x) in y)` which is syntactically invalid.
1038 // However, this is prevented before we get here.
1039 Applicability::MachineApplicable,
1043 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1044 pat.and_then(|pat| match pat.kind {
1045 PatKind::Paren(pat) => pat,
1053 pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1054 (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1055 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1056 || self.token.is_ident() &&
1058 // `foo::` → `foo:` or `foo.bar::` → `foo.bar:`
1059 ast::ExprKind::Path(..) | ast::ExprKind::Field(..) => true,
1062 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
1063 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren))
1064 || self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz`
1065 self.look_ahead(2, |t| t.is_ident())
1066 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
1067 self.look_ahead(2, |t| t.is_ident())
1068 || self.look_ahead(1, |t| t == &token::ModSep)
1069 && (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
1070 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1073 pub(super) fn recover_seq_parse_error(
1075 delim: token::DelimToken,
1077 result: PResult<'a, P<Expr>>,
1083 // Recover from parse error, callers expect the closing delim to be consumed.
1084 self.consume_block(delim, ConsumeClosingDelim::Yes);
1085 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, AttrVec::new())
1090 pub(super) fn recover_closing_delimiter(
1092 tokens: &[TokenKind],
1093 mut err: DiagnosticBuilder<'a>,
1094 ) -> PResult<'a, bool> {
1096 // We want to use the last closing delim that would apply.
1097 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1098 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1099 && Some(self.token.span) > unmatched.unclosed_span
1106 // Recover and assume that the detected unclosed delimiter was meant for
1107 // this location. Emit the diagnostic and act as if the delimiter was
1108 // present for the parser's sake.
1110 // Don't attempt to recover from this unclosed delimiter more than once.
1111 let unmatched = self.unclosed_delims.remove(pos);
1112 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1113 if unmatched.found_delim.is_none() {
1114 // We encountered `Eof`, set this fact here to avoid complaining about missing
1115 // `fn main()` when we found place to suggest the closing brace.
1116 *self.sess.reached_eof.borrow_mut() = true;
1119 // We want to suggest the inclusion of the closing delimiter where it makes
1120 // the most sense, which is immediately after the last token:
1125 // | help: `)` may belong here
1127 // unclosed delimiter
1128 if let Some(sp) = unmatched.unclosed_span {
1129 err.span_label(sp, "unclosed delimiter");
1131 err.span_suggestion_short(
1132 self.prev_span.shrink_to_hi(),
1133 &format!("{} may belong here", delim.to_string()),
1135 Applicability::MaybeIncorrect,
1137 if unmatched.found_delim.is_none() {
1138 // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1139 // errors which would be emitted elsewhere in the parser and let other error
1140 // recovery consume the rest of the file.
1144 self.expected_tokens.clear(); // Reduce the number of errors.
1152 /// Eats tokens until we can be relatively sure we reached the end of the
1153 /// statement. This is something of a best-effort heuristic.
1155 /// We terminate when we find an unmatched `}` (without consuming it).
1156 pub(super) fn recover_stmt(&mut self) {
1157 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1160 /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1161 /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1162 /// approximate -- it can mean we break too early due to macros, but that
1163 /// should only lead to sub-optimal recovery, not inaccurate parsing).
1165 /// If `break_on_block` is `Break`, then we will stop consuming tokens
1166 /// after finding (and consuming) a brace-delimited block.
1167 pub(super) fn recover_stmt_(
1169 break_on_semi: SemiColonMode,
1170 break_on_block: BlockMode,
1172 let mut brace_depth = 0;
1173 let mut bracket_depth = 0;
1174 let mut in_block = false;
1175 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1177 debug!("recover_stmt_ loop {:?}", self.token);
1178 match self.token.kind {
1179 token::OpenDelim(token::DelimToken::Brace) => {
1182 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1187 token::OpenDelim(token::DelimToken::Bracket) => {
1191 token::CloseDelim(token::DelimToken::Brace) => {
1192 if brace_depth == 0 {
1193 debug!("recover_stmt_ return - close delim {:?}", self.token);
1198 if in_block && bracket_depth == 0 && brace_depth == 0 {
1199 debug!("recover_stmt_ return - block end {:?}", self.token);
1203 token::CloseDelim(token::DelimToken::Bracket) => {
1205 if bracket_depth < 0 {
1211 debug!("recover_stmt_ return - Eof");
1216 if break_on_semi == SemiColonMode::Break
1218 && bracket_depth == 0
1220 debug!("recover_stmt_ return - Semi");
1225 if break_on_semi == SemiColonMode::Comma
1227 && bracket_depth == 0 =>
1229 debug!("recover_stmt_ return - Semi");
1237 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1238 if self.eat_keyword(kw::In) {
1239 // a common typo: `for _ in in bar {}`
1240 self.struct_span_err(self.prev_span, "expected iterable, found keyword `in`")
1241 .span_suggestion_short(
1242 in_span.until(self.prev_span),
1243 "remove the duplicated `in`",
1245 Applicability::MachineApplicable,
1251 pub(super) fn expected_semi_or_open_brace<T>(&mut self) -> PResult<'a, T> {
1252 let token_str = super::token_descr(&self.token);
1253 let msg = &format!("expected `;` or `{{`, found {}", token_str);
1254 let mut err = self.struct_span_err(self.token.span, msg);
1255 err.span_label(self.token.span, "expected `;` or `{`");
1259 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1260 if let token::DocComment(_) = self.token.kind {
1261 self.struct_span_err(
1263 "documentation comments cannot be applied to a function parameter's type",
1265 .span_label(self.token.span, "doc comments are not allowed here")
1268 } else if self.token == token::Pound
1269 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Bracket))
1271 let lo = self.token.span;
1272 // Skip every token until next possible arg.
1273 while self.token != token::CloseDelim(token::Bracket) {
1276 let sp = lo.to(self.token.span);
1278 self.struct_span_err(sp, "attributes cannot be applied to a function parameter's type")
1279 .span_label(sp, "attributes are not allowed here")
1284 pub(super) fn parameter_without_type(
1286 err: &mut DiagnosticBuilder<'_>,
1289 is_self_allowed: bool,
1290 is_trait_item: bool,
1291 ) -> Option<Ident> {
1292 // If we find a pattern followed by an identifier, it could be an (incorrect)
1293 // C-style parameter declaration.
1294 if self.check_ident()
1295 && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseDelim(token::Paren))
1297 // `fn foo(String s) {}`
1298 let ident = self.parse_ident().unwrap();
1299 let span = pat.span.with_hi(ident.span.hi());
1301 err.span_suggestion(
1303 "declare the type after the parameter binding",
1304 String::from("<identifier>: <type>"),
1305 Applicability::HasPlaceholders,
1308 } else if let PatKind::Ident(_, ident, _) = pat.kind {
1311 || self.token == token::Comma
1312 || self.token == token::Lt
1313 || self.token == token::CloseDelim(token::Paren))
1315 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1316 if is_self_allowed {
1317 err.span_suggestion(
1319 "if this is a `self` type, give it a parameter name",
1320 format!("self: {}", ident),
1321 Applicability::MaybeIncorrect,
1324 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
1325 // `fn foo(HashMap: TypeName<u32>)`.
1326 if self.token != token::Lt {
1327 err.span_suggestion(
1329 "if this was a parameter name, give it a type",
1330 format!("{}: TypeName", ident),
1331 Applicability::HasPlaceholders,
1334 err.span_suggestion(
1336 "if this is a type, explicitly ignore the parameter name",
1337 format!("_: {}", ident),
1338 Applicability::MachineApplicable,
1340 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1342 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
1343 return if self.token == token::Lt { None } else { Some(ident) };
1349 pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
1350 let pat = self.parse_pat(Some("argument name"))?;
1351 self.expect(&token::Colon)?;
1352 let ty = self.parse_ty()?;
1358 "patterns aren't allowed in methods without bodies",
1360 .span_suggestion_short(
1362 "give this argument a name or use an underscore to ignore it",
1364 Applicability::MachineApplicable,
1368 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1369 let pat = P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID });
1373 pub(super) fn recover_bad_self_param(
1375 mut param: ast::Param,
1376 is_trait_item: bool,
1377 ) -> PResult<'a, ast::Param> {
1378 let sp = param.pat.span;
1379 param.ty.kind = TyKind::Err;
1380 let mut err = self.struct_span_err(sp, "unexpected `self` parameter in function");
1382 err.span_label(sp, "must be the first associated function parameter");
1384 err.span_label(sp, "not valid as function parameter");
1385 err.note("`self` is only valid as the first parameter of an associated function");
1391 pub(super) fn consume_block(
1393 delim: token::DelimToken,
1394 consume_close: ConsumeClosingDelim,
1396 let mut brace_depth = 0;
1398 if self.eat(&token::OpenDelim(delim)) {
1400 } else if self.check(&token::CloseDelim(delim)) {
1401 if brace_depth == 0 {
1402 if let ConsumeClosingDelim::Yes = consume_close {
1403 // Some of the callers of this method expect to be able to parse the
1404 // closing delimiter themselves, so we leave it alone. Otherwise we advance
1414 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
1422 pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a> {
1423 let (span, msg) = match (&self.token.kind, self.subparser_name) {
1424 (&token::Eof, Some(origin)) => {
1425 let sp = self.sess.source_map().next_point(self.token.span);
1426 (sp, format!("expected expression, found end of {}", origin))
1430 format!("expected expression, found {}", super::token_descr(&self.token),),
1433 let mut err = self.struct_span_err(span, &msg);
1434 let sp = self.sess.source_map().start_point(self.token.span);
1435 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
1436 self.sess.expr_parentheses_needed(&mut err, *sp, None);
1438 err.span_label(span, "expected expression");
1444 mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
1445 // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
1446 modifier: &[(token::TokenKind, i64)],
1449 if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
1452 if self.token.kind == token::Eof {
1459 /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
1461 /// This is necessary because at this point we don't know whether we parsed a function with
1462 /// anonymous parameters or a function with names but no types. In order to minimize
1463 /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
1464 /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
1465 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
1466 /// we deduplicate them to not complain about duplicated parameter names.
1467 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
1468 let mut seen_inputs = FxHashSet::default();
1469 for input in fn_inputs.iter_mut() {
1470 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
1471 (&input.pat.kind, &input.ty.kind)
1477 if let Some(ident) = opt_ident {
1478 if seen_inputs.contains(&ident) {
1479 input.pat.kind = PatKind::Wild;
1481 seen_inputs.insert(ident);