2 self, Arg, BinOpKind, BindingMode, BlockCheckMode, Expr, ExprKind, Ident, Item, ItemKind,
3 Mutability, Pat, PatKind, PathSegment, QSelf, Ty, TyKind, VariantData,
5 use crate::feature_gate::{feature_err, UnstableFeatures};
6 use crate::parse::{SeqSep, PResult, Parser, ParseSess};
7 use crate::parse::parser::{BlockMode, PathStyle, SemiColonMode, TokenType, TokenExpectType};
8 use crate::parse::token::{self, TokenKind};
9 use crate::print::pprust;
11 use crate::source_map::Spanned;
12 use crate::symbol::{kw, sym};
14 use crate::util::parser::AssocOp;
15 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
16 use rustc_data_structures::fx::FxHashSet;
17 use syntax_pos::{Span, DUMMY_SP, MultiSpan, SpanSnippetError};
18 use log::{debug, trace};
21 /// Creates a placeholder argument.
22 crate fn dummy_arg(ident: Ident) -> Arg {
24 id: ast::DUMMY_NODE_ID,
25 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
31 id: ast::DUMMY_NODE_ID
33 Arg { attrs: ThinVec::default(), id: ast::DUMMY_NODE_ID, pat, span: ident.span, ty: P(ty) }
37 FileNotFoundForModule {
40 secondary_path: String,
46 secondary_path: String,
49 InclusiveRangeWithNoEnd,
53 fn span_err<S: Into<MultiSpan>>(
56 handler: &errors::Handler,
57 ) -> 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 \"{}\"",
80 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
81 let mut err = struct_span_err!(
85 "file for module `{}` found at both {} and {}",
90 err.help("delete or rename one of them to remove the ambiguity");
93 Error::UselessDocComment => {
94 let mut err = struct_span_err!(
98 "found a documentation comment that doesn't document anything",
100 err.help("doc comments must come before what they document, maybe a comment was \
101 intended with `//`?");
104 Error::InclusiveRangeWithNoEnd => {
105 let mut err = struct_span_err!(
109 "inclusive range with no end",
111 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
118 pub trait RecoverQPath: Sized + 'static {
119 const PATH_STYLE: PathStyle = PathStyle::Expr;
120 fn to_ty(&self) -> Option<P<Ty>>;
121 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
124 impl RecoverQPath for Ty {
125 const PATH_STYLE: PathStyle = PathStyle::Type;
126 fn to_ty(&self) -> Option<P<Ty>> {
127 Some(P(self.clone()))
129 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
132 node: TyKind::Path(qself, path),
133 id: ast::DUMMY_NODE_ID,
138 impl RecoverQPath for Pat {
139 fn to_ty(&self) -> Option<P<Ty>> {
142 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
145 node: PatKind::Path(qself, path),
146 id: ast::DUMMY_NODE_ID,
151 impl RecoverQPath for Expr {
152 fn to_ty(&self) -> Option<P<Ty>> {
155 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
158 node: ExprKind::Path(qself, path),
159 attrs: ThinVec::new(),
160 id: ast::DUMMY_NODE_ID,
165 impl<'a> Parser<'a> {
166 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
167 self.span_fatal(self.token.span, m)
170 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
171 self.sess.span_diagnostic.struct_span_fatal(sp, m)
174 pub fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
175 err.span_err(sp, self.diagnostic())
178 pub fn bug(&self, m: &str) -> ! {
179 self.sess.span_diagnostic.span_bug(self.token.span, m)
182 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
183 self.sess.span_diagnostic.span_err(sp, m)
186 crate fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
187 self.sess.span_diagnostic.struct_span_err(sp, m)
190 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
191 self.sess.span_diagnostic.span_bug(sp, m)
194 crate fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
195 self.sess.span_diagnostic.cancel(err)
198 crate fn diagnostic(&self) -> &'a errors::Handler {
199 &self.sess.span_diagnostic
202 crate fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
203 self.sess.source_map().span_to_snippet(span)
206 crate fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
207 let mut err = self.struct_span_err(
209 &format!("expected identifier, found {}", self.this_token_descr()),
211 if let token::Ident(name, false) = self.token.kind {
212 if Ident::new(name, self.token.span).is_raw_guess() {
215 "you can escape reserved keywords to use them as identifiers",
216 format!("r#{}", name),
217 Applicability::MaybeIncorrect,
221 if let Some(token_descr) = self.token_descr() {
222 err.span_label(self.token.span, format!("expected identifier, found {}", token_descr));
224 err.span_label(self.token.span, "expected identifier");
225 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
230 Applicability::MachineApplicable,
237 pub fn expected_one_of_not_found(
239 edible: &[TokenKind],
240 inedible: &[TokenKind],
241 ) -> PResult<'a, bool /* recovered */> {
242 fn tokens_to_string(tokens: &[TokenType]) -> String {
243 let mut i = tokens.iter();
244 // This might be a sign we need a connect method on Iterator.
246 .map_or(String::new(), |t| t.to_string());
247 i.enumerate().fold(b, |mut b, (i, a)| {
248 if tokens.len() > 2 && i == tokens.len() - 2 {
250 } else if tokens.len() == 2 && i == tokens.len() - 2 {
255 b.push_str(&a.to_string());
260 let mut expected = edible.iter()
261 .map(|x| TokenType::Token(x.clone()))
262 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
263 .chain(self.expected_tokens.iter().cloned())
264 .collect::<Vec<_>>();
265 expected.sort_by_cached_key(|x| x.to_string());
267 let expect = tokens_to_string(&expected[..]);
268 let actual = self.this_token_to_string();
269 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
270 let short_expect = if expected.len() > 6 {
271 format!("{} possible tokens", expected.len())
275 (format!("expected one of {}, found `{}`", expect, actual),
276 (self.sess.source_map().next_point(self.prev_span),
277 format!("expected one of {} here", short_expect)))
278 } else if expected.is_empty() {
279 (format!("unexpected token: `{}`", actual),
280 (self.prev_span, "unexpected token after this".to_string()))
282 (format!("expected {}, found `{}`", expect, actual),
283 (self.sess.source_map().next_point(self.prev_span),
284 format!("expected {} here", expect)))
286 self.last_unexpected_token_span = Some(self.token.span);
287 let mut err = self.fatal(&msg_exp);
288 if self.token.is_ident_named(sym::and) {
289 err.span_suggestion_short(
291 "use `&&` instead of `and` for the boolean operator",
293 Applicability::MaybeIncorrect,
296 if self.token.is_ident_named(sym::or) {
297 err.span_suggestion_short(
299 "use `||` instead of `or` for the boolean operator",
301 Applicability::MaybeIncorrect,
304 let sp = if self.token == token::Eof {
305 // This is EOF, don't want to point at the following char, but rather the last token
310 match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt {
311 TokenType::Token(t) => Some(t.clone()),
313 }).collect::<Vec<_>>(), err) {
316 return Ok(recovered);
320 let is_semi_suggestable = expected.iter().any(|t| match t {
321 TokenType::Token(token::Semi) => true, // we expect a `;` here
323 }) && ( // a `;` would be expected before the current keyword
324 self.token.is_keyword(kw::Break) ||
325 self.token.is_keyword(kw::Continue) ||
326 self.token.is_keyword(kw::For) ||
327 self.token.is_keyword(kw::If) ||
328 self.token.is_keyword(kw::Let) ||
329 self.token.is_keyword(kw::Loop) ||
330 self.token.is_keyword(kw::Match) ||
331 self.token.is_keyword(kw::Return) ||
332 self.token.is_keyword(kw::While)
334 let sm = self.sess.source_map();
335 match (sm.lookup_line(self.token.span.lo()), sm.lookup_line(sp.lo())) {
336 (Ok(ref a), Ok(ref b)) if a.line != b.line && is_semi_suggestable => {
337 // The spans are in different lines, expected `;` and found `let` or `return`.
338 // High likelihood that it is only a missing `;`.
339 err.span_suggestion_short(
341 "a semicolon may be missing here",
343 Applicability::MaybeIncorrect,
348 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
349 // When the spans are in the same line, it means that the only content between
350 // them is whitespace, point at the found token in that case:
352 // X | () => { syntax error };
353 // | ^^^^^ expected one of 8 possible tokens here
355 // instead of having:
357 // X | () => { syntax error };
358 // | -^^^^^ unexpected token
360 // | expected one of 8 possible tokens here
361 err.span_label(self.token.span, label_exp);
363 _ if self.prev_span == syntax_pos::DUMMY_SP => {
364 // Account for macro context where the previous span might not be
365 // available to avoid incorrect output (#54841).
366 err.span_label(self.token.span, "unexpected token");
369 err.span_label(sp, label_exp);
370 err.span_label(self.token.span, "unexpected token");
373 self.maybe_annotate_with_ascription(&mut err, false);
377 pub fn maybe_annotate_with_ascription(
379 err: &mut DiagnosticBuilder<'_>,
380 maybe_expected_semicolon: bool,
382 if let Some((sp, likely_path)) = self.last_type_ascription {
383 let sm = self.sess.source_map();
384 let next_pos = sm.lookup_char_pos(self.token.span.lo());
385 let op_pos = sm.lookup_char_pos(sp.hi());
390 "maybe write a path separator here",
392 match self.sess.unstable_features {
393 UnstableFeatures::Disallow => Applicability::MachineApplicable,
394 _ => Applicability::MaybeIncorrect,
397 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
400 "try using a semicolon",
402 Applicability::MaybeIncorrect,
404 } else if let UnstableFeatures::Disallow = self.sess.unstable_features {
405 err.span_label(sp, "tried to parse a type due to this");
407 err.span_label(sp, "tried to parse a type due to this type ascription");
409 if let UnstableFeatures::Disallow = self.sess.unstable_features {
410 // Give extra information about type ascription only if it's a nightly compiler.
412 err.note("`#![feature(type_ascription)]` lets you annotate an expression with a \
413 type: `<expr>: <type>`");
414 err.note("for more information, see \
415 https://github.com/rust-lang/rust/issues/23416");
420 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
421 /// passes through any errors encountered. Used for error recovery.
422 crate fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
423 let handler = self.diagnostic();
425 if let Err(ref mut err) = self.parse_seq_to_before_tokens(
428 TokenExpectType::Expect,
429 |p| Ok(p.parse_token_tree()),
435 /// This function checks if there are trailing angle brackets and produces
436 /// a diagnostic to suggest removing them.
438 /// ```ignore (diagnostic)
439 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
440 /// ^^ help: remove extra angle brackets
442 crate fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: TokenKind) {
443 // This function is intended to be invoked after parsing a path segment where there are two
446 // 1. A specific token is expected after the path segment.
447 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
448 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
449 // 2. No specific token is expected after the path segment.
450 // eg. `x.foo` (field access)
452 // This function is called after parsing `.foo` and before parsing the token `end` (if
453 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
456 // We only care about trailing angle brackets if we previously parsed angle bracket
457 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
458 // removed in this case:
460 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
462 // This case is particularly tricky as we won't notice it just looking at the tokens -
463 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
464 // have already been parsed):
466 // `x.foo::<u32>>>(3)`
467 let parsed_angle_bracket_args = segment.args
469 .map(|args| args.is_angle_bracketed())
473 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
474 parsed_angle_bracket_args,
476 if !parsed_angle_bracket_args {
480 // Keep the span at the start so we can highlight the sequence of `>` characters to be
482 let lo = self.token.span;
484 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
485 // (since we might have the field access case and the characters we're eating are
486 // actual operators and not trailing characters - ie `x.foo >> 3`).
487 let mut position = 0;
489 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
490 // many of each (so we can correctly pluralize our error messages) and continue to
492 let mut number_of_shr = 0;
493 let mut number_of_gt = 0;
494 while self.look_ahead(position, |t| {
495 trace!("check_trailing_angle_brackets: t={:?}", t);
496 if *t == token::BinOp(token::BinOpToken::Shr) {
499 } else if *t == token::Gt {
509 // If we didn't find any trailing `>` characters, then we have nothing to error about.
511 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
512 number_of_gt, number_of_shr,
514 if number_of_gt < 1 && number_of_shr < 1 {
518 // Finally, double check that we have our end token as otherwise this is the
520 if self.look_ahead(position, |t| {
521 trace!("check_trailing_angle_brackets: t={:?}", t);
524 // Eat from where we started until the end token so that parsing can continue
525 // as if we didn't have those extra angle brackets.
526 self.eat_to_tokens(&[&end]);
527 let span = lo.until(self.token.span);
529 let plural = number_of_gt > 1 || number_of_shr >= 1;
533 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
537 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
539 Applicability::MachineApplicable,
545 /// Produce an error if comparison operators are chained (RFC #558).
546 /// We only need to check lhs, not rhs, because all comparison ops
547 /// have same precedence and are left-associative
548 crate fn check_no_chained_comparison(&self, lhs: &Expr, outer_op: &AssocOp) {
549 debug_assert!(outer_op.is_comparison(),
550 "check_no_chained_comparison: {:?} is not comparison",
553 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
554 // respan to include both operators
555 let op_span = op.span.to(self.token.span);
556 let mut err = self.struct_span_err(
558 "chained comparison operators require parentheses",
560 if op.node == BinOpKind::Lt &&
561 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
562 *outer_op == AssocOp::Greater // even in a case like the following:
563 { // Foo<Bar<Baz<Qux, ()>>>
565 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
566 err.help("or use `(...)` if you meant to specify fn arguments");
574 crate fn maybe_report_ambiguous_plus(
577 impl_dyn_multi: bool,
580 if !allow_plus && impl_dyn_multi {
581 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
582 self.struct_span_err(ty.span, "ambiguous `+` in a type")
585 "use parentheses to disambiguate",
587 Applicability::MachineApplicable,
593 crate fn maybe_report_invalid_custom_discriminants(
595 variants: &[Spanned<ast::Variant_>],
597 let has_fields = variants.iter().any(|variant| match variant.node.data {
598 VariantData::Tuple(..) | VariantData::Struct(..) => true,
599 VariantData::Unit(..) => false,
602 let discriminant_spans = variants.iter().filter(|variant| match variant.node.data {
603 VariantData::Tuple(..) | VariantData::Struct(..) => false,
604 VariantData::Unit(..) => true,
606 .filter_map(|variant| variant.node.disr_expr.as_ref().map(|c| c.value.span))
607 .collect::<Vec<_>>();
609 if !discriminant_spans.is_empty() && has_fields {
610 let mut err = feature_err(
612 sym::arbitrary_enum_discriminant,
613 discriminant_spans.clone(),
614 crate::feature_gate::GateIssue::Language,
615 "custom discriminant values are not allowed in enums with tuple or struct variants",
617 for sp in discriminant_spans {
618 err.span_label(sp, "disallowed custom discriminant");
620 for variant in variants.iter() {
621 match &variant.node.data {
622 VariantData::Struct(..) => {
625 "struct variant defined here",
628 VariantData::Tuple(..) => {
631 "tuple variant defined here",
634 VariantData::Unit(..) => {}
641 crate fn maybe_recover_from_bad_type_plus(
645 ) -> PResult<'a, ()> {
646 // Do not add `+` to expected tokens.
647 if !allow_plus || !self.token.is_like_plus() {
652 let bounds = self.parse_generic_bounds(None)?;
653 let sum_span = ty.span.to(self.prev_span);
655 let mut err = struct_span_err!(
656 self.sess.span_diagnostic,
659 "expected a path on the left-hand side of `+`, not `{}`",
660 pprust::ty_to_string(ty)
664 TyKind::Rptr(ref lifetime, ref mut_ty) => {
665 let sum_with_parens = pprust::to_string(|s| {
667 s.print_opt_lifetime(lifetime);
668 s.print_mutability(mut_ty.mutbl);
670 s.print_type(&mut_ty.ty);
671 s.print_type_bounds(" +", &bounds);
676 "try adding parentheses",
678 Applicability::MachineApplicable,
681 TyKind::Ptr(..) | TyKind::BareFn(..) => {
682 err.span_label(sum_span, "perhaps you forgot parentheses?");
685 err.span_label(sum_span, "expected a path");
692 /// Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
693 /// Attempt to convert the base expression/pattern/type into a type, parse the `::AssocItem`
694 /// tail, and combine them into a `<Ty>::AssocItem` expression/pattern/type.
695 crate fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
698 allow_recovery: bool,
699 ) -> PResult<'a, P<T>> {
700 // Do not add `::` to expected tokens.
701 if allow_recovery && self.token == token::ModSep {
702 if let Some(ty) = base.to_ty() {
703 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
709 /// Given an already parsed `Ty` parse the `::AssocItem` tail and
710 /// combine them into a `<Ty>::AssocItem` expression/pattern/type.
711 crate fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
715 ) -> PResult<'a, P<T>> {
716 self.expect(&token::ModSep)?;
718 let mut path = ast::Path {
719 segments: Vec::new(),
722 self.parse_path_segments(&mut path.segments, T::PATH_STYLE)?;
723 path.span = ty_span.to(self.prev_span);
726 .span_to_snippet(ty_span)
727 .unwrap_or_else(|_| pprust::ty_to_string(&ty));
729 .struct_span_err(path.span, "missing angle brackets in associated item path")
731 // this is a best-effort recovery
734 format!("<{}>::{}", ty_str, path),
735 Applicability::MaybeIncorrect,
739 let path_span = ty_span.shrink_to_hi(); // use an empty path since `position` == 0
750 crate fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
751 if self.eat(&token::Semi) {
752 let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`");
753 err.span_suggestion_short(
755 "remove this semicolon",
757 Applicability::MachineApplicable,
759 if !items.is_empty() {
760 let previous_item = &items[items.len() - 1];
761 let previous_item_kind_name = match previous_item.node {
762 // say "braced struct" because tuple-structs and
763 // braceless-empty-struct declarations do take a semicolon
764 ItemKind::Struct(..) => Some("braced struct"),
765 ItemKind::Enum(..) => Some("enum"),
766 ItemKind::Trait(..) => Some("trait"),
767 ItemKind::Union(..) => Some("union"),
770 if let Some(name) = previous_item_kind_name {
772 "{} declarations are not followed by a semicolon",
784 /// Create a `DiagnosticBuilder` for an unexpected token `t` and try to recover if it is a
785 /// closing delimiter.
786 pub fn unexpected_try_recover(
789 ) -> PResult<'a, bool /* recovered */> {
790 let token_str = pprust::token_kind_to_string(t);
791 let this_token_str = self.this_token_descr();
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.sess.source_map().next_point(self.prev_span), 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 match (sm.lookup_line(prev_sp.lo()), sm.lookup_line(sp.lo())) {
823 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
824 // When the spans are in the same line, it means that the only content
825 // between them is whitespace, point only at the found token.
826 err.span_label(sp, label_exp);
829 err.span_label(prev_sp, label_exp);
830 err.span_label(sp, "unexpected token");
836 crate fn parse_semi_or_incorrect_foreign_fn_body(
840 ) -> PResult<'a, ()> {
841 if self.token != token::Semi {
842 // this might be an incorrect fn definition (#62109)
843 let parser_snapshot = self.clone();
844 match self.parse_inner_attrs_and_block() {
846 self.struct_span_err(ident.span, "incorrect `fn` inside `extern` block")
847 .span_label(ident.span, "can't have a body")
848 .span_label(body.span, "this body is invalid here")
851 "`extern` blocks define existing foreign functions and `fn`s \
852 inside of them cannot have a body")
853 .help("you might have meant to write a function accessible through ffi, \
854 which can be done by writing `extern fn` outside of the \
856 .note("for more information, visit \
857 https://doc.rust-lang.org/std/keyword.extern.html")
862 mem::replace(self, parser_snapshot);
863 self.expect(&token::Semi)?;
872 /// Consume alternative await syntaxes like `await <expr>`, `await? <expr>`, `await(<expr>)`
873 /// and `await { <expr> }`.
874 crate fn parse_incorrect_await_syntax(
878 ) -> PResult<'a, (Span, ExprKind)> {
879 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
880 let expr = if self.token == token::OpenDelim(token::Brace) {
881 // Handle `await { <expr> }`.
882 // This needs to be handled separatedly from the next arm to avoid
883 // interpreting `await { <expr> }?` as `<expr>?.await`.
884 self.parse_block_expr(
887 BlockCheckMode::Default,
892 }.map_err(|mut err| {
893 err.span_label(await_sp, "while parsing this incorrect await expression");
896 let expr_str = self.span_to_snippet(expr.span)
897 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
898 let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" });
899 let sp = lo.to(expr.span);
900 let app = match expr.node {
901 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
902 _ => Applicability::MachineApplicable,
904 self.struct_span_err(sp, "incorrect use of `await`")
905 .span_suggestion(sp, "`await` is a postfix operation", suggestion, app)
907 Ok((sp, ExprKind::Await(ast::AwaitOrigin::FieldLike, expr)))
910 /// If encountering `future.await()`, consume and emit error.
911 crate fn recover_from_await_method_call(&mut self) {
912 if self.token == token::OpenDelim(token::Paren) &&
913 self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren))
916 let lo = self.token.span;
918 let sp = lo.to(self.token.span);
920 self.struct_span_err(sp, "incorrect use of `await`")
923 "`await` is not a method call, remove the parentheses",
925 Applicability::MachineApplicable,
930 /// Recover a situation like `for ( $pat in $expr )`
931 /// and suggest writing `for $pat in $expr` instead.
933 /// This should be called before parsing the `$block`.
934 crate fn recover_parens_around_for_head(
938 begin_paren: Option<Span>,
940 match (&self.token.kind, begin_paren) {
941 (token::CloseDelim(token::Paren), Some(begin_par_sp)) => {
945 // Remove the `(` from the span of the pattern:
946 .span_to_snippet(pat.span.trim_start(begin_par_sp).unwrap())
947 .unwrap_or_else(|_| pprust::pat_to_string(&pat));
949 self.struct_span_err(self.prev_span, "unexpected closing `)`")
950 .span_label(begin_par_sp, "opening `(`")
952 begin_par_sp.to(self.prev_span),
953 "remove parenthesis in `for` loop",
954 format!("{} in {}", pat_str, pprust::expr_to_string(&expr)),
955 // With e.g. `for (x) in y)` this would replace `(x) in y)`
956 // with `x) in y)` which is syntactically invalid.
957 // However, this is prevented before we get here.
958 Applicability::MachineApplicable,
962 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
963 pat.and_then(|pat| match pat.node {
964 PatKind::Paren(pat) => pat,
972 crate fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
973 self.token.is_ident() &&
974 if let ast::ExprKind::Path(..) = node { true } else { false } &&
975 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
976 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) ||
977 self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz`
978 self.look_ahead(2, |t| t.is_ident()) ||
979 self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
980 self.look_ahead(2, |t| t.is_ident()) ||
981 self.look_ahead(1, |t| t == &token::ModSep) &&
982 (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
983 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
986 crate fn recover_seq_parse_error(
988 delim: token::DelimToken,
990 result: PResult<'a, P<Expr>>,
996 // recover from parse error
997 self.consume_block(delim);
998 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, ThinVec::new())
1003 crate fn recover_closing_delimiter(
1005 tokens: &[TokenKind],
1006 mut err: DiagnosticBuilder<'a>,
1007 ) -> PResult<'a, bool> {
1009 // we want to use the last closing delim that would apply
1010 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1011 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1012 && Some(self.token.span) > unmatched.unclosed_span
1019 // Recover and assume that the detected unclosed delimiter was meant for
1020 // this location. Emit the diagnostic and act as if the delimiter was
1021 // present for the parser's sake.
1023 // Don't attempt to recover from this unclosed delimiter more than once.
1024 let unmatched = self.unclosed_delims.remove(pos);
1025 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1027 // We want to suggest the inclusion of the closing delimiter where it makes
1028 // the most sense, which is immediately after the last token:
1033 // | help: `)` may belong here
1035 // unclosed delimiter
1036 if let Some(sp) = unmatched.unclosed_span {
1037 err.span_label(sp, "unclosed delimiter");
1039 err.span_suggestion_short(
1040 self.sess.source_map().next_point(self.prev_span),
1041 &format!("{} may belong here", delim.to_string()),
1043 Applicability::MaybeIncorrect,
1046 self.expected_tokens.clear(); // reduce errors
1053 /// Recover from `pub` keyword in places where it seems _reasonable_ but isn't valid.
1054 crate fn eat_bad_pub(&mut self) {
1055 if self.token.is_keyword(kw::Pub) {
1056 match self.parse_visibility(false) {
1059 .struct_span_err(vis.span, "unnecessary visibility qualifier")
1060 .span_label(vis.span, "`pub` not permitted here")
1063 Err(mut err) => err.emit(),
1068 // Eat tokens until we can be relatively sure we reached the end of the
1069 // statement. This is something of a best-effort heuristic.
1071 // We terminate when we find an unmatched `}` (without consuming it).
1072 crate fn recover_stmt(&mut self) {
1073 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1076 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
1077 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1078 // approximate - it can mean we break too early due to macros, but that
1079 // should only lead to sub-optimal recovery, not inaccurate parsing).
1081 // If `break_on_block` is `Break`, then we will stop consuming tokens
1082 // after finding (and consuming) a brace-delimited block.
1083 crate fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
1084 let mut brace_depth = 0;
1085 let mut bracket_depth = 0;
1086 let mut in_block = false;
1087 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
1088 break_on_semi, break_on_block);
1090 debug!("recover_stmt_ loop {:?}", self.token);
1091 match self.token.kind {
1092 token::OpenDelim(token::DelimToken::Brace) => {
1095 if break_on_block == BlockMode::Break &&
1097 bracket_depth == 0 {
1101 token::OpenDelim(token::DelimToken::Bracket) => {
1105 token::CloseDelim(token::DelimToken::Brace) => {
1106 if brace_depth == 0 {
1107 debug!("recover_stmt_ return - close delim {:?}", self.token);
1112 if in_block && bracket_depth == 0 && brace_depth == 0 {
1113 debug!("recover_stmt_ return - block end {:?}", self.token);
1117 token::CloseDelim(token::DelimToken::Bracket) => {
1119 if bracket_depth < 0 {
1125 debug!("recover_stmt_ return - Eof");
1130 if break_on_semi == SemiColonMode::Break &&
1132 bracket_depth == 0 {
1133 debug!("recover_stmt_ return - Semi");
1137 token::Comma if break_on_semi == SemiColonMode::Comma &&
1139 bracket_depth == 0 =>
1141 debug!("recover_stmt_ return - Semi");
1151 crate fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1152 if self.eat_keyword(kw::In) {
1153 // a common typo: `for _ in in bar {}`
1154 self.struct_span_err(self.prev_span, "expected iterable, found keyword `in`")
1155 .span_suggestion_short(
1156 in_span.until(self.prev_span),
1157 "remove the duplicated `in`",
1159 Applicability::MachineApplicable,
1165 crate fn expected_semi_or_open_brace(&mut self) -> PResult<'a, ast::TraitItem> {
1166 let token_str = self.this_token_descr();
1167 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}", token_str));
1168 err.span_label(self.token.span, "expected `;` or `{`");
1172 crate fn eat_incorrect_doc_comment_for_arg_type(&mut self) {
1173 if let token::DocComment(_) = self.token.kind {
1174 self.struct_span_err(
1176 "documentation comments cannot be applied to a function parameter's type",
1178 .span_label(self.token.span, "doc comments are not allowed here")
1181 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1182 *t == token::OpenDelim(token::Bracket)
1184 let lo = self.token.span;
1185 // Skip every token until next possible arg.
1186 while self.token != token::CloseDelim(token::Bracket) {
1189 let sp = lo.to(self.token.span);
1191 self.struct_span_err(
1193 "attributes cannot be applied to a function parameter's type",
1195 .span_label(sp, "attributes are not allowed here")
1200 crate fn argument_without_type(
1202 err: &mut DiagnosticBuilder<'_>,
1205 is_trait_item: bool,
1206 ) -> Option<Ident> {
1207 // If we find a pattern followed by an identifier, it could be an (incorrect)
1208 // C-style parameter declaration.
1209 if self.check_ident() && self.look_ahead(1, |t| {
1210 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1211 }) { // `fn foo(String s) {}`
1212 let ident = self.parse_ident().unwrap();
1213 let span = pat.span.with_hi(ident.span.hi());
1215 err.span_suggestion(
1217 "declare the type after the parameter binding",
1218 String::from("<identifier>: <type>"),
1219 Applicability::HasPlaceholders,
1222 } else if let PatKind::Ident(_, ident, _) = pat.node {
1223 if require_name && (
1225 self.token == token::Comma ||
1226 self.token == token::CloseDelim(token::Paren)
1227 ) { // `fn foo(a, b) {}` or `fn foo(usize, usize) {}`
1228 err.span_suggestion(
1230 "if this was a parameter name, give it a type",
1231 format!("{}: TypeName", ident),
1232 Applicability::HasPlaceholders,
1234 err.span_suggestion(
1236 "if this is a type, explicitly ignore the parameter name",
1237 format!("_: {}", ident),
1238 Applicability::MachineApplicable,
1240 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1247 crate fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
1248 let pat = self.parse_pat(Some("argument name"))?;
1249 self.expect(&token::Colon)?;
1250 let ty = self.parse_ty()?;
1253 .struct_span_err_with_code(
1255 "patterns aren't allowed in methods without bodies",
1256 DiagnosticId::Error("E0642".into()),
1258 .span_suggestion_short(
1260 "give this argument a name or use an underscore to ignore it",
1262 Applicability::MachineApplicable,
1266 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1268 node: PatKind::Wild,
1270 id: ast::DUMMY_NODE_ID
1275 crate fn recover_bad_self_arg(
1278 is_trait_item: bool,
1279 ) -> PResult<'a, ast::Arg> {
1280 let sp = arg.pat.span;
1281 arg.ty.node = TyKind::Err;
1282 let mut err = self.struct_span_err(sp, "unexpected `self` parameter in function");
1284 err.span_label(sp, "must be the first associated function parameter");
1286 err.span_label(sp, "not valid as function parameter");
1287 err.note("`self` is only valid as the first parameter of an associated function");
1293 crate fn consume_block(&mut self, delim: token::DelimToken) {
1294 let mut brace_depth = 0;
1296 if self.eat(&token::OpenDelim(delim)) {
1298 } else if self.eat(&token::CloseDelim(delim)) {
1299 if brace_depth == 0 {
1305 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
1313 crate fn expected_expression_found(&self) -> DiagnosticBuilder<'a> {
1314 let (span, msg) = match (&self.token.kind, self.subparser_name) {
1315 (&token::Eof, Some(origin)) => {
1316 let sp = self.sess.source_map().next_point(self.token.span);
1317 (sp, format!("expected expression, found end of {}", origin))
1319 _ => (self.token.span, format!(
1320 "expected expression, found {}",
1321 self.this_token_descr(),
1324 let mut err = self.struct_span_err(span, &msg);
1325 let sp = self.sess.source_map().start_point(self.token.span);
1326 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
1327 self.sess.expr_parentheses_needed(&mut err, *sp, None);
1329 err.span_label(span, "expected expression");
1333 /// Replace duplicated recovered arguments with `_` pattern to avoid unecessary errors.
1335 /// This is necessary because at this point we don't know whether we parsed a function with
1336 /// anonymous arguments or a function with names but no types. In order to minimize
1337 /// unecessary errors, we assume the arguments are in the shape of `fn foo(a, b, c)` where
1338 /// the arguments are *names* (so we don't emit errors about not being able to find `b` in
1339 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
1340 /// we deduplicate them to not complain about duplicated argument names.
1341 crate fn deduplicate_recovered_arg_names(&self, fn_inputs: &mut Vec<Arg>) {
1342 let mut seen_inputs = FxHashSet::default();
1343 for input in fn_inputs.iter_mut() {
1344 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) = (
1345 &input.pat.node, &input.ty.node,
1351 if let Some(ident) = opt_ident {
1352 if seen_inputs.contains(&ident) {
1353 input.pat.node = PatKind::Wild;
1355 seen_inputs.insert(ident);