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::{self, pluralize, Applicability, DiagnosticBuilder, Handler, PResult};
7 self, BinOpKind, BindingMode, BlockCheckMode, Expr, ExprKind, Ident, Item, Param,
9 use syntax::ast::{AttrVec, ItemKind, Mutability, Pat, PatKind, PathSegment, QSelf, Ty, TyKind};
10 use syntax::print::pprust;
12 use syntax::struct_span_err;
13 use syntax::token::{self, token_can_begin_expr, TokenKind};
14 use syntax::util::parser::AssocOp;
15 use syntax_pos::symbol::kw;
16 use syntax_pos::{MultiSpan, Span, SpanSnippetError, DUMMY_SP};
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),
269 self.sess.source_map().next_point(self.prev_span),
270 format!("expected one of {}", short_expect),
273 } else if expected.is_empty() {
275 format!("unexpected token: {}", actual),
276 (self.prev_span, "unexpected token after this".to_string()),
280 format!("expected {}, found {}", expect, actual),
281 (self.sess.source_map().next_point(self.prev_span), format!("expected {}", expect)),
284 self.last_unexpected_token_span = Some(self.token.span);
285 let mut err = self.struct_span_err(self.token.span, &msg_exp);
286 let sp = if self.token == token::Eof {
287 // This is EOF; don't want to point at the following char, but rather the last token.
292 match self.recover_closing_delimiter(
295 .filter_map(|tt| match tt {
296 TokenType::Token(t) => Some(t.clone()),
299 .collect::<Vec<_>>(),
304 return Ok(recovered);
308 let sm = self.sess.source_map();
309 if self.prev_span == DUMMY_SP {
310 // Account for macro context where the previous span might not be
311 // available to avoid incorrect output (#54841).
312 err.span_label(self.token.span, label_exp);
313 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
314 // When the spans are in the same line, it means that the only content between
315 // them is whitespace, point at the found token in that case:
317 // X | () => { syntax error };
318 // | ^^^^^ expected one of 8 possible tokens here
320 // instead of having:
322 // X | () => { syntax error };
323 // | -^^^^^ unexpected token
325 // | expected one of 8 possible tokens here
326 err.span_label(self.token.span, label_exp);
328 err.span_label(sp, label_exp);
329 err.span_label(self.token.span, "unexpected token");
331 self.maybe_annotate_with_ascription(&mut err, false);
335 pub fn maybe_annotate_with_ascription(
337 err: &mut DiagnosticBuilder<'_>,
338 maybe_expected_semicolon: bool,
340 if let Some((sp, likely_path)) = self.last_type_ascription.take() {
341 let sm = self.sess.source_map();
342 let next_pos = sm.lookup_char_pos(self.token.span.lo());
343 let op_pos = sm.lookup_char_pos(sp.hi());
345 let allow_unstable = self.sess.unstable_features.is_nightly_build();
350 "maybe write a path separator here",
353 Applicability::MaybeIncorrect
355 Applicability::MachineApplicable
358 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
361 "try using a semicolon",
363 Applicability::MaybeIncorrect,
365 } else if allow_unstable {
366 err.span_label(sp, "tried to parse a type due to this type ascription");
368 err.span_label(sp, "tried to parse a type due to this");
371 // Give extra information about type ascription only if it's a nightly compiler.
373 "`#![feature(type_ascription)]` lets you annotate an expression with a \
374 type: `<expr>: <type>`",
377 "for more information, see \
378 https://github.com/rust-lang/rust/issues/23416",
384 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
385 /// passes through any errors encountered. Used for error recovery.
386 pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
387 if let Err(ref mut err) =
388 self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
389 Ok(p.parse_token_tree())
396 /// This function checks if there are trailing angle brackets and produces
397 /// a diagnostic to suggest removing them.
399 /// ```ignore (diagnostic)
400 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
401 /// ^^ help: remove extra angle brackets
403 pub(super) fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: TokenKind) {
404 // This function is intended to be invoked after parsing a path segment where there are two
407 // 1. A specific token is expected after the path segment.
408 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
409 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
410 // 2. No specific token is expected after the path segment.
411 // eg. `x.foo` (field access)
413 // This function is called after parsing `.foo` and before parsing the token `end` (if
414 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
417 // We only care about trailing angle brackets if we previously parsed angle bracket
418 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
419 // removed in this case:
421 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
423 // This case is particularly tricky as we won't notice it just looking at the tokens -
424 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
425 // have already been parsed):
427 // `x.foo::<u32>>>(3)`
428 let parsed_angle_bracket_args =
429 segment.args.as_ref().map(|args| args.is_angle_bracketed()).unwrap_or(false);
432 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
433 parsed_angle_bracket_args,
435 if !parsed_angle_bracket_args {
439 // Keep the span at the start so we can highlight the sequence of `>` characters to be
441 let lo = self.token.span;
443 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
444 // (since we might have the field access case and the characters we're eating are
445 // actual operators and not trailing characters - ie `x.foo >> 3`).
446 let mut position = 0;
448 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
449 // many of each (so we can correctly pluralize our error messages) and continue to
451 let mut number_of_shr = 0;
452 let mut number_of_gt = 0;
453 while self.look_ahead(position, |t| {
454 trace!("check_trailing_angle_brackets: t={:?}", t);
455 if *t == token::BinOp(token::BinOpToken::Shr) {
458 } else if *t == token::Gt {
468 // If we didn't find any trailing `>` characters, then we have nothing to error about.
470 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
471 number_of_gt, number_of_shr,
473 if number_of_gt < 1 && number_of_shr < 1 {
477 // Finally, double check that we have our end token as otherwise this is the
479 if self.look_ahead(position, |t| {
480 trace!("check_trailing_angle_brackets: t={:?}", t);
483 // Eat from where we started until the end token so that parsing can continue
484 // as if we didn't have those extra angle brackets.
485 self.eat_to_tokens(&[&end]);
486 let span = lo.until(self.token.span);
488 let total_num_of_gt = number_of_gt + number_of_shr * 2;
489 self.struct_span_err(
491 &format!("unmatched angle bracket{}", pluralize!(total_num_of_gt)),
495 &format!("remove extra angle bracket{}", pluralize!(total_num_of_gt)),
497 Applicability::MachineApplicable,
503 /// Produces an error if comparison operators are chained (RFC #558).
504 /// We only need to check the LHS, not the RHS, because all comparison ops have same
505 /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
507 /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
508 /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
511 /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
512 /// associative we can infer that we have:
519 pub(super) fn check_no_chained_comparison(
523 ) -> PResult<'a, Option<P<Expr>>> {
525 outer_op.is_comparison(),
526 "check_no_chained_comparison: {:?} is not comparison",
531 |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err, AttrVec::new())));
534 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
535 // Respan to include both operators.
536 let op_span = op.span.to(self.prev_span);
538 .struct_span_err(op_span, "chained comparison operators require parentheses");
540 let suggest = |err: &mut DiagnosticBuilder<'_>| {
541 err.span_suggestion_verbose(
542 op_span.shrink_to_lo(),
545 Applicability::MaybeIncorrect,
549 if op.node == BinOpKind::Lt &&
550 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
551 *outer_op == AssocOp::Greater
552 // even in a case like the following:
554 // Foo<Bar<Baz<Qux, ()>>>
555 if *outer_op == AssocOp::Less {
556 let snapshot = self.clone();
558 // So far we have parsed `foo<bar<`, consume the rest of the type args.
560 [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
561 self.consume_tts(1, &modifiers[..]);
563 if !&[token::OpenDelim(token::Paren), token::ModSep]
564 .contains(&self.token.kind)
566 // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
567 // parser and bail out.
568 mem::replace(self, snapshot.clone());
571 return if token::ModSep == self.token.kind {
572 // We have some certainty that this was a bad turbofish at this point.
576 let snapshot = self.clone();
579 // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
580 match self.parse_expr() {
582 // 99% certain that the suggestion is correct, continue parsing.
584 // FIXME: actually check that the two expressions in the binop are
585 // paths and resynthesize new fn call expression instead of using
586 // `ExprKind::Err` placeholder.
587 mk_err_expr(self, lhs.span.to(self.prev_span))
589 Err(mut expr_err) => {
591 // Not entirely sure now, but we bubble the error up with the
593 mem::replace(self, snapshot);
597 } else if token::OpenDelim(token::Paren) == self.token.kind {
598 // We have high certainty that this was a bad turbofish at this point.
601 // Consume the fn call arguments.
602 match self.consume_fn_args() {
606 // FIXME: actually check that the two expressions in the binop are
607 // paths and resynthesize new fn call expression instead of using
608 // `ExprKind::Err` placeholder.
609 mk_err_expr(self, lhs.span.to(self.prev_span))
613 // All we know is that this is `foo < bar >` and *nothing* else. Try to
614 // be helpful, but don't attempt to recover.
616 err.help("or use `(...)` if you meant to specify fn arguments");
617 // These cases cause too many knock-down errors, bail out (#61329).
628 fn consume_fn_args(&mut self) -> Result<(), ()> {
629 let snapshot = self.clone();
632 // Consume the fn call arguments.
634 [(token::OpenDelim(token::Paren), 1), (token::CloseDelim(token::Paren), -1)];
635 self.consume_tts(1, &modifiers[..]);
637 if self.token.kind == token::Eof {
638 // Not entirely sure that what we consumed were fn arguments, rollback.
639 mem::replace(self, snapshot);
642 // 99% certain that the suggestion is correct, continue parsing.
647 pub(super) fn maybe_report_ambiguous_plus(
650 impl_dyn_multi: bool,
653 if !allow_plus && impl_dyn_multi {
654 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
655 self.struct_span_err(ty.span, "ambiguous `+` in a type")
658 "use parentheses to disambiguate",
660 Applicability::MachineApplicable,
666 pub(super) fn maybe_recover_from_bad_type_plus(
670 ) -> PResult<'a, ()> {
671 // Do not add `+` to expected tokens.
672 if !allow_plus || !self.token.is_like_plus() {
677 let bounds = self.parse_generic_bounds(None)?;
678 let sum_span = ty.span.to(self.prev_span);
680 let mut err = struct_span_err!(
681 self.sess.span_diagnostic,
684 "expected a path on the left-hand side of `+`, not `{}`",
685 pprust::ty_to_string(ty)
689 TyKind::Rptr(ref lifetime, ref mut_ty) => {
690 let sum_with_parens = pprust::to_string(|s| {
692 s.print_opt_lifetime(lifetime);
693 s.print_mutability(mut_ty.mutbl, false);
695 s.print_type(&mut_ty.ty);
696 s.print_type_bounds(" +", &bounds);
701 "try adding parentheses",
703 Applicability::MachineApplicable,
706 TyKind::Ptr(..) | TyKind::BareFn(..) => {
707 err.span_label(sum_span, "perhaps you forgot parentheses?");
710 err.span_label(sum_span, "expected a path");
717 /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
718 /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
719 /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
720 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
723 allow_recovery: bool,
724 ) -> PResult<'a, P<T>> {
725 // Do not add `::` to expected tokens.
726 if allow_recovery && self.token == token::ModSep {
727 if let Some(ty) = base.to_ty() {
728 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
734 /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
735 /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
736 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
740 ) -> PResult<'a, P<T>> {
741 self.expect(&token::ModSep)?;
743 let mut path = ast::Path { segments: Vec::new(), span: DUMMY_SP };
744 self.parse_path_segments(&mut path.segments, T::PATH_STYLE)?;
745 path.span = ty_span.to(self.prev_span);
747 let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
748 self.struct_span_err(path.span, "missing angle brackets in associated item path")
750 // This is a best-effort recovery.
753 format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
754 Applicability::MaybeIncorrect,
758 let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
759 Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path)))
762 pub(super) fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
763 if self.eat(&token::Semi) {
764 let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`");
765 err.span_suggestion_short(
767 "remove this semicolon",
769 Applicability::MachineApplicable,
771 if !items.is_empty() {
772 let previous_item = &items[items.len() - 1];
773 let previous_item_kind_name = match previous_item.kind {
774 // Say "braced struct" because tuple-structs and
775 // braceless-empty-struct declarations do take a semicolon.
776 ItemKind::Struct(..) => Some("braced struct"),
777 ItemKind::Enum(..) => Some("enum"),
778 ItemKind::Trait(..) => Some("trait"),
779 ItemKind::Union(..) => Some("union"),
782 if let Some(name) = previous_item_kind_name {
783 err.help(&format!("{} declarations are not followed by a semicolon", name));
793 /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
794 /// closing delimiter.
795 pub(super) fn unexpected_try_recover(
798 ) -> PResult<'a, bool /* recovered */> {
799 let token_str = pprust::token_kind_to_string(t);
800 let this_token_str = super::token_descr(&self.token);
801 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
802 // Point at the end of the macro call when reaching end of macro arguments.
803 (token::Eof, Some(_)) => {
804 let sp = self.sess.source_map().next_point(self.token.span);
807 // We don't want to point at the following span after DUMMY_SP.
808 // This happens when the parser finds an empty TokenStream.
809 _ if self.prev_span == DUMMY_SP => (self.token.span, self.token.span),
810 // EOF, don't want to point at the following char, but rather the last token.
811 (token::Eof, None) => (self.prev_span, self.token.span),
812 _ => (self.sess.source_map().next_point(self.prev_span), self.token.span),
815 "expected `{}`, found {}",
817 match (&self.token.kind, self.subparser_name) {
818 (token::Eof, Some(origin)) => format!("end of {}", origin),
822 let mut err = self.struct_span_err(sp, &msg);
823 let label_exp = format!("expected `{}`", token_str);
824 match self.recover_closing_delimiter(&[t.clone()], err) {
827 return Ok(recovered);
830 let sm = self.sess.source_map();
831 if !sm.is_multiline(prev_sp.until(sp)) {
832 // When the spans are in the same line, it means that the only content
833 // between them is whitespace, point only at the found token.
834 err.span_label(sp, label_exp);
836 err.span_label(prev_sp, label_exp);
837 err.span_label(sp, "unexpected token");
842 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
843 if self.eat(&token::Semi) {
846 let sm = self.sess.source_map();
847 let msg = format!("expected `;`, found `{}`", super::token_descr(&self.token));
848 let appl = Applicability::MachineApplicable;
849 if self.token.span == DUMMY_SP || self.prev_span == DUMMY_SP {
850 // Likely inside a macro, can't provide meaninful suggestions.
851 return self.expect(&token::Semi).map(|_| ());
852 } else if !sm.is_multiline(self.prev_span.until(self.token.span)) {
853 // The current token is in the same line as the prior token, not recoverable.
854 } else if self.look_ahead(1, |t| {
855 t == &token::CloseDelim(token::Brace)
856 || token_can_begin_expr(t) && t.kind != token::Colon
857 }) && [token::Comma, token::Colon].contains(&self.token.kind)
859 // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is
860 // either `,` or `:`, and the next token could either start a new statement or is a
861 // block close. For example:
866 let sp = self.prev_span;
867 self.struct_span_err(sp, &msg)
868 .span_suggestion(sp, "change this to `;`", ";".to_string(), appl)
871 } else if self.look_ahead(0, |t| {
872 t == &token::CloseDelim(token::Brace)
874 token_can_begin_expr(t) && t != &token::Semi && t != &token::Pound
875 // Avoid triggering with too many trailing `#` in raw string.
878 // Missing semicolon typo. This is triggered if the next token could either start a
879 // new statement or is a block close. For example:
883 let sp = self.prev_span.shrink_to_hi();
884 self.struct_span_err(sp, &msg)
885 .span_label(self.token.span, "unexpected token")
886 .span_suggestion_short(sp, "add `;` here", ";".to_string(), appl)
890 self.expect(&token::Semi).map(|_| ()) // Error unconditionally
893 pub(super) fn parse_semi_or_incorrect_foreign_fn_body(
897 ) -> PResult<'a, ()> {
898 if self.token != token::Semi {
899 // This might be an incorrect fn definition (#62109).
900 let parser_snapshot = self.clone();
901 match self.parse_inner_attrs_and_block() {
903 self.struct_span_err(ident.span, "incorrect `fn` inside `extern` block")
904 .span_label(ident.span, "can't have a body")
905 .span_label(body.span, "this body is invalid here")
908 "`extern` blocks define existing foreign functions and `fn`s \
909 inside of them cannot have a body",
912 "you might have meant to write a function accessible through ffi, \
913 which can be done by writing `extern fn` outside of the \
917 "for more information, visit \
918 https://doc.rust-lang.org/std/keyword.extern.html",
924 mem::replace(self, parser_snapshot);
934 /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
935 /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
936 pub(super) fn recover_incorrect_await_syntax(
941 ) -> PResult<'a, P<Expr>> {
942 let (hi, expr, is_question) = if self.token == token::Not {
943 // Handle `await!(<expr>)`.
944 self.recover_await_macro()?
946 self.recover_await_prefix(await_sp)?
948 let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
949 let expr = self.mk_expr(lo.to(sp), ExprKind::Await(expr), attrs);
950 self.maybe_recover_from_bad_qpath(expr, true)
953 fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
954 self.expect(&token::Not)?;
955 self.expect(&token::OpenDelim(token::Paren))?;
956 let expr = self.parse_expr()?;
957 self.expect(&token::CloseDelim(token::Paren))?;
958 Ok((self.prev_span, expr, false))
961 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
962 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
963 let expr = if self.token == token::OpenDelim(token::Brace) {
964 // Handle `await { <expr> }`.
965 // This needs to be handled separatedly from the next arm to avoid
966 // interpreting `await { <expr> }?` as `<expr>?.await`.
967 self.parse_block_expr(None, self.token.span, BlockCheckMode::Default, AttrVec::new())
972 err.span_label(await_sp, "while parsing this incorrect await expression");
975 Ok((expr.span, expr, is_question))
978 fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
980 self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr));
981 let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" });
983 let app = match expr.kind {
984 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
985 _ => Applicability::MachineApplicable,
987 self.struct_span_err(sp, "incorrect use of `await`")
988 .span_suggestion(sp, "`await` is a postfix operation", suggestion, app)
993 /// If encountering `future.await()`, consumes and emits an error.
994 pub(super) fn recover_from_await_method_call(&mut self) {
995 if self.token == token::OpenDelim(token::Paren)
996 && self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren))
999 let lo = self.token.span;
1001 let sp = lo.to(self.token.span);
1003 self.struct_span_err(sp, "incorrect use of `await`")
1006 "`await` is not a method call, remove the parentheses",
1008 Applicability::MachineApplicable,
1014 /// Recovers a situation like `for ( $pat in $expr )`
1015 /// and suggest writing `for $pat in $expr` instead.
1017 /// This should be called before parsing the `$block`.
1018 pub(super) fn recover_parens_around_for_head(
1022 begin_paren: Option<Span>,
1024 match (&self.token.kind, begin_paren) {
1025 (token::CloseDelim(token::Paren), Some(begin_par_sp)) => {
1029 // Remove the `(` from the span of the pattern:
1030 .span_to_snippet(pat.span.trim_start(begin_par_sp).unwrap())
1031 .unwrap_or_else(|_| pprust::pat_to_string(&pat));
1033 self.struct_span_err(self.prev_span, "unexpected closing `)`")
1034 .span_label(begin_par_sp, "opening `(`")
1036 begin_par_sp.to(self.prev_span),
1037 "remove parenthesis in `for` loop",
1038 format!("{} in {}", pat_str, pprust::expr_to_string(&expr)),
1039 // With e.g. `for (x) in y)` this would replace `(x) in y)`
1040 // with `x) in y)` which is syntactically invalid.
1041 // However, this is prevented before we get here.
1042 Applicability::MachineApplicable,
1046 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1047 pat.and_then(|pat| match pat.kind {
1048 PatKind::Paren(pat) => pat,
1056 pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1057 (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1058 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1059 || self.token.is_ident() &&
1061 // `foo::` → `foo:` or `foo.bar::` → `foo.bar:`
1062 ast::ExprKind::Path(..) | ast::ExprKind::Field(..) => true,
1065 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
1066 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren))
1067 || self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz`
1068 self.look_ahead(2, |t| t.is_ident())
1069 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
1070 self.look_ahead(2, |t| t.is_ident())
1071 || self.look_ahead(1, |t| t == &token::ModSep)
1072 && (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
1073 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1076 pub(super) fn recover_seq_parse_error(
1078 delim: token::DelimToken,
1080 result: PResult<'a, P<Expr>>,
1086 // Recover from parse error, callers expect the closing delim to be consumed.
1087 self.consume_block(delim, ConsumeClosingDelim::Yes);
1088 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, AttrVec::new())
1093 pub(super) fn recover_closing_delimiter(
1095 tokens: &[TokenKind],
1096 mut err: DiagnosticBuilder<'a>,
1097 ) -> PResult<'a, bool> {
1099 // We want to use the last closing delim that would apply.
1100 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1101 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1102 && Some(self.token.span) > unmatched.unclosed_span
1109 // Recover and assume that the detected unclosed delimiter was meant for
1110 // this location. Emit the diagnostic and act as if the delimiter was
1111 // present for the parser's sake.
1113 // Don't attempt to recover from this unclosed delimiter more than once.
1114 let unmatched = self.unclosed_delims.remove(pos);
1115 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1116 if unmatched.found_delim.is_none() {
1117 // We encountered `Eof`, set this fact here to avoid complaining about missing
1118 // `fn main()` when we found place to suggest the closing brace.
1119 *self.sess.reached_eof.borrow_mut() = true;
1122 // We want to suggest the inclusion of the closing delimiter where it makes
1123 // the most sense, which is immediately after the last token:
1128 // | help: `)` may belong here
1130 // unclosed delimiter
1131 if let Some(sp) = unmatched.unclosed_span {
1132 err.span_label(sp, "unclosed delimiter");
1134 err.span_suggestion_short(
1135 self.sess.source_map().next_point(self.prev_span),
1136 &format!("{} may belong here", delim.to_string()),
1138 Applicability::MaybeIncorrect,
1140 if unmatched.found_delim.is_none() {
1141 // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1142 // errors which would be emitted elsewhere in the parser and let other error
1143 // recovery consume the rest of the file.
1147 self.expected_tokens.clear(); // Reduce the number of errors.
1155 /// Eats tokens until we can be relatively sure we reached the end of the
1156 /// statement. This is something of a best-effort heuristic.
1158 /// We terminate when we find an unmatched `}` (without consuming it).
1159 pub(super) fn recover_stmt(&mut self) {
1160 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1163 /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1164 /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1165 /// approximate -- it can mean we break too early due to macros, but that
1166 /// should only lead to sub-optimal recovery, not inaccurate parsing).
1168 /// If `break_on_block` is `Break`, then we will stop consuming tokens
1169 /// after finding (and consuming) a brace-delimited block.
1170 pub(super) fn recover_stmt_(
1172 break_on_semi: SemiColonMode,
1173 break_on_block: BlockMode,
1175 let mut brace_depth = 0;
1176 let mut bracket_depth = 0;
1177 let mut in_block = false;
1178 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1180 debug!("recover_stmt_ loop {:?}", self.token);
1181 match self.token.kind {
1182 token::OpenDelim(token::DelimToken::Brace) => {
1185 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1190 token::OpenDelim(token::DelimToken::Bracket) => {
1194 token::CloseDelim(token::DelimToken::Brace) => {
1195 if brace_depth == 0 {
1196 debug!("recover_stmt_ return - close delim {:?}", self.token);
1201 if in_block && bracket_depth == 0 && brace_depth == 0 {
1202 debug!("recover_stmt_ return - block end {:?}", self.token);
1206 token::CloseDelim(token::DelimToken::Bracket) => {
1208 if bracket_depth < 0 {
1214 debug!("recover_stmt_ return - Eof");
1219 if break_on_semi == SemiColonMode::Break
1221 && bracket_depth == 0
1223 debug!("recover_stmt_ return - Semi");
1228 if break_on_semi == SemiColonMode::Comma
1230 && bracket_depth == 0 =>
1232 debug!("recover_stmt_ return - Semi");
1240 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1241 if self.eat_keyword(kw::In) {
1242 // a common typo: `for _ in in bar {}`
1243 self.struct_span_err(self.prev_span, "expected iterable, found keyword `in`")
1244 .span_suggestion_short(
1245 in_span.until(self.prev_span),
1246 "remove the duplicated `in`",
1248 Applicability::MachineApplicable,
1254 pub(super) fn expected_semi_or_open_brace<T>(&mut self) -> PResult<'a, T> {
1255 let token_str = super::token_descr(&self.token);
1256 let msg = &format!("expected `;` or `{{`, found {}", token_str);
1257 let mut err = self.struct_span_err(self.token.span, msg);
1258 err.span_label(self.token.span, "expected `;` or `{`");
1262 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1263 if let token::DocComment(_) = self.token.kind {
1264 self.struct_span_err(
1266 "documentation comments cannot be applied to a function parameter's type",
1268 .span_label(self.token.span, "doc comments are not allowed here")
1271 } else if self.token == token::Pound
1272 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Bracket))
1274 let lo = self.token.span;
1275 // Skip every token until next possible arg.
1276 while self.token != token::CloseDelim(token::Bracket) {
1279 let sp = lo.to(self.token.span);
1281 self.struct_span_err(sp, "attributes cannot be applied to a function parameter's type")
1282 .span_label(sp, "attributes are not allowed here")
1287 pub(super) fn parameter_without_type(
1289 err: &mut DiagnosticBuilder<'_>,
1292 is_self_allowed: bool,
1293 is_trait_item: bool,
1294 ) -> Option<Ident> {
1295 // If we find a pattern followed by an identifier, it could be an (incorrect)
1296 // C-style parameter declaration.
1297 if self.check_ident()
1298 && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseDelim(token::Paren))
1300 // `fn foo(String s) {}`
1301 let ident = self.parse_ident().unwrap();
1302 let span = pat.span.with_hi(ident.span.hi());
1304 err.span_suggestion(
1306 "declare the type after the parameter binding",
1307 String::from("<identifier>: <type>"),
1308 Applicability::HasPlaceholders,
1311 } else if let PatKind::Ident(_, ident, _) = pat.kind {
1314 || self.token == token::Comma
1315 || self.token == token::Lt
1316 || self.token == token::CloseDelim(token::Paren))
1318 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1319 if is_self_allowed {
1320 err.span_suggestion(
1322 "if this is a `self` type, give it a parameter name",
1323 format!("self: {}", ident),
1324 Applicability::MaybeIncorrect,
1327 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
1328 // `fn foo(HashMap: TypeName<u32>)`.
1329 if self.token != token::Lt {
1330 err.span_suggestion(
1332 "if this was a parameter name, give it a type",
1333 format!("{}: TypeName", ident),
1334 Applicability::HasPlaceholders,
1337 err.span_suggestion(
1339 "if this is a type, explicitly ignore the parameter name",
1340 format!("_: {}", ident),
1341 Applicability::MachineApplicable,
1343 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1345 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
1346 return if self.token == token::Lt { None } else { Some(ident) };
1352 pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
1353 let pat = self.parse_pat(Some("argument name"))?;
1354 self.expect(&token::Colon)?;
1355 let ty = self.parse_ty()?;
1361 "patterns aren't allowed in methods without bodies",
1363 .span_suggestion_short(
1365 "give this argument a name or use an underscore to ignore it",
1367 Applicability::MachineApplicable,
1371 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1372 let pat = P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID });
1376 pub(super) fn recover_bad_self_param(
1378 mut param: ast::Param,
1379 is_trait_item: bool,
1380 ) -> PResult<'a, ast::Param> {
1381 let sp = param.pat.span;
1382 param.ty.kind = TyKind::Err;
1383 let mut err = self.struct_span_err(sp, "unexpected `self` parameter in function");
1385 err.span_label(sp, "must be the first associated function parameter");
1387 err.span_label(sp, "not valid as function parameter");
1388 err.note("`self` is only valid as the first parameter of an associated function");
1394 pub(super) fn consume_block(
1396 delim: token::DelimToken,
1397 consume_close: ConsumeClosingDelim,
1399 let mut brace_depth = 0;
1401 if self.eat(&token::OpenDelim(delim)) {
1403 } else if self.check(&token::CloseDelim(delim)) {
1404 if brace_depth == 0 {
1405 if let ConsumeClosingDelim::Yes = consume_close {
1406 // Some of the callers of this method expect to be able to parse the
1407 // closing delimiter themselves, so we leave it alone. Otherwise we advance
1417 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
1425 pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a> {
1426 let (span, msg) = match (&self.token.kind, self.subparser_name) {
1427 (&token::Eof, Some(origin)) => {
1428 let sp = self.sess.source_map().next_point(self.token.span);
1429 (sp, format!("expected expression, found end of {}", origin))
1433 format!("expected expression, found {}", super::token_descr(&self.token),),
1436 let mut err = self.struct_span_err(span, &msg);
1437 let sp = self.sess.source_map().start_point(self.token.span);
1438 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
1439 self.sess.expr_parentheses_needed(&mut err, *sp, None);
1441 err.span_label(span, "expected expression");
1447 mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
1448 // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
1449 modifier: &[(token::TokenKind, i64)],
1452 if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
1455 if self.token.kind == token::Eof {
1462 /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
1464 /// This is necessary because at this point we don't know whether we parsed a function with
1465 /// anonymous parameters or a function with names but no types. In order to minimize
1466 /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
1467 /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
1468 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
1469 /// we deduplicate them to not complain about duplicated parameter names.
1470 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
1471 let mut seen_inputs = FxHashSet::default();
1472 for input in fn_inputs.iter_mut() {
1473 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
1474 (&input.pat.kind, &input.ty.kind)
1480 if let Some(ident) = opt_ident {
1481 if seen_inputs.contains(&ident) {
1482 input.pat.kind = PatKind::Wild;
1484 seen_inputs.insert(ident);