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,
57 fn span_err(self, sp: impl Into<MultiSpan>, handler: &Handler) -> DiagnosticBuilder<'_> {
59 Error::FileNotFoundForModule {
65 let mut err = struct_span_err!(
69 "file not found for module `{}`",
73 "name the file either {} or {} inside the directory \"{}\"",
74 default_path, secondary_path, dir_path,
78 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
79 let mut err = struct_span_err!(
83 "file for module `{}` found at both {} and {}",
88 err.help("delete or rename one of them to remove the ambiguity");
91 Error::UselessDocComment => {
92 let mut err = struct_span_err!(
96 "found a documentation comment that doesn't document anything",
99 "doc comments must come before what they document, maybe a comment was \
100 intended with `//`?",
108 pub(super) trait RecoverQPath: Sized + 'static {
109 const PATH_STYLE: PathStyle = PathStyle::Expr;
110 fn to_ty(&self) -> Option<P<Ty>>;
111 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
114 impl RecoverQPath for Ty {
115 const PATH_STYLE: PathStyle = PathStyle::Type;
116 fn to_ty(&self) -> Option<P<Ty>> {
117 Some(P(self.clone()))
119 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
120 Self { span: path.span, kind: TyKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
124 impl RecoverQPath for Pat {
125 fn to_ty(&self) -> Option<P<Ty>> {
128 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
129 Self { span: path.span, kind: PatKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
133 impl RecoverQPath for Expr {
134 fn to_ty(&self) -> Option<P<Ty>> {
137 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
140 kind: ExprKind::Path(qself, path),
141 attrs: AttrVec::new(),
142 id: ast::DUMMY_NODE_ID,
147 /// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
148 crate enum ConsumeClosingDelim {
153 impl<'a> Parser<'a> {
154 pub(super) fn span_fatal_err<S: Into<MultiSpan>>(
158 ) -> DiagnosticBuilder<'a> {
159 err.span_err(sp, self.diagnostic())
162 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
163 self.sess.span_diagnostic.struct_span_err(sp, m)
166 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
167 self.sess.span_diagnostic.span_bug(sp, m)
170 pub(super) fn diagnostic(&self) -> &'a Handler {
171 &self.sess.span_diagnostic
174 pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
175 self.sess.source_map().span_to_snippet(span)
178 pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
179 let mut err = self.struct_span_err(
181 &format!("expected identifier, found {}", super::token_descr(&self.token)),
183 let valid_follow = &[
189 TokenKind::OpenDelim(token::DelimToken::Brace),
190 TokenKind::OpenDelim(token::DelimToken::Paren),
191 TokenKind::CloseDelim(token::DelimToken::Brace),
192 TokenKind::CloseDelim(token::DelimToken::Paren),
194 if let token::Ident(name, false) = self.token.kind {
195 if Ident::new(name, self.token.span).is_raw_guess()
196 && self.look_ahead(1, |t| valid_follow.contains(&t.kind))
200 "you can escape reserved keywords to use them as identifiers",
201 format!("r#{}", name),
202 Applicability::MaybeIncorrect,
206 if let Some(token_descr) = super::token_descr_opt(&self.token) {
207 err.span_label(self.token.span, format!("expected identifier, found {}", token_descr));
209 err.span_label(self.token.span, "expected identifier");
210 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
215 Applicability::MachineApplicable,
222 pub(super) fn expected_one_of_not_found(
224 edible: &[TokenKind],
225 inedible: &[TokenKind],
226 ) -> PResult<'a, bool /* recovered */> {
227 fn tokens_to_string(tokens: &[TokenType]) -> String {
228 let mut i = tokens.iter();
229 // This might be a sign we need a connect method on `Iterator`.
230 let b = i.next().map_or(String::new(), |t| t.to_string());
231 i.enumerate().fold(b, |mut b, (i, a)| {
232 if tokens.len() > 2 && i == tokens.len() - 2 {
234 } else if tokens.len() == 2 && i == tokens.len() - 2 {
239 b.push_str(&a.to_string());
244 let mut expected = edible
246 .map(|x| TokenType::Token(x.clone()))
247 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
248 .chain(self.expected_tokens.iter().cloned())
249 .collect::<Vec<_>>();
250 expected.sort_by_cached_key(|x| x.to_string());
252 let expect = tokens_to_string(&expected[..]);
253 let actual = super::token_descr(&self.token);
254 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
255 let short_expect = if expected.len() > 6 {
256 format!("{} possible tokens", expected.len())
261 format!("expected one of {}, found {}", expect, actual),
262 (self.prev_span.shrink_to_hi(), format!("expected one of {}", short_expect)),
264 } else if expected.is_empty() {
266 format!("unexpected token: {}", actual),
267 (self.prev_span, "unexpected token after this".to_string()),
271 format!("expected {}, found {}", expect, actual),
272 (self.prev_span.shrink_to_hi(), format!("expected {}", expect)),
275 self.last_unexpected_token_span = Some(self.token.span);
276 let mut err = self.struct_span_err(self.token.span, &msg_exp);
277 let sp = if self.token == token::Eof {
278 // This is EOF; don't want to point at the following char, but rather the last token.
283 match self.recover_closing_delimiter(
286 .filter_map(|tt| match tt {
287 TokenType::Token(t) => Some(t.clone()),
290 .collect::<Vec<_>>(),
295 return Ok(recovered);
299 let sm = self.sess.source_map();
300 if self.prev_span == DUMMY_SP {
301 // Account for macro context where the previous span might not be
302 // available to avoid incorrect output (#54841).
303 err.span_label(self.token.span, label_exp);
304 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
305 // When the spans are in the same line, it means that the only content between
306 // them is whitespace, point at the found token in that case:
308 // X | () => { syntax error };
309 // | ^^^^^ expected one of 8 possible tokens here
311 // instead of having:
313 // X | () => { syntax error };
314 // | -^^^^^ unexpected token
316 // | expected one of 8 possible tokens here
317 err.span_label(self.token.span, label_exp);
319 err.span_label(sp, label_exp);
320 err.span_label(self.token.span, "unexpected token");
322 self.maybe_annotate_with_ascription(&mut err, false);
326 pub fn maybe_annotate_with_ascription(
328 err: &mut DiagnosticBuilder<'_>,
329 maybe_expected_semicolon: bool,
331 if let Some((sp, likely_path)) = self.last_type_ascription.take() {
332 let sm = self.sess.source_map();
333 let next_pos = sm.lookup_char_pos(self.token.span.lo());
334 let op_pos = sm.lookup_char_pos(sp.hi());
336 let allow_unstable = self.sess.unstable_features.is_nightly_build();
341 "maybe write a path separator here",
344 Applicability::MaybeIncorrect
346 Applicability::MachineApplicable
349 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
352 "try using a semicolon",
354 Applicability::MaybeIncorrect,
356 } else if allow_unstable {
357 err.span_label(sp, "tried to parse a type due to this type ascription");
359 err.span_label(sp, "tried to parse a type due to this");
362 // Give extra information about type ascription only if it's a nightly compiler.
364 "`#![feature(type_ascription)]` lets you annotate an expression with a \
365 type: `<expr>: <type>`",
368 "for more information, see \
369 https://github.com/rust-lang/rust/issues/23416",
375 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
376 /// passes through any errors encountered. Used for error recovery.
377 pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
378 if let Err(ref mut err) =
379 self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
380 Ok(p.parse_token_tree())
387 /// This function checks if there are trailing angle brackets and produces
388 /// a diagnostic to suggest removing them.
390 /// ```ignore (diagnostic)
391 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
392 /// ^^ help: remove extra angle brackets
394 pub(super) fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: TokenKind) {
395 // This function is intended to be invoked after parsing a path segment where there are two
398 // 1. A specific token is expected after the path segment.
399 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
400 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
401 // 2. No specific token is expected after the path segment.
402 // eg. `x.foo` (field access)
404 // This function is called after parsing `.foo` and before parsing the token `end` (if
405 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
408 // We only care about trailing angle brackets if we previously parsed angle bracket
409 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
410 // removed in this case:
412 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
414 // This case is particularly tricky as we won't notice it just looking at the tokens -
415 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
416 // have already been parsed):
418 // `x.foo::<u32>>>(3)`
419 let parsed_angle_bracket_args =
420 segment.args.as_ref().map(|args| args.is_angle_bracketed()).unwrap_or(false);
423 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
424 parsed_angle_bracket_args,
426 if !parsed_angle_bracket_args {
430 // Keep the span at the start so we can highlight the sequence of `>` characters to be
432 let lo = self.token.span;
434 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
435 // (since we might have the field access case and the characters we're eating are
436 // actual operators and not trailing characters - ie `x.foo >> 3`).
437 let mut position = 0;
439 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
440 // many of each (so we can correctly pluralize our error messages) and continue to
442 let mut number_of_shr = 0;
443 let mut number_of_gt = 0;
444 while self.look_ahead(position, |t| {
445 trace!("check_trailing_angle_brackets: t={:?}", t);
446 if *t == token::BinOp(token::BinOpToken::Shr) {
449 } else if *t == token::Gt {
459 // If we didn't find any trailing `>` characters, then we have nothing to error about.
461 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
462 number_of_gt, number_of_shr,
464 if number_of_gt < 1 && number_of_shr < 1 {
468 // Finally, double check that we have our end token as otherwise this is the
470 if self.look_ahead(position, |t| {
471 trace!("check_trailing_angle_brackets: t={:?}", t);
474 // Eat from where we started until the end token so that parsing can continue
475 // as if we didn't have those extra angle brackets.
476 self.eat_to_tokens(&[&end]);
477 let span = lo.until(self.token.span);
479 let total_num_of_gt = number_of_gt + number_of_shr * 2;
480 self.struct_span_err(
482 &format!("unmatched angle bracket{}", pluralize!(total_num_of_gt)),
486 &format!("remove extra angle bracket{}", pluralize!(total_num_of_gt)),
488 Applicability::MachineApplicable,
494 /// Produces an error if comparison operators are chained (RFC #558).
495 /// We only need to check the LHS, not the RHS, because all comparison ops have same
496 /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
498 /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
499 /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
502 /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
503 /// associative we can infer that we have:
510 pub(super) fn check_no_chained_comparison(
514 ) -> PResult<'a, Option<P<Expr>>> {
516 outer_op.is_comparison(),
517 "check_no_chained_comparison: {:?} is not comparison",
522 |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err, AttrVec::new())));
525 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
526 // Respan to include both operators.
527 let op_span = op.span.to(self.prev_span);
529 .struct_span_err(op_span, "chained comparison operators require parentheses");
531 let suggest = |err: &mut DiagnosticBuilder<'_>| {
532 err.span_suggestion_verbose(
533 op_span.shrink_to_lo(),
536 Applicability::MaybeIncorrect,
540 if op.node == BinOpKind::Lt &&
541 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
542 *outer_op == AssocOp::Greater
543 // even in a case like the following:
545 // Foo<Bar<Baz<Qux, ()>>>
546 if *outer_op == AssocOp::Less {
547 let snapshot = self.clone();
549 // So far we have parsed `foo<bar<`, consume the rest of the type args.
551 [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
552 self.consume_tts(1, &modifiers[..]);
554 if !&[token::OpenDelim(token::Paren), token::ModSep]
555 .contains(&self.token.kind)
557 // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
558 // parser and bail out.
559 mem::replace(self, snapshot.clone());
562 return if token::ModSep == self.token.kind {
563 // We have some certainty that this was a bad turbofish at this point.
567 let snapshot = self.clone();
570 // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
571 match self.parse_expr() {
573 // 99% certain that the suggestion is correct, continue parsing.
575 // FIXME: actually check that the two expressions in the binop are
576 // paths and resynthesize new fn call expression instead of using
577 // `ExprKind::Err` placeholder.
578 mk_err_expr(self, lhs.span.to(self.prev_span))
580 Err(mut expr_err) => {
582 // Not entirely sure now, but we bubble the error up with the
584 mem::replace(self, snapshot);
588 } else if token::OpenDelim(token::Paren) == self.token.kind {
589 // We have high certainty that this was a bad turbofish at this point.
592 // Consume the fn call arguments.
593 match self.consume_fn_args() {
597 // FIXME: actually check that the two expressions in the binop are
598 // paths and resynthesize new fn call expression instead of using
599 // `ExprKind::Err` placeholder.
600 mk_err_expr(self, lhs.span.to(self.prev_span))
604 // All we know is that this is `foo < bar >` and *nothing* else. Try to
605 // be helpful, but don't attempt to recover.
607 err.help("or use `(...)` if you meant to specify fn arguments");
608 // These cases cause too many knock-down errors, bail out (#61329).
619 fn consume_fn_args(&mut self) -> Result<(), ()> {
620 let snapshot = self.clone();
623 // Consume the fn call arguments.
625 [(token::OpenDelim(token::Paren), 1), (token::CloseDelim(token::Paren), -1)];
626 self.consume_tts(1, &modifiers[..]);
628 if self.token.kind == token::Eof {
629 // Not entirely sure that what we consumed were fn arguments, rollback.
630 mem::replace(self, snapshot);
633 // 99% certain that the suggestion is correct, continue parsing.
638 pub(super) fn maybe_report_ambiguous_plus(
641 impl_dyn_multi: bool,
644 if !allow_plus && impl_dyn_multi {
645 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
646 self.struct_span_err(ty.span, "ambiguous `+` in a type")
649 "use parentheses to disambiguate",
651 Applicability::MachineApplicable,
657 pub(super) fn maybe_recover_from_bad_type_plus(
661 ) -> PResult<'a, ()> {
662 // Do not add `+` to expected tokens.
663 if !allow_plus || !self.token.is_like_plus() {
668 let bounds = self.parse_generic_bounds(None)?;
669 let sum_span = ty.span.to(self.prev_span);
671 let mut err = struct_span_err!(
672 self.sess.span_diagnostic,
675 "expected a path on the left-hand side of `+`, not `{}`",
676 pprust::ty_to_string(ty)
680 TyKind::Rptr(ref lifetime, ref mut_ty) => {
681 let sum_with_parens = pprust::to_string(|s| {
683 s.print_opt_lifetime(lifetime);
684 s.print_mutability(mut_ty.mutbl, false);
686 s.print_type(&mut_ty.ty);
687 s.print_type_bounds(" +", &bounds);
692 "try adding parentheses",
694 Applicability::MachineApplicable,
697 TyKind::Ptr(..) | TyKind::BareFn(..) => {
698 err.span_label(sum_span, "perhaps you forgot parentheses?");
701 err.span_label(sum_span, "expected a path");
708 /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
709 /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
710 /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
711 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
714 allow_recovery: bool,
715 ) -> PResult<'a, P<T>> {
716 // Do not add `::` to expected tokens.
717 if allow_recovery && self.token == token::ModSep {
718 if let Some(ty) = base.to_ty() {
719 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
725 /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
726 /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
727 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
731 ) -> PResult<'a, P<T>> {
732 self.expect(&token::ModSep)?;
734 let mut path = ast::Path { segments: Vec::new(), span: DUMMY_SP };
735 self.parse_path_segments(&mut path.segments, T::PATH_STYLE)?;
736 path.span = ty_span.to(self.prev_span);
738 let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
739 self.struct_span_err(path.span, "missing angle brackets in associated item path")
741 // This is a best-effort recovery.
744 format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
745 Applicability::MaybeIncorrect,
749 let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
750 Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path)))
753 pub(super) fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
754 if self.eat(&token::Semi) {
755 let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`");
756 err.span_suggestion_short(
758 "remove this semicolon",
760 Applicability::MachineApplicable,
762 if !items.is_empty() {
763 let previous_item = &items[items.len() - 1];
764 let previous_item_kind_name = match previous_item.kind {
765 // Say "braced struct" because tuple-structs and
766 // braceless-empty-struct declarations do take a semicolon.
767 ItemKind::Struct(..) => Some("braced struct"),
768 ItemKind::Enum(..) => Some("enum"),
769 ItemKind::Trait(..) => Some("trait"),
770 ItemKind::Union(..) => Some("union"),
773 if let Some(name) = previous_item_kind_name {
774 err.help(&format!("{} declarations are not followed by a semicolon", name));
784 /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
785 /// closing delimiter.
786 pub(super) fn unexpected_try_recover(
789 ) -> PResult<'a, bool /* recovered */> {
790 let token_str = pprust::token_kind_to_string(t);
791 let this_token_str = super::token_descr(&self.token);
792 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
793 // Point at the end of the macro call when reaching end of macro arguments.
794 (token::Eof, Some(_)) => {
795 let sp = self.sess.source_map().next_point(self.token.span);
798 // We don't want to point at the following span after DUMMY_SP.
799 // This happens when the parser finds an empty TokenStream.
800 _ if self.prev_span == DUMMY_SP => (self.token.span, self.token.span),
801 // EOF, don't want to point at the following char, but rather the last token.
802 (token::Eof, None) => (self.prev_span, self.token.span),
803 _ => (self.prev_span.shrink_to_hi(), self.token.span),
806 "expected `{}`, found {}",
808 match (&self.token.kind, self.subparser_name) {
809 (token::Eof, Some(origin)) => format!("end of {}", origin),
813 let mut err = self.struct_span_err(sp, &msg);
814 let label_exp = format!("expected `{}`", token_str);
815 match self.recover_closing_delimiter(&[t.clone()], err) {
818 return Ok(recovered);
821 let sm = self.sess.source_map();
822 if !sm.is_multiline(prev_sp.until(sp)) {
823 // When the spans are in the same line, it means that the only content
824 // between them is whitespace, point only at the found token.
825 err.span_label(sp, label_exp);
827 err.span_label(prev_sp, label_exp);
828 err.span_label(sp, "unexpected token");
833 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
834 if self.eat(&token::Semi) {
837 let sm = self.sess.source_map();
838 let msg = format!("expected `;`, found `{}`", super::token_descr(&self.token));
839 let appl = Applicability::MachineApplicable;
840 if self.token.span == DUMMY_SP || self.prev_span == DUMMY_SP {
841 // Likely inside a macro, can't provide meaninful suggestions.
842 return self.expect(&token::Semi).map(drop);
843 } else if !sm.is_multiline(self.prev_span.until(self.token.span)) {
844 // The current token is in the same line as the prior token, not recoverable.
845 } else if self.look_ahead(1, |t| {
846 t == &token::CloseDelim(token::Brace)
847 || token_can_begin_expr(t) && t.kind != token::Colon
848 }) && [token::Comma, token::Colon].contains(&self.token.kind)
850 // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is
851 // either `,` or `:`, and the next token could either start a new statement or is a
852 // block close. For example:
857 let sp = self.prev_span;
858 self.struct_span_err(sp, &msg)
859 .span_suggestion(sp, "change this to `;`", ";".to_string(), appl)
862 } else if self.look_ahead(0, |t| {
863 t == &token::CloseDelim(token::Brace)
865 token_can_begin_expr(t) && t != &token::Semi && t != &token::Pound
866 // Avoid triggering with too many trailing `#` in raw string.
869 // Missing semicolon typo. This is triggered if the next token could either start a
870 // new statement or is a block close. For example:
874 let sp = self.prev_span.shrink_to_hi();
875 self.struct_span_err(sp, &msg)
876 .span_label(self.token.span, "unexpected token")
877 .span_suggestion_short(sp, "add `;` here", ";".to_string(), appl)
881 self.expect(&token::Semi).map(drop) // Error unconditionally
884 pub(super) fn parse_semi_or_incorrect_foreign_fn_body(
888 ) -> PResult<'a, ()> {
889 if self.token != token::Semi {
890 // This might be an incorrect fn definition (#62109).
891 let parser_snapshot = self.clone();
892 match self.parse_inner_attrs_and_block() {
894 self.struct_span_err(ident.span, "incorrect `fn` inside `extern` block")
895 .span_label(ident.span, "can't have a body")
896 .span_label(body.span, "this body is invalid here")
899 "`extern` blocks define existing foreign functions and `fn`s \
900 inside of them cannot have a body",
903 "you might have meant to write a function accessible through ffi, \
904 which can be done by writing `extern fn` outside of the \
908 "for more information, visit \
909 https://doc.rust-lang.org/std/keyword.extern.html",
915 mem::replace(self, parser_snapshot);
925 /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
926 /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
927 pub(super) fn recover_incorrect_await_syntax(
932 ) -> PResult<'a, P<Expr>> {
933 let (hi, expr, is_question) = if self.token == token::Not {
934 // Handle `await!(<expr>)`.
935 self.recover_await_macro()?
937 self.recover_await_prefix(await_sp)?
939 let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
940 let expr = self.mk_expr(lo.to(sp), ExprKind::Await(expr), attrs);
941 self.maybe_recover_from_bad_qpath(expr, true)
944 fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
945 self.expect(&token::Not)?;
946 self.expect(&token::OpenDelim(token::Paren))?;
947 let expr = self.parse_expr()?;
948 self.expect(&token::CloseDelim(token::Paren))?;
949 Ok((self.prev_span, expr, false))
952 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
953 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
954 let expr = if self.token == token::OpenDelim(token::Brace) {
955 // Handle `await { <expr> }`.
956 // This needs to be handled separatedly from the next arm to avoid
957 // interpreting `await { <expr> }?` as `<expr>?.await`.
958 self.parse_block_expr(None, self.token.span, BlockCheckMode::Default, AttrVec::new())
963 err.span_label(await_sp, "while parsing this incorrect await expression");
966 Ok((expr.span, expr, is_question))
969 fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
971 self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr));
972 let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" });
974 let app = match expr.kind {
975 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
976 _ => Applicability::MachineApplicable,
978 self.struct_span_err(sp, "incorrect use of `await`")
979 .span_suggestion(sp, "`await` is a postfix operation", suggestion, app)
984 /// If encountering `future.await()`, consumes and emits an error.
985 pub(super) fn recover_from_await_method_call(&mut self) {
986 if self.token == token::OpenDelim(token::Paren)
987 && self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren))
990 let lo = self.token.span;
992 let sp = lo.to(self.token.span);
994 self.struct_span_err(sp, "incorrect use of `await`")
997 "`await` is not a method call, remove the parentheses",
999 Applicability::MachineApplicable,
1005 /// Recovers a situation like `for ( $pat in $expr )`
1006 /// and suggest writing `for $pat in $expr` instead.
1008 /// This should be called before parsing the `$block`.
1009 pub(super) fn recover_parens_around_for_head(
1013 begin_paren: Option<Span>,
1015 match (&self.token.kind, begin_paren) {
1016 (token::CloseDelim(token::Paren), Some(begin_par_sp)) => {
1020 // Remove the `(` from the span of the pattern:
1021 .span_to_snippet(pat.span.trim_start(begin_par_sp).unwrap())
1022 .unwrap_or_else(|_| pprust::pat_to_string(&pat));
1024 self.struct_span_err(self.prev_span, "unexpected closing `)`")
1025 .span_label(begin_par_sp, "opening `(`")
1027 begin_par_sp.to(self.prev_span),
1028 "remove parenthesis in `for` loop",
1029 format!("{} in {}", pat_str, pprust::expr_to_string(&expr)),
1030 // With e.g. `for (x) in y)` this would replace `(x) in y)`
1031 // with `x) in y)` which is syntactically invalid.
1032 // However, this is prevented before we get here.
1033 Applicability::MachineApplicable,
1037 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1038 pat.and_then(|pat| match pat.kind {
1039 PatKind::Paren(pat) => pat,
1047 pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1048 (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1049 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1050 || self.token.is_ident() &&
1052 // `foo::` → `foo:` or `foo.bar::` → `foo.bar:`
1053 ast::ExprKind::Path(..) | ast::ExprKind::Field(..) => true,
1056 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
1057 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren))
1058 || self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz`
1059 self.look_ahead(2, |t| t.is_ident())
1060 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
1061 self.look_ahead(2, |t| t.is_ident())
1062 || self.look_ahead(1, |t| t == &token::ModSep)
1063 && (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
1064 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1067 pub(super) fn recover_seq_parse_error(
1069 delim: token::DelimToken,
1071 result: PResult<'a, P<Expr>>,
1077 // Recover from parse error, callers expect the closing delim to be consumed.
1078 self.consume_block(delim, ConsumeClosingDelim::Yes);
1079 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, AttrVec::new())
1084 pub(super) fn recover_closing_delimiter(
1086 tokens: &[TokenKind],
1087 mut err: DiagnosticBuilder<'a>,
1088 ) -> PResult<'a, bool> {
1090 // We want to use the last closing delim that would apply.
1091 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1092 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1093 && Some(self.token.span) > unmatched.unclosed_span
1100 // Recover and assume that the detected unclosed delimiter was meant for
1101 // this location. Emit the diagnostic and act as if the delimiter was
1102 // present for the parser's sake.
1104 // Don't attempt to recover from this unclosed delimiter more than once.
1105 let unmatched = self.unclosed_delims.remove(pos);
1106 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1107 if unmatched.found_delim.is_none() {
1108 // We encountered `Eof`, set this fact here to avoid complaining about missing
1109 // `fn main()` when we found place to suggest the closing brace.
1110 *self.sess.reached_eof.borrow_mut() = true;
1113 // We want to suggest the inclusion of the closing delimiter where it makes
1114 // the most sense, which is immediately after the last token:
1119 // | help: `)` may belong here
1121 // unclosed delimiter
1122 if let Some(sp) = unmatched.unclosed_span {
1123 err.span_label(sp, "unclosed delimiter");
1125 err.span_suggestion_short(
1126 self.prev_span.shrink_to_hi(),
1127 &format!("{} may belong here", delim.to_string()),
1129 Applicability::MaybeIncorrect,
1131 if unmatched.found_delim.is_none() {
1132 // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1133 // errors which would be emitted elsewhere in the parser and let other error
1134 // recovery consume the rest of the file.
1138 self.expected_tokens.clear(); // Reduce the number of errors.
1146 /// Eats tokens until we can be relatively sure we reached the end of the
1147 /// statement. This is something of a best-effort heuristic.
1149 /// We terminate when we find an unmatched `}` (without consuming it).
1150 pub(super) fn recover_stmt(&mut self) {
1151 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1154 /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1155 /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1156 /// approximate -- it can mean we break too early due to macros, but that
1157 /// should only lead to sub-optimal recovery, not inaccurate parsing).
1159 /// If `break_on_block` is `Break`, then we will stop consuming tokens
1160 /// after finding (and consuming) a brace-delimited block.
1161 pub(super) fn recover_stmt_(
1163 break_on_semi: SemiColonMode,
1164 break_on_block: BlockMode,
1166 let mut brace_depth = 0;
1167 let mut bracket_depth = 0;
1168 let mut in_block = false;
1169 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1171 debug!("recover_stmt_ loop {:?}", self.token);
1172 match self.token.kind {
1173 token::OpenDelim(token::DelimToken::Brace) => {
1176 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1181 token::OpenDelim(token::DelimToken::Bracket) => {
1185 token::CloseDelim(token::DelimToken::Brace) => {
1186 if brace_depth == 0 {
1187 debug!("recover_stmt_ return - close delim {:?}", self.token);
1192 if in_block && bracket_depth == 0 && brace_depth == 0 {
1193 debug!("recover_stmt_ return - block end {:?}", self.token);
1197 token::CloseDelim(token::DelimToken::Bracket) => {
1199 if bracket_depth < 0 {
1205 debug!("recover_stmt_ return - Eof");
1210 if break_on_semi == SemiColonMode::Break
1212 && bracket_depth == 0
1214 debug!("recover_stmt_ return - Semi");
1219 if break_on_semi == SemiColonMode::Comma
1221 && bracket_depth == 0 =>
1223 debug!("recover_stmt_ return - Semi");
1231 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1232 if self.eat_keyword(kw::In) {
1233 // a common typo: `for _ in in bar {}`
1234 self.struct_span_err(self.prev_span, "expected iterable, found keyword `in`")
1235 .span_suggestion_short(
1236 in_span.until(self.prev_span),
1237 "remove the duplicated `in`",
1239 Applicability::MachineApplicable,
1245 pub(super) fn expected_semi_or_open_brace<T>(&mut self) -> PResult<'a, T> {
1246 let token_str = super::token_descr(&self.token);
1247 let msg = &format!("expected `;` or `{{`, found {}", token_str);
1248 let mut err = self.struct_span_err(self.token.span, msg);
1249 err.span_label(self.token.span, "expected `;` or `{`");
1253 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1254 if let token::DocComment(_) = self.token.kind {
1255 self.struct_span_err(
1257 "documentation comments cannot be applied to a function parameter's type",
1259 .span_label(self.token.span, "doc comments are not allowed here")
1262 } else if self.token == token::Pound
1263 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Bracket))
1265 let lo = self.token.span;
1266 // Skip every token until next possible arg.
1267 while self.token != token::CloseDelim(token::Bracket) {
1270 let sp = lo.to(self.token.span);
1272 self.struct_span_err(sp, "attributes cannot be applied to a function parameter's type")
1273 .span_label(sp, "attributes are not allowed here")
1278 pub(super) fn parameter_without_type(
1280 err: &mut DiagnosticBuilder<'_>,
1283 is_self_allowed: bool,
1284 is_trait_item: bool,
1285 ) -> Option<Ident> {
1286 // If we find a pattern followed by an identifier, it could be an (incorrect)
1287 // C-style parameter declaration.
1288 if self.check_ident()
1289 && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseDelim(token::Paren))
1291 // `fn foo(String s) {}`
1292 let ident = self.parse_ident().unwrap();
1293 let span = pat.span.with_hi(ident.span.hi());
1295 err.span_suggestion(
1297 "declare the type after the parameter binding",
1298 String::from("<identifier>: <type>"),
1299 Applicability::HasPlaceholders,
1302 } else if let PatKind::Ident(_, ident, _) = pat.kind {
1305 || self.token == token::Comma
1306 || self.token == token::Lt
1307 || self.token == token::CloseDelim(token::Paren))
1309 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1310 if is_self_allowed {
1311 err.span_suggestion(
1313 "if this is a `self` type, give it a parameter name",
1314 format!("self: {}", ident),
1315 Applicability::MaybeIncorrect,
1318 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
1319 // `fn foo(HashMap: TypeName<u32>)`.
1320 if self.token != token::Lt {
1321 err.span_suggestion(
1323 "if this was a parameter name, give it a type",
1324 format!("{}: TypeName", ident),
1325 Applicability::HasPlaceholders,
1328 err.span_suggestion(
1330 "if this is a type, explicitly ignore the parameter name",
1331 format!("_: {}", ident),
1332 Applicability::MachineApplicable,
1334 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1336 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
1337 return if self.token == token::Lt { None } else { Some(ident) };
1343 pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
1344 let pat = self.parse_pat(Some("argument name"))?;
1345 self.expect(&token::Colon)?;
1346 let ty = self.parse_ty()?;
1352 "patterns aren't allowed in methods without bodies",
1354 .span_suggestion_short(
1356 "give this argument a name or use an underscore to ignore it",
1358 Applicability::MachineApplicable,
1362 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1363 let pat = P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID });
1367 pub(super) fn recover_bad_self_param(
1369 mut param: ast::Param,
1370 is_trait_item: bool,
1371 ) -> PResult<'a, ast::Param> {
1372 let sp = param.pat.span;
1373 param.ty.kind = TyKind::Err;
1374 let mut err = self.struct_span_err(sp, "unexpected `self` parameter in function");
1376 err.span_label(sp, "must be the first associated function parameter");
1378 err.span_label(sp, "not valid as function parameter");
1379 err.note("`self` is only valid as the first parameter of an associated function");
1385 pub(super) fn consume_block(
1387 delim: token::DelimToken,
1388 consume_close: ConsumeClosingDelim,
1390 let mut brace_depth = 0;
1392 if self.eat(&token::OpenDelim(delim)) {
1394 } else if self.check(&token::CloseDelim(delim)) {
1395 if brace_depth == 0 {
1396 if let ConsumeClosingDelim::Yes = consume_close {
1397 // Some of the callers of this method expect to be able to parse the
1398 // closing delimiter themselves, so we leave it alone. Otherwise we advance
1408 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
1416 pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a> {
1417 let (span, msg) = match (&self.token.kind, self.subparser_name) {
1418 (&token::Eof, Some(origin)) => {
1419 let sp = self.sess.source_map().next_point(self.token.span);
1420 (sp, format!("expected expression, found end of {}", origin))
1424 format!("expected expression, found {}", super::token_descr(&self.token),),
1427 let mut err = self.struct_span_err(span, &msg);
1428 let sp = self.sess.source_map().start_point(self.token.span);
1429 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
1430 self.sess.expr_parentheses_needed(&mut err, *sp, None);
1432 err.span_label(span, "expected expression");
1438 mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
1439 // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
1440 modifier: &[(token::TokenKind, i64)],
1443 if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
1446 if self.token.kind == token::Eof {
1453 /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
1455 /// This is necessary because at this point we don't know whether we parsed a function with
1456 /// anonymous parameters or a function with names but no types. In order to minimize
1457 /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
1458 /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
1459 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
1460 /// we deduplicate them to not complain about duplicated parameter names.
1461 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
1462 let mut seen_inputs = FxHashSet::default();
1463 for input in fn_inputs.iter_mut() {
1464 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
1465 (&input.pat.kind, &input.ty.kind)
1471 if let Some(ident) = opt_ident {
1472 if seen_inputs.contains(&ident) {
1473 input.pat.kind = PatKind::Wild;
1475 seen_inputs.insert(ident);