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};
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, 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 expected_ident_found(&self) -> DiagnosticBuilder<'a> {
203 let mut err = self.struct_span_err(
205 &format!("expected identifier, found {}", self.this_token_descr()),
207 if let token::Ident(name, false) = self.token.kind {
208 if Ident::new(name, self.token.span).is_raw_guess() {
211 "you can escape reserved keywords to use them as identifiers",
212 format!("r#{}", name),
213 Applicability::MaybeIncorrect,
217 if let Some(token_descr) = self.token_descr() {
218 err.span_label(self.token.span, format!("expected identifier, found {}", token_descr));
220 err.span_label(self.token.span, "expected identifier");
221 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
226 Applicability::MachineApplicable,
233 pub fn expected_one_of_not_found(
235 edible: &[TokenKind],
236 inedible: &[TokenKind],
237 ) -> PResult<'a, bool /* recovered */> {
238 fn tokens_to_string(tokens: &[TokenType]) -> String {
239 let mut i = tokens.iter();
240 // This might be a sign we need a connect method on Iterator.
242 .map_or(String::new(), |t| t.to_string());
243 i.enumerate().fold(b, |mut b, (i, a)| {
244 if tokens.len() > 2 && i == tokens.len() - 2 {
246 } else if tokens.len() == 2 && i == tokens.len() - 2 {
251 b.push_str(&a.to_string());
256 let mut expected = edible.iter()
257 .map(|x| TokenType::Token(x.clone()))
258 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
259 .chain(self.expected_tokens.iter().cloned())
260 .collect::<Vec<_>>();
261 expected.sort_by_cached_key(|x| x.to_string());
263 let expect = tokens_to_string(&expected[..]);
264 let actual = self.this_token_to_string();
265 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
266 let short_expect = if expected.len() > 6 {
267 format!("{} possible tokens", expected.len())
271 (format!("expected one of {}, found `{}`", expect, actual),
272 (self.sess.source_map().next_point(self.prev_span),
273 format!("expected one of {} here", short_expect)))
274 } else if expected.is_empty() {
275 (format!("unexpected token: `{}`", actual),
276 (self.prev_span, "unexpected token after this".to_string()))
278 (format!("expected {}, found `{}`", expect, actual),
279 (self.sess.source_map().next_point(self.prev_span),
280 format!("expected {} here", expect)))
282 self.last_unexpected_token_span = Some(self.token.span);
283 let mut err = self.fatal(&msg_exp);
284 if self.token.is_ident_named(sym::and) {
285 err.span_suggestion_short(
287 "use `&&` instead of `and` for the boolean operator",
289 Applicability::MaybeIncorrect,
292 if self.token.is_ident_named(sym::or) {
293 err.span_suggestion_short(
295 "use `||` instead of `or` for the boolean operator",
297 Applicability::MaybeIncorrect,
300 let sp = if self.token == token::Eof {
301 // This is EOF, don't want to point at the following char, but rather the last token
306 match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt {
307 TokenType::Token(t) => Some(t.clone()),
309 }).collect::<Vec<_>>(), err) {
312 return Ok(recovered);
316 let is_semi_suggestable = expected.iter().any(|t| match t {
317 TokenType::Token(token::Semi) => true, // we expect a `;` here
319 }) && ( // a `;` would be expected before the current keyword
320 self.token.is_keyword(kw::Break) ||
321 self.token.is_keyword(kw::Continue) ||
322 self.token.is_keyword(kw::For) ||
323 self.token.is_keyword(kw::If) ||
324 self.token.is_keyword(kw::Let) ||
325 self.token.is_keyword(kw::Loop) ||
326 self.token.is_keyword(kw::Match) ||
327 self.token.is_keyword(kw::Return) ||
328 self.token.is_keyword(kw::While)
330 let sm = self.sess.source_map();
331 match (sm.lookup_line(self.token.span.lo()), sm.lookup_line(sp.lo())) {
332 (Ok(ref a), Ok(ref b)) if a.line != b.line && is_semi_suggestable => {
333 // The spans are in different lines, expected `;` and found `let` or `return`.
334 // High likelihood that it is only a missing `;`.
335 err.span_suggestion_short(
337 "a semicolon may be missing here",
339 Applicability::MaybeIncorrect,
344 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
345 // When the spans are in the same line, it means that the only content between
346 // them is whitespace, point at the found token in that case:
348 // X | () => { syntax error };
349 // | ^^^^^ expected one of 8 possible tokens here
351 // instead of having:
353 // X | () => { syntax error };
354 // | -^^^^^ unexpected token
356 // | expected one of 8 possible tokens here
357 err.span_label(self.token.span, label_exp);
359 _ if self.prev_span == syntax_pos::DUMMY_SP => {
360 // Account for macro context where the previous span might not be
361 // available to avoid incorrect output (#54841).
362 err.span_label(self.token.span, "unexpected token");
365 err.span_label(sp, label_exp);
366 err.span_label(self.token.span, "unexpected token");
369 self.maybe_annotate_with_ascription(&mut err, false);
373 pub fn maybe_annotate_with_ascription(
375 err: &mut DiagnosticBuilder<'_>,
376 maybe_expected_semicolon: bool,
378 if let Some((sp, likely_path)) = self.last_type_ascription {
379 let sm = self.sess.source_map();
380 let next_pos = sm.lookup_char_pos(self.token.span.lo());
381 let op_pos = sm.lookup_char_pos(sp.hi());
386 "maybe write a path separator here",
388 match self.sess.unstable_features {
389 UnstableFeatures::Disallow => Applicability::MachineApplicable,
390 _ => Applicability::MaybeIncorrect,
393 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
396 "try using a semicolon",
398 Applicability::MaybeIncorrect,
400 } else if let UnstableFeatures::Disallow = self.sess.unstable_features {
401 err.span_label(sp, "tried to parse a type due to this");
403 err.span_label(sp, "tried to parse a type due to this type ascription");
405 if let UnstableFeatures::Disallow = self.sess.unstable_features {
406 // Give extra information about type ascription only if it's a nightly compiler.
408 err.note("`#![feature(type_ascription)]` lets you annotate an expression with a \
409 type: `<expr>: <type>`");
410 err.note("for more information, see \
411 https://github.com/rust-lang/rust/issues/23416");
416 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
417 /// passes through any errors encountered. Used for error recovery.
418 crate fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
419 let handler = self.diagnostic();
421 if let Err(ref mut err) = self.parse_seq_to_before_tokens(
424 TokenExpectType::Expect,
425 |p| Ok(p.parse_token_tree()),
431 /// This function checks if there are trailing angle brackets and produces
432 /// a diagnostic to suggest removing them.
434 /// ```ignore (diagnostic)
435 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
436 /// ^^ help: remove extra angle brackets
438 crate fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: TokenKind) {
439 // This function is intended to be invoked after parsing a path segment where there are two
442 // 1. A specific token is expected after the path segment.
443 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
444 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
445 // 2. No specific token is expected after the path segment.
446 // eg. `x.foo` (field access)
448 // This function is called after parsing `.foo` and before parsing the token `end` (if
449 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
452 // We only care about trailing angle brackets if we previously parsed angle bracket
453 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
454 // removed in this case:
456 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
458 // This case is particularly tricky as we won't notice it just looking at the tokens -
459 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
460 // have already been parsed):
462 // `x.foo::<u32>>>(3)`
463 let parsed_angle_bracket_args = segment.args
465 .map(|args| args.is_angle_bracketed())
469 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
470 parsed_angle_bracket_args,
472 if !parsed_angle_bracket_args {
476 // Keep the span at the start so we can highlight the sequence of `>` characters to be
478 let lo = self.token.span;
480 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
481 // (since we might have the field access case and the characters we're eating are
482 // actual operators and not trailing characters - ie `x.foo >> 3`).
483 let mut position = 0;
485 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
486 // many of each (so we can correctly pluralize our error messages) and continue to
488 let mut number_of_shr = 0;
489 let mut number_of_gt = 0;
490 while self.look_ahead(position, |t| {
491 trace!("check_trailing_angle_brackets: t={:?}", t);
492 if *t == token::BinOp(token::BinOpToken::Shr) {
495 } else if *t == token::Gt {
505 // If we didn't find any trailing `>` characters, then we have nothing to error about.
507 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
508 number_of_gt, number_of_shr,
510 if number_of_gt < 1 && number_of_shr < 1 {
514 // Finally, double check that we have our end token as otherwise this is the
516 if self.look_ahead(position, |t| {
517 trace!("check_trailing_angle_brackets: t={:?}", t);
520 // Eat from where we started until the end token so that parsing can continue
521 // as if we didn't have those extra angle brackets.
522 self.eat_to_tokens(&[&end]);
523 let span = lo.until(self.token.span);
525 let plural = number_of_gt > 1 || number_of_shr >= 1;
529 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
533 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
535 Applicability::MachineApplicable,
541 /// Produce an error if comparison operators are chained (RFC #558).
542 /// We only need to check lhs, not rhs, because all comparison ops
543 /// have same precedence and are left-associative
544 crate fn check_no_chained_comparison(&self, lhs: &Expr, outer_op: &AssocOp) {
545 debug_assert!(outer_op.is_comparison(),
546 "check_no_chained_comparison: {:?} is not comparison",
549 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
550 // respan to include both operators
551 let op_span = op.span.to(self.token.span);
552 let mut err = self.diagnostic().struct_span_err(op_span,
553 "chained comparison operators require parentheses");
554 if op.node == BinOpKind::Lt &&
555 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
556 *outer_op == AssocOp::Greater // even in a case like the following:
557 { // Foo<Bar<Baz<Qux, ()>>>
559 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
560 err.help("or use `(...)` if you meant to specify fn arguments");
568 crate fn maybe_report_ambiguous_plus(
571 impl_dyn_multi: bool,
574 if !allow_plus && impl_dyn_multi {
575 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
576 self.struct_span_err(ty.span, "ambiguous `+` in a type")
579 "use parentheses to disambiguate",
581 Applicability::MachineApplicable,
587 crate fn maybe_report_invalid_custom_discriminants(
589 variants: &[Spanned<ast::Variant_>],
591 let has_fields = variants.iter().any(|variant| match variant.node.data {
592 VariantData::Tuple(..) | VariantData::Struct(..) => true,
593 VariantData::Unit(..) => false,
596 let discriminant_spans = variants.iter().filter(|variant| match variant.node.data {
597 VariantData::Tuple(..) | VariantData::Struct(..) => false,
598 VariantData::Unit(..) => true,
600 .filter_map(|variant| variant.node.disr_expr.as_ref().map(|c| c.value.span))
601 .collect::<Vec<_>>();
603 if !discriminant_spans.is_empty() && has_fields {
604 let mut err = feature_err(
606 sym::arbitrary_enum_discriminant,
607 discriminant_spans.clone(),
608 crate::feature_gate::GateIssue::Language,
609 "custom discriminant values are not allowed in enums with tuple or struct variants",
611 for sp in discriminant_spans {
612 err.span_label(sp, "disallowed custom discriminant");
614 for variant in variants.iter() {
615 match &variant.node.data {
616 VariantData::Struct(..) => {
619 "struct variant defined here",
622 VariantData::Tuple(..) => {
625 "tuple variant defined here",
628 VariantData::Unit(..) => {}
635 crate fn maybe_recover_from_bad_type_plus(
639 ) -> PResult<'a, ()> {
640 // Do not add `+` to expected tokens.
641 if !allow_plus || !self.token.is_like_plus() {
646 let bounds = self.parse_generic_bounds(None)?;
647 let sum_span = ty.span.to(self.prev_span);
649 let mut err = struct_span_err!(
650 self.sess.span_diagnostic,
653 "expected a path on the left-hand side of `+`, not `{}`",
654 pprust::ty_to_string(ty)
658 TyKind::Rptr(ref lifetime, ref mut_ty) => {
659 let sum_with_parens = pprust::to_string(|s| {
661 s.print_opt_lifetime(lifetime);
662 s.print_mutability(mut_ty.mutbl);
664 s.print_type(&mut_ty.ty);
665 s.print_type_bounds(" +", &bounds);
670 "try adding parentheses",
672 Applicability::MachineApplicable,
675 TyKind::Ptr(..) | TyKind::BareFn(..) => {
676 err.span_label(sum_span, "perhaps you forgot parentheses?");
679 err.span_label(sum_span, "expected a path");
686 /// Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
687 /// Attempt to convert the base expression/pattern/type into a type, parse the `::AssocItem`
688 /// tail, and combine them into a `<Ty>::AssocItem` expression/pattern/type.
689 crate fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
692 allow_recovery: bool,
693 ) -> PResult<'a, P<T>> {
694 // Do not add `::` to expected tokens.
695 if allow_recovery && self.token == token::ModSep {
696 if let Some(ty) = base.to_ty() {
697 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
703 /// Given an already parsed `Ty` parse the `::AssocItem` tail and
704 /// combine them into a `<Ty>::AssocItem` expression/pattern/type.
705 crate fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
709 ) -> PResult<'a, P<T>> {
710 self.expect(&token::ModSep)?;
712 let mut path = ast::Path {
713 segments: Vec::new(),
716 self.parse_path_segments(&mut path.segments, T::PATH_STYLE)?;
717 path.span = ty_span.to(self.prev_span);
722 .span_to_snippet(ty_span)
723 .unwrap_or_else(|_| pprust::ty_to_string(&ty));
725 .struct_span_err(path.span, "missing angle brackets in associated item path")
727 // this is a best-effort recovery
730 format!("<{}>::{}", ty_str, path),
731 Applicability::MaybeIncorrect,
735 let path_span = ty_span.shrink_to_hi(); // use an empty path since `position` == 0
746 crate fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
747 if self.eat(&token::Semi) {
748 let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`");
749 err.span_suggestion_short(
751 "remove this semicolon",
753 Applicability::MachineApplicable,
755 if !items.is_empty() {
756 let previous_item = &items[items.len() - 1];
757 let previous_item_kind_name = match previous_item.node {
758 // say "braced struct" because tuple-structs and
759 // braceless-empty-struct declarations do take a semicolon
760 ItemKind::Struct(..) => Some("braced struct"),
761 ItemKind::Enum(..) => Some("enum"),
762 ItemKind::Trait(..) => Some("trait"),
763 ItemKind::Union(..) => Some("union"),
766 if let Some(name) = previous_item_kind_name {
768 "{} declarations are not followed by a semicolon",
780 /// Create a `DiagnosticBuilder` for an unexpected token `t` and try to recover if it is a
781 /// closing delimiter.
782 pub fn unexpected_try_recover(
785 ) -> PResult<'a, bool /* recovered */> {
786 let token_str = pprust::token_kind_to_string(t);
787 let this_token_str = self.this_token_descr();
788 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
789 // Point at the end of the macro call when reaching end of macro arguments.
790 (token::Eof, Some(_)) => {
791 let sp = self.sess.source_map().next_point(self.token.span);
794 // We don't want to point at the following span after DUMMY_SP.
795 // This happens when the parser finds an empty TokenStream.
796 _ if self.prev_span == DUMMY_SP => (self.token.span, self.token.span),
797 // EOF, don't want to point at the following char, but rather the last token.
798 (token::Eof, None) => (self.prev_span, self.token.span),
799 _ => (self.sess.source_map().next_point(self.prev_span), self.token.span),
802 "expected `{}`, found {}",
804 match (&self.token.kind, self.subparser_name) {
805 (token::Eof, Some(origin)) => format!("end of {}", origin),
809 let mut err = self.struct_span_err(sp, &msg);
810 let label_exp = format!("expected `{}`", token_str);
811 match self.recover_closing_delimiter(&[t.clone()], err) {
814 return Ok(recovered);
817 let sm = self.sess.source_map();
818 match (sm.lookup_line(prev_sp.lo()), sm.lookup_line(sp.lo())) {
819 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
820 // When the spans are in the same line, it means that the only content
821 // between them is whitespace, point only at the found token.
822 err.span_label(sp, label_exp);
825 err.span_label(prev_sp, label_exp);
826 err.span_label(sp, "unexpected token");
832 crate fn parse_semi_or_incorrect_foreign_fn_body(
836 ) -> PResult<'a, ()> {
837 if self.token != token::Semi {
838 // this might be an incorrect fn definition (#62109)
839 let parser_snapshot = self.clone();
840 match self.parse_inner_attrs_and_block() {
842 self.struct_span_err(ident.span, "incorrect `fn` inside `extern` block")
843 .span_label(ident.span, "can't have a body")
844 .span_label(body.span, "this body is invalid here")
847 "`extern` blocks define existing foreign functions and `fn`s \
848 inside of them cannot have a body")
849 .help("you might have meant to write a function accessible through ffi, \
850 which can be done by writing `extern fn` outside of the \
852 .note("for more information, visit \
853 https://doc.rust-lang.org/std/keyword.extern.html")
858 mem::replace(self, parser_snapshot);
859 self.expect(&token::Semi)?;
868 /// Consume alternative await syntaxes like `await <expr>`, `await? <expr>`, `await(<expr>)`
869 /// and `await { <expr> }`.
870 crate fn parse_incorrect_await_syntax(
874 ) -> PResult<'a, (Span, ExprKind)> {
875 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
876 let expr = if self.token == token::OpenDelim(token::Brace) {
877 // Handle `await { <expr> }`.
878 // This needs to be handled separatedly from the next arm to avoid
879 // interpreting `await { <expr> }?` as `<expr>?.await`.
880 self.parse_block_expr(
883 BlockCheckMode::Default,
888 }.map_err(|mut err| {
889 err.span_label(await_sp, "while parsing this incorrect await expression");
892 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
893 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
894 let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" });
895 let sp = lo.to(expr.span);
896 let app = match expr.node {
897 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
898 _ => Applicability::MachineApplicable,
900 self.struct_span_err(sp, "incorrect use of `await`")
901 .span_suggestion(sp, "`await` is a postfix operation", suggestion, app)
903 Ok((sp, ExprKind::Await(ast::AwaitOrigin::FieldLike, expr)))
906 /// If encountering `future.await()`, consume and emit error.
907 crate fn recover_from_await_method_call(&mut self) {
908 if self.token == token::OpenDelim(token::Paren) &&
909 self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren))
912 let lo = self.token.span;
914 let sp = lo.to(self.token.span);
916 self.struct_span_err(sp, "incorrect use of `await`")
919 "`await` is not a method call, remove the parentheses",
921 Applicability::MachineApplicable,
926 crate fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
927 self.token.is_ident() &&
928 if let ast::ExprKind::Path(..) = node { true } else { false } &&
929 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
930 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) ||
931 self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz`
932 self.look_ahead(2, |t| t.is_ident()) ||
933 self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
934 self.look_ahead(2, |t| t.is_ident()) ||
935 self.look_ahead(1, |t| t == &token::ModSep) &&
936 (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
937 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
940 crate fn recover_seq_parse_error(
942 delim: token::DelimToken,
944 result: PResult<'a, P<Expr>>,
950 // recover from parse error
951 self.consume_block(delim);
952 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, ThinVec::new())
957 crate fn recover_closing_delimiter(
959 tokens: &[TokenKind],
960 mut err: DiagnosticBuilder<'a>,
961 ) -> PResult<'a, bool> {
963 // we want to use the last closing delim that would apply
964 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
965 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
966 && Some(self.token.span) > unmatched.unclosed_span
973 // Recover and assume that the detected unclosed delimiter was meant for
974 // this location. Emit the diagnostic and act as if the delimiter was
975 // present for the parser's sake.
977 // Don't attempt to recover from this unclosed delimiter more than once.
978 let unmatched = self.unclosed_delims.remove(pos);
979 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
981 // We want to suggest the inclusion of the closing delimiter where it makes
982 // the most sense, which is immediately after the last token:
987 // | help: `)` may belong here
989 // unclosed delimiter
990 if let Some(sp) = unmatched.unclosed_span {
991 err.span_label(sp, "unclosed delimiter");
993 err.span_suggestion_short(
994 self.sess.source_map().next_point(self.prev_span),
995 &format!("{} may belong here", delim.to_string()),
997 Applicability::MaybeIncorrect,
1000 self.expected_tokens.clear(); // reduce errors
1007 /// Recover from `pub` keyword in places where it seems _reasonable_ but isn't valid.
1008 crate fn eat_bad_pub(&mut self) {
1009 if self.token.is_keyword(kw::Pub) {
1010 match self.parse_visibility(false) {
1013 .struct_span_err(vis.span, "unnecessary visibility qualifier")
1014 .span_label(vis.span, "`pub` not permitted here")
1017 Err(mut err) => err.emit(),
1022 // Eat tokens until we can be relatively sure we reached the end of the
1023 // statement. This is something of a best-effort heuristic.
1025 // We terminate when we find an unmatched `}` (without consuming it).
1026 crate fn recover_stmt(&mut self) {
1027 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1030 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
1031 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1032 // approximate - it can mean we break too early due to macros, but that
1033 // should only lead to sub-optimal recovery, not inaccurate parsing).
1035 // If `break_on_block` is `Break`, then we will stop consuming tokens
1036 // after finding (and consuming) a brace-delimited block.
1037 crate fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
1038 let mut brace_depth = 0;
1039 let mut bracket_depth = 0;
1040 let mut in_block = false;
1041 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
1042 break_on_semi, break_on_block);
1044 debug!("recover_stmt_ loop {:?}", self.token);
1045 match self.token.kind {
1046 token::OpenDelim(token::DelimToken::Brace) => {
1049 if break_on_block == BlockMode::Break &&
1051 bracket_depth == 0 {
1055 token::OpenDelim(token::DelimToken::Bracket) => {
1059 token::CloseDelim(token::DelimToken::Brace) => {
1060 if brace_depth == 0 {
1061 debug!("recover_stmt_ return - close delim {:?}", self.token);
1066 if in_block && bracket_depth == 0 && brace_depth == 0 {
1067 debug!("recover_stmt_ return - block end {:?}", self.token);
1071 token::CloseDelim(token::DelimToken::Bracket) => {
1073 if bracket_depth < 0 {
1079 debug!("recover_stmt_ return - Eof");
1084 if break_on_semi == SemiColonMode::Break &&
1086 bracket_depth == 0 {
1087 debug!("recover_stmt_ return - Semi");
1091 token::Comma if break_on_semi == SemiColonMode::Comma &&
1093 bracket_depth == 0 =>
1095 debug!("recover_stmt_ return - Semi");
1105 crate fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1106 if self.eat_keyword(kw::In) {
1107 // a common typo: `for _ in in bar {}`
1108 let mut err = self.sess.span_diagnostic.struct_span_err(
1110 "expected iterable, found keyword `in`",
1112 err.span_suggestion_short(
1113 in_span.until(self.prev_span),
1114 "remove the duplicated `in`",
1116 Applicability::MachineApplicable,
1122 crate fn expected_semi_or_open_brace(&mut self) -> PResult<'a, ast::TraitItem> {
1123 let token_str = self.this_token_descr();
1124 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}", token_str));
1125 err.span_label(self.token.span, "expected `;` or `{`");
1129 crate fn eat_incorrect_doc_comment_for_arg_type(&mut self) {
1130 if let token::DocComment(_) = self.token.kind {
1131 let mut err = self.diagnostic().struct_span_err(
1133 "documentation comments cannot be applied to a function parameter's type",
1135 err.span_label(self.token.span, "doc comments are not allowed here");
1138 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1139 *t == token::OpenDelim(token::Bracket)
1141 let lo = self.token.span;
1142 // Skip every token until next possible arg.
1143 while self.token != token::CloseDelim(token::Bracket) {
1146 let sp = lo.to(self.token.span);
1148 let mut err = self.diagnostic().struct_span_err(
1150 "attributes cannot be applied to a function parameter's type",
1152 err.span_label(sp, "attributes are not allowed here");
1157 crate fn argument_without_type(
1159 err: &mut DiagnosticBuilder<'_>,
1162 is_trait_item: bool,
1163 ) -> Option<Ident> {
1164 // If we find a pattern followed by an identifier, it could be an (incorrect)
1165 // C-style parameter declaration.
1166 if self.check_ident() && self.look_ahead(1, |t| {
1167 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1168 }) { // `fn foo(String s) {}`
1169 let ident = self.parse_ident().unwrap();
1170 let span = pat.span.with_hi(ident.span.hi());
1172 err.span_suggestion(
1174 "declare the type after the parameter binding",
1175 String::from("<identifier>: <type>"),
1176 Applicability::HasPlaceholders,
1179 } else if let PatKind::Ident(_, ident, _) = pat.node {
1180 if require_name && (
1182 self.token == token::Comma ||
1183 self.token == token::CloseDelim(token::Paren)
1184 ) { // `fn foo(a, b) {}` or `fn foo(usize, usize) {}`
1185 err.span_suggestion(
1187 "if this was a parameter name, give it a type",
1188 format!("{}: TypeName", ident),
1189 Applicability::HasPlaceholders,
1191 err.span_suggestion(
1193 "if this is a type, explicitly ignore the parameter name",
1194 format!("_: {}", ident),
1195 Applicability::MachineApplicable,
1197 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1204 crate fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
1205 let pat = self.parse_pat(Some("argument name"))?;
1206 self.expect(&token::Colon)?;
1207 let ty = self.parse_ty()?;
1209 let mut err = self.diagnostic().struct_span_err_with_code(
1211 "patterns aren't allowed in methods without bodies",
1212 DiagnosticId::Error("E0642".into()),
1214 err.span_suggestion_short(
1216 "give this argument a name or use an underscore to ignore it",
1218 Applicability::MachineApplicable,
1222 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1224 node: PatKind::Wild,
1226 id: ast::DUMMY_NODE_ID
1231 crate fn recover_bad_self_arg(
1234 is_trait_item: bool,
1235 ) -> PResult<'a, ast::Arg> {
1236 let sp = arg.pat.span;
1237 arg.ty.node = TyKind::Err;
1238 let mut err = self.struct_span_err(sp, "unexpected `self` parameter in function");
1240 err.span_label(sp, "must be the first associated function parameter");
1242 err.span_label(sp, "not valid as function parameter");
1243 err.note("`self` is only valid as the first parameter of an associated function");
1249 crate fn consume_block(&mut self, delim: token::DelimToken) {
1250 let mut brace_depth = 0;
1252 if self.eat(&token::OpenDelim(delim)) {
1254 } else if self.eat(&token::CloseDelim(delim)) {
1255 if brace_depth == 0 {
1261 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
1269 crate fn expected_expression_found(&self) -> DiagnosticBuilder<'a> {
1270 let (span, msg) = match (&self.token.kind, self.subparser_name) {
1271 (&token::Eof, Some(origin)) => {
1272 let sp = self.sess.source_map().next_point(self.token.span);
1273 (sp, format!("expected expression, found end of {}", origin))
1275 _ => (self.token.span, format!(
1276 "expected expression, found {}",
1277 self.this_token_descr(),
1280 let mut err = self.struct_span_err(span, &msg);
1281 let sp = self.sess.source_map().start_point(self.token.span);
1282 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
1283 self.sess.expr_parentheses_needed(&mut err, *sp, None);
1285 err.span_label(span, "expected expression");
1289 /// Replace duplicated recovered arguments with `_` pattern to avoid unecessary errors.
1291 /// This is necessary because at this point we don't know whether we parsed a function with
1292 /// anonymous arguments or a function with names but no types. In order to minimize
1293 /// unecessary errors, we assume the arguments are in the shape of `fn foo(a, b, c)` where
1294 /// the arguments are *names* (so we don't emit errors about not being able to find `b` in
1295 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
1296 /// we deduplicate them to not complain about duplicated argument names.
1297 crate fn deduplicate_recovered_arg_names(&self, fn_inputs: &mut Vec<Arg>) {
1298 let mut seen_inputs = FxHashSet::default();
1299 for input in fn_inputs.iter_mut() {
1300 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) = (
1301 &input.pat.node, &input.ty.node,
1307 if let Some(ident) = opt_ident {
1308 if seen_inputs.contains(&ident) {
1309 input.pat.node = PatKind::Wild;
1311 seen_inputs.insert(ident);