]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/diagnostics.rs
pin docs: add some forward references
[rust.git] / src / librustc_parse / parser / diagnostics.rs
1 use super::ty::AllowPlus;
2 use super::{BlockMode, Parser, PathStyle, SemiColonMode, SeqSep, TokenExpectType, TokenType};
3
4 use rustc_ast::ast::{
5     self, AngleBracketedArgs, AttrVec, BinOpKind, BindingMode, BlockCheckMode, Expr, ExprKind,
6     Item, ItemKind, Mutability, Param, Pat, PatKind, PathSegment, QSelf, Ty, TyKind,
7 };
8 use rustc_ast::ptr::P;
9 use rustc_ast::token::{self, Lit, LitKind, TokenKind};
10 use rustc_ast::util::parser::AssocOp;
11 use rustc_ast_pretty::pprust;
12 use rustc_data_structures::fx::FxHashSet;
13 use rustc_errors::{pluralize, struct_span_err};
14 use rustc_errors::{Applicability, DiagnosticBuilder, Handler, PResult};
15 use rustc_span::source_map::Spanned;
16 use rustc_span::symbol::{kw, Ident};
17 use rustc_span::{MultiSpan, Span, SpanSnippetError, DUMMY_SP};
18
19 use log::{debug, trace};
20
21 const TURBOFISH: &str = "use `::<...>` instead of `<...>` to specify type arguments";
22
23 /// Creates a placeholder argument.
24 pub(super) fn dummy_arg(ident: Ident) -> Param {
25     let pat = P(Pat {
26         id: ast::DUMMY_NODE_ID,
27         kind: PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None),
28         span: ident.span,
29     });
30     let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID };
31     Param {
32         attrs: AttrVec::default(),
33         id: ast::DUMMY_NODE_ID,
34         pat,
35         span: ident.span,
36         ty: P(ty),
37         is_placeholder: false,
38     }
39 }
40
41 pub enum Error {
42     UselessDocComment,
43 }
44
45 impl Error {
46     fn span_err(self, sp: impl Into<MultiSpan>, handler: &Handler) -> DiagnosticBuilder<'_> {
47         match self {
48             Error::UselessDocComment => {
49                 let mut err = struct_span_err!(
50                     handler,
51                     sp,
52                     E0585,
53                     "found a documentation comment that doesn't document anything",
54                 );
55                 err.help(
56                     "doc comments must come before what they document, maybe a comment was \
57                           intended with `//`?",
58                 );
59                 err
60             }
61         }
62     }
63 }
64
65 pub(super) trait RecoverQPath: Sized + 'static {
66     const PATH_STYLE: PathStyle = PathStyle::Expr;
67     fn to_ty(&self) -> Option<P<Ty>>;
68     fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
69 }
70
71 impl RecoverQPath for Ty {
72     const PATH_STYLE: PathStyle = PathStyle::Type;
73     fn to_ty(&self) -> Option<P<Ty>> {
74         Some(P(self.clone()))
75     }
76     fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
77         Self { span: path.span, kind: TyKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
78     }
79 }
80
81 impl RecoverQPath for Pat {
82     fn to_ty(&self) -> Option<P<Ty>> {
83         self.to_ty()
84     }
85     fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
86         Self { span: path.span, kind: PatKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
87     }
88 }
89
90 impl RecoverQPath for Expr {
91     fn to_ty(&self) -> Option<P<Ty>> {
92         self.to_ty()
93     }
94     fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
95         Self {
96             span: path.span,
97             kind: ExprKind::Path(qself, path),
98             attrs: AttrVec::new(),
99             id: ast::DUMMY_NODE_ID,
100             tokens: None,
101         }
102     }
103 }
104
105 /// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
106 crate enum ConsumeClosingDelim {
107     Yes,
108     No,
109 }
110
111 impl<'a> Parser<'a> {
112     pub(super) fn span_fatal_err<S: Into<MultiSpan>>(
113         &self,
114         sp: S,
115         err: Error,
116     ) -> DiagnosticBuilder<'a> {
117         err.span_err(sp, self.diagnostic())
118     }
119
120     pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
121         self.sess.span_diagnostic.struct_span_err(sp, m)
122     }
123
124     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
125         self.sess.span_diagnostic.span_bug(sp, m)
126     }
127
128     pub(super) fn diagnostic(&self) -> &'a Handler {
129         &self.sess.span_diagnostic
130     }
131
132     pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
133         self.sess.source_map().span_to_snippet(span)
134     }
135
136     pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
137         let mut err = self.struct_span_err(
138             self.token.span,
139             &format!("expected identifier, found {}", super::token_descr(&self.token)),
140         );
141         let valid_follow = &[
142             TokenKind::Eq,
143             TokenKind::Colon,
144             TokenKind::Comma,
145             TokenKind::Semi,
146             TokenKind::ModSep,
147             TokenKind::OpenDelim(token::DelimToken::Brace),
148             TokenKind::OpenDelim(token::DelimToken::Paren),
149             TokenKind::CloseDelim(token::DelimToken::Brace),
150             TokenKind::CloseDelim(token::DelimToken::Paren),
151         ];
152         match self.token.ident() {
153             Some((ident, false))
154                 if ident.is_raw_guess()
155                     && self.look_ahead(1, |t| valid_follow.contains(&t.kind)) =>
156             {
157                 err.span_suggestion(
158                     ident.span,
159                     "you can escape reserved keywords to use them as identifiers",
160                     format!("r#{}", ident.name),
161                     Applicability::MaybeIncorrect,
162                 );
163             }
164             _ => {}
165         }
166         if let Some(token_descr) = super::token_descr_opt(&self.token) {
167             err.span_label(self.token.span, format!("expected identifier, found {}", token_descr));
168         } else {
169             err.span_label(self.token.span, "expected identifier");
170             if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
171                 err.span_suggestion(
172                     self.token.span,
173                     "remove this comma",
174                     String::new(),
175                     Applicability::MachineApplicable,
176                 );
177             }
178         }
179         err
180     }
181
182     pub(super) fn expected_one_of_not_found(
183         &mut self,
184         edible: &[TokenKind],
185         inedible: &[TokenKind],
186     ) -> PResult<'a, bool /* recovered */> {
187         fn tokens_to_string(tokens: &[TokenType]) -> String {
188             let mut i = tokens.iter();
189             // This might be a sign we need a connect method on `Iterator`.
190             let b = i.next().map_or(String::new(), |t| t.to_string());
191             i.enumerate().fold(b, |mut b, (i, a)| {
192                 if tokens.len() > 2 && i == tokens.len() - 2 {
193                     b.push_str(", or ");
194                 } else if tokens.len() == 2 && i == tokens.len() - 2 {
195                     b.push_str(" or ");
196                 } else {
197                     b.push_str(", ");
198                 }
199                 b.push_str(&a.to_string());
200                 b
201             })
202         }
203
204         let mut expected = edible
205             .iter()
206             .map(|x| TokenType::Token(x.clone()))
207             .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
208             .chain(self.expected_tokens.iter().cloned())
209             .collect::<Vec<_>>();
210         expected.sort_by_cached_key(|x| x.to_string());
211         expected.dedup();
212         let expect = tokens_to_string(&expected[..]);
213         let actual = super::token_descr(&self.token);
214         let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
215             let short_expect = if expected.len() > 6 {
216                 format!("{} possible tokens", expected.len())
217             } else {
218                 expect.clone()
219             };
220             (
221                 format!("expected one of {}, found {}", expect, actual),
222                 (self.prev_token.span.shrink_to_hi(), format!("expected one of {}", short_expect)),
223             )
224         } else if expected.is_empty() {
225             (
226                 format!("unexpected token: {}", actual),
227                 (self.prev_token.span, "unexpected token after this".to_string()),
228             )
229         } else {
230             (
231                 format!("expected {}, found {}", expect, actual),
232                 (self.prev_token.span.shrink_to_hi(), format!("expected {}", expect)),
233             )
234         };
235         self.last_unexpected_token_span = Some(self.token.span);
236         let mut err = self.struct_span_err(self.token.span, &msg_exp);
237         let sp = if self.token == token::Eof {
238             // This is EOF; don't want to point at the following char, but rather the last token.
239             self.prev_token.span
240         } else {
241             label_sp
242         };
243         match self.recover_closing_delimiter(
244             &expected
245                 .iter()
246                 .filter_map(|tt| match tt {
247                     TokenType::Token(t) => Some(t.clone()),
248                     _ => None,
249                 })
250                 .collect::<Vec<_>>(),
251             err,
252         ) {
253             Err(e) => err = e,
254             Ok(recovered) => {
255                 return Ok(recovered);
256             }
257         }
258
259         if self.check_too_many_raw_str_terminators(&mut err) {
260             return Err(err);
261         }
262
263         let sm = self.sess.source_map();
264         if self.prev_token.span == DUMMY_SP {
265             // Account for macro context where the previous span might not be
266             // available to avoid incorrect output (#54841).
267             err.span_label(self.token.span, label_exp);
268         } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
269             // When the spans are in the same line, it means that the only content between
270             // them is whitespace, point at the found token in that case:
271             //
272             // X |     () => { syntax error };
273             //   |                    ^^^^^ expected one of 8 possible tokens here
274             //
275             // instead of having:
276             //
277             // X |     () => { syntax error };
278             //   |                   -^^^^^ unexpected token
279             //   |                   |
280             //   |                   expected one of 8 possible tokens here
281             err.span_label(self.token.span, label_exp);
282         } else {
283             err.span_label(sp, label_exp);
284             err.span_label(self.token.span, "unexpected token");
285         }
286         self.maybe_annotate_with_ascription(&mut err, false);
287         Err(err)
288     }
289
290     fn check_too_many_raw_str_terminators(&mut self, err: &mut DiagnosticBuilder<'_>) -> bool {
291         match (&self.prev_token.kind, &self.token.kind) {
292             (
293                 TokenKind::Literal(Lit {
294                     kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
295                     ..
296                 }),
297                 TokenKind::Pound,
298             ) => {
299                 err.set_primary_message("too many `#` when terminating raw string");
300                 err.span_suggestion(
301                     self.token.span,
302                     "remove the extra `#`",
303                     String::new(),
304                     Applicability::MachineApplicable,
305                 );
306                 err.note(&format!("the raw string started with {} `#`s", n_hashes));
307                 true
308             }
309             _ => false,
310         }
311     }
312
313     pub fn maybe_annotate_with_ascription(
314         &mut self,
315         err: &mut DiagnosticBuilder<'_>,
316         maybe_expected_semicolon: bool,
317     ) {
318         if let Some((sp, likely_path)) = self.last_type_ascription.take() {
319             let sm = self.sess.source_map();
320             let next_pos = sm.lookup_char_pos(self.token.span.lo());
321             let op_pos = sm.lookup_char_pos(sp.hi());
322
323             let allow_unstable = self.sess.unstable_features.is_nightly_build();
324
325             if likely_path {
326                 err.span_suggestion(
327                     sp,
328                     "maybe write a path separator here",
329                     "::".to_string(),
330                     if allow_unstable {
331                         Applicability::MaybeIncorrect
332                     } else {
333                         Applicability::MachineApplicable
334                     },
335                 );
336                 self.sess.type_ascription_path_suggestions.borrow_mut().insert(sp);
337             } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
338                 err.span_suggestion(
339                     sp,
340                     "try using a semicolon",
341                     ";".to_string(),
342                     Applicability::MaybeIncorrect,
343                 );
344             } else if allow_unstable {
345                 err.span_label(sp, "tried to parse a type due to this type ascription");
346             } else {
347                 err.span_label(sp, "tried to parse a type due to this");
348             }
349             if allow_unstable {
350                 // Give extra information about type ascription only if it's a nightly compiler.
351                 err.note(
352                     "`#![feature(type_ascription)]` lets you annotate an expression with a type: \
353                      `<expr>: <type>`",
354                 );
355                 if !likely_path {
356                     // Avoid giving too much info when it was likely an unrelated typo.
357                     err.note(
358                         "see issue #23416 <https://github.com/rust-lang/rust/issues/23416> \
359                         for more information",
360                     );
361                 }
362             }
363         }
364     }
365
366     /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
367     /// passes through any errors encountered. Used for error recovery.
368     pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
369         if let Err(ref mut err) =
370             self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
371                 Ok(p.parse_token_tree())
372             })
373         {
374             err.cancel();
375         }
376     }
377
378     /// This function checks if there are trailing angle brackets and produces
379     /// a diagnostic to suggest removing them.
380     ///
381     /// ```ignore (diagnostic)
382     /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
383     ///                                                        ^^ help: remove extra angle brackets
384     /// ```
385     ///
386     /// If `true` is returned, then trailing brackets were recovered, tokens were consumed
387     /// up until one of the tokens in 'end' was encountered, and an error was emitted.
388     pub(super) fn check_trailing_angle_brackets(
389         &mut self,
390         segment: &PathSegment,
391         end: &[&TokenKind],
392     ) -> bool {
393         // This function is intended to be invoked after parsing a path segment where there are two
394         // cases:
395         //
396         // 1. A specific token is expected after the path segment.
397         //    eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
398         //        `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
399         // 2. No specific token is expected after the path segment.
400         //    eg. `x.foo` (field access)
401         //
402         // This function is called after parsing `.foo` and before parsing the token `end` (if
403         // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
404         // `Foo::<Bar>`.
405
406         // We only care about trailing angle brackets if we previously parsed angle bracket
407         // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
408         // removed in this case:
409         //
410         // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
411         //
412         // This case is particularly tricky as we won't notice it just looking at the tokens -
413         // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
414         // have already been parsed):
415         //
416         // `x.foo::<u32>>>(3)`
417         let parsed_angle_bracket_args =
418             segment.args.as_ref().map(|args| args.is_angle_bracketed()).unwrap_or(false);
419
420         debug!(
421             "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
422             parsed_angle_bracket_args,
423         );
424         if !parsed_angle_bracket_args {
425             return false;
426         }
427
428         // Keep the span at the start so we can highlight the sequence of `>` characters to be
429         // removed.
430         let lo = self.token.span;
431
432         // We need to look-ahead to see if we have `>` characters without moving the cursor forward
433         // (since we might have the field access case and the characters we're eating are
434         // actual operators and not trailing characters - ie `x.foo >> 3`).
435         let mut position = 0;
436
437         // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
438         // many of each (so we can correctly pluralize our error messages) and continue to
439         // advance.
440         let mut number_of_shr = 0;
441         let mut number_of_gt = 0;
442         while self.look_ahead(position, |t| {
443             trace!("check_trailing_angle_brackets: t={:?}", t);
444             if *t == token::BinOp(token::BinOpToken::Shr) {
445                 number_of_shr += 1;
446                 true
447             } else if *t == token::Gt {
448                 number_of_gt += 1;
449                 true
450             } else {
451                 false
452             }
453         }) {
454             position += 1;
455         }
456
457         // If we didn't find any trailing `>` characters, then we have nothing to error about.
458         debug!(
459             "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
460             number_of_gt, number_of_shr,
461         );
462         if number_of_gt < 1 && number_of_shr < 1 {
463             return false;
464         }
465
466         // Finally, double check that we have our end token as otherwise this is the
467         // second case.
468         if self.look_ahead(position, |t| {
469             trace!("check_trailing_angle_brackets: t={:?}", t);
470             end.contains(&&t.kind)
471         }) {
472             // Eat from where we started until the end token so that parsing can continue
473             // as if we didn't have those extra angle brackets.
474             self.eat_to_tokens(end);
475             let span = lo.until(self.token.span);
476
477             let total_num_of_gt = number_of_gt + number_of_shr * 2;
478             self.struct_span_err(
479                 span,
480                 &format!("unmatched angle bracket{}", pluralize!(total_num_of_gt)),
481             )
482             .span_suggestion(
483                 span,
484                 &format!("remove extra angle bracket{}", pluralize!(total_num_of_gt)),
485                 String::new(),
486                 Applicability::MachineApplicable,
487             )
488             .emit();
489             return true;
490         }
491         false
492     }
493
494     /// Check if a method call with an intended turbofish has been written without surrounding
495     /// angle brackets.
496     pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
497         if token::ModSep == self.token.kind && segment.args.is_none() {
498             let snapshot = self.clone();
499             self.bump();
500             let lo = self.token.span;
501             match self.parse_angle_args() {
502                 Ok(args) => {
503                     let span = lo.to(self.prev_token.span);
504                     // Detect trailing `>` like in `x.collect::Vec<_>>()`.
505                     let mut trailing_span = self.prev_token.span.shrink_to_hi();
506                     while self.token.kind == token::BinOp(token::Shr)
507                         || self.token.kind == token::Gt
508                     {
509                         trailing_span = trailing_span.to(self.token.span);
510                         self.bump();
511                     }
512                     if self.token.kind == token::OpenDelim(token::Paren) {
513                         // Recover from bad turbofish: `foo.collect::Vec<_>()`.
514                         let args = AngleBracketedArgs { args, span }.into();
515                         segment.args = args;
516
517                         self.struct_span_err(
518                             span,
519                             "generic parameters without surrounding angle brackets",
520                         )
521                         .multipart_suggestion(
522                             "surround the type parameters with angle brackets",
523                             vec![
524                                 (span.shrink_to_lo(), "<".to_string()),
525                                 (trailing_span, ">".to_string()),
526                             ],
527                             Applicability::MachineApplicable,
528                         )
529                         .emit();
530                     } else {
531                         // This doesn't look like an invalid turbofish, can't recover parse state.
532                         *self = snapshot;
533                     }
534                 }
535                 Err(mut err) => {
536                     // We could't parse generic parameters, unlikely to be a turbofish. Rely on
537                     // generic parse error instead.
538                     err.cancel();
539                     *self = snapshot;
540                 }
541             }
542         }
543     }
544
545     /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
546     /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
547     /// parenthesising the leftmost comparison.
548     fn attempt_chained_comparison_suggestion(
549         &mut self,
550         err: &mut DiagnosticBuilder<'_>,
551         inner_op: &Expr,
552         outer_op: &Spanned<AssocOp>,
553     ) -> bool /* advanced the cursor */ {
554         if let ExprKind::Binary(op, ref l1, ref r1) = inner_op.kind {
555             if let ExprKind::Field(_, ident) = l1.kind {
556                 if ident.as_str().parse::<i32>().is_err() && !matches!(r1.kind, ExprKind::Lit(_)) {
557                     // The parser has encountered `foo.bar<baz`, the likelihood of the turbofish
558                     // suggestion being the only one to apply is high.
559                     return false;
560                 }
561             }
562             let mut enclose = |left: Span, right: Span| {
563                 err.multipart_suggestion(
564                     "parenthesize the comparison",
565                     vec![
566                         (left.shrink_to_lo(), "(".to_string()),
567                         (right.shrink_to_hi(), ")".to_string()),
568                     ],
569                     Applicability::MaybeIncorrect,
570                 );
571             };
572             return match (op.node, &outer_op.node) {
573                 // `x == y == z`
574                 (BinOpKind::Eq, AssocOp::Equal) |
575                 // `x < y < z` and friends.
576                 (BinOpKind::Lt, AssocOp::Less | AssocOp::LessEqual) |
577                 (BinOpKind::Le, AssocOp::LessEqual | AssocOp::Less) |
578                 // `x > y > z` and friends.
579                 (BinOpKind::Gt, AssocOp::Greater | AssocOp::GreaterEqual) |
580                 (BinOpKind::Ge, AssocOp::GreaterEqual | AssocOp::Greater) => {
581                     let expr_to_str = |e: &Expr| {
582                         self.span_to_snippet(e.span)
583                             .unwrap_or_else(|_| pprust::expr_to_string(&e))
584                     };
585                     err.span_suggestion_verbose(
586                         inner_op.span.shrink_to_hi(),
587                         "split the comparison into two",
588                         format!(" && {}", expr_to_str(&r1)),
589                         Applicability::MaybeIncorrect,
590                     );
591                     false // Keep the current parse behavior, where the AST is `(x < y) < z`.
592                 }
593                 // `x == y < z`
594                 (BinOpKind::Eq, AssocOp::Less | AssocOp::LessEqual | AssocOp::Greater | AssocOp::GreaterEqual) => {
595                     // Consume `z`/outer-op-rhs.
596                     let snapshot = self.clone();
597                     match self.parse_expr() {
598                         Ok(r2) => {
599                             // We are sure that outer-op-rhs could be consumed, the suggestion is
600                             // likely correct.
601                             enclose(r1.span, r2.span);
602                             true
603                         }
604                         Err(mut expr_err) => {
605                             expr_err.cancel();
606                             *self = snapshot;
607                             false
608                         }
609                     }
610                 }
611                 // `x > y == z`
612                 (BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge, AssocOp::Equal) => {
613                     let snapshot = self.clone();
614                     // At this point it is always valid to enclose the lhs in parentheses, no
615                     // further checks are necessary.
616                     match self.parse_expr() {
617                         Ok(_) => {
618                             enclose(l1.span, r1.span);
619                             true
620                         }
621                         Err(mut expr_err) => {
622                             expr_err.cancel();
623                             *self = snapshot;
624                             false
625                         }
626                     }
627                 }
628                 _ => false,
629             };
630         }
631         false
632     }
633
634     /// Produces an error if comparison operators are chained (RFC #558).
635     /// We only need to check the LHS, not the RHS, because all comparison ops have same
636     /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
637     ///
638     /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
639     /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
640     /// case.
641     ///
642     /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
643     /// associative we can infer that we have:
644     ///
645     /// ```text
646     ///           outer_op
647     ///           /   \
648     ///     inner_op   r2
649     ///        /  \
650     ///      l1    r1
651     /// ```
652     pub(super) fn check_no_chained_comparison(
653         &mut self,
654         inner_op: &Expr,
655         outer_op: &Spanned<AssocOp>,
656     ) -> PResult<'a, Option<P<Expr>>> {
657         debug_assert!(
658             outer_op.node.is_comparison(),
659             "check_no_chained_comparison: {:?} is not comparison",
660             outer_op.node,
661         );
662
663         let mk_err_expr =
664             |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err, AttrVec::new())));
665
666         match inner_op.kind {
667             ExprKind::Binary(op, ref l1, ref r1) if op.node.is_comparison() => {
668                 let mut err = self.struct_span_err(
669                     vec![op.span, self.prev_token.span],
670                     "comparison operators cannot be chained",
671                 );
672
673                 let suggest = |err: &mut DiagnosticBuilder<'_>| {
674                     err.span_suggestion_verbose(
675                         op.span.shrink_to_lo(),
676                         TURBOFISH,
677                         "::".to_string(),
678                         Applicability::MaybeIncorrect,
679                     );
680                 };
681
682                 // Include `<` to provide this recommendation even in a case like
683                 // `Foo<Bar<Baz<Qux, ()>>>`
684                 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Less
685                     || outer_op.node == AssocOp::Greater
686                 {
687                     if outer_op.node == AssocOp::Less {
688                         let snapshot = self.clone();
689                         self.bump();
690                         // So far we have parsed `foo<bar<`, consume the rest of the type args.
691                         let modifiers =
692                             [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
693                         self.consume_tts(1, &modifiers[..]);
694
695                         if !&[token::OpenDelim(token::Paren), token::ModSep]
696                             .contains(&self.token.kind)
697                         {
698                             // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
699                             // parser and bail out.
700                             *self = snapshot.clone();
701                         }
702                     }
703                     return if token::ModSep == self.token.kind {
704                         // We have some certainty that this was a bad turbofish at this point.
705                         // `foo< bar >::`
706                         suggest(&mut err);
707
708                         let snapshot = self.clone();
709                         self.bump(); // `::`
710
711                         // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
712                         match self.parse_expr() {
713                             Ok(_) => {
714                                 // 99% certain that the suggestion is correct, continue parsing.
715                                 err.emit();
716                                 // FIXME: actually check that the two expressions in the binop are
717                                 // paths and resynthesize new fn call expression instead of using
718                                 // `ExprKind::Err` placeholder.
719                                 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
720                             }
721                             Err(mut expr_err) => {
722                                 expr_err.cancel();
723                                 // Not entirely sure now, but we bubble the error up with the
724                                 // suggestion.
725                                 *self = snapshot;
726                                 Err(err)
727                             }
728                         }
729                     } else if token::OpenDelim(token::Paren) == self.token.kind {
730                         // We have high certainty that this was a bad turbofish at this point.
731                         // `foo< bar >(`
732                         suggest(&mut err);
733                         // Consume the fn call arguments.
734                         match self.consume_fn_args() {
735                             Err(()) => Err(err),
736                             Ok(()) => {
737                                 err.emit();
738                                 // FIXME: actually check that the two expressions in the binop are
739                                 // paths and resynthesize new fn call expression instead of using
740                                 // `ExprKind::Err` placeholder.
741                                 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
742                             }
743                         }
744                     } else {
745                         if !matches!(l1.kind, ExprKind::Lit(_))
746                             && !matches!(r1.kind, ExprKind::Lit(_))
747                         {
748                             // All we know is that this is `foo < bar >` and *nothing* else. Try to
749                             // be helpful, but don't attempt to recover.
750                             err.help(TURBOFISH);
751                             err.help("or use `(...)` if you meant to specify fn arguments");
752                         }
753
754                         // If it looks like a genuine attempt to chain operators (as opposed to a
755                         // misformatted turbofish, for instance), suggest a correct form.
756                         if self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op)
757                         {
758                             err.emit();
759                             mk_err_expr(self, inner_op.span.to(self.prev_token.span))
760                         } else {
761                             // These cases cause too many knock-down errors, bail out (#61329).
762                             Err(err)
763                         }
764                     };
765                 }
766                 let recover =
767                     self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
768                 err.emit();
769                 if recover {
770                     return mk_err_expr(self, inner_op.span.to(self.prev_token.span));
771                 }
772             }
773             _ => {}
774         }
775         Ok(None)
776     }
777
778     fn consume_fn_args(&mut self) -> Result<(), ()> {
779         let snapshot = self.clone();
780         self.bump(); // `(`
781
782         // Consume the fn call arguments.
783         let modifiers =
784             [(token::OpenDelim(token::Paren), 1), (token::CloseDelim(token::Paren), -1)];
785         self.consume_tts(1, &modifiers[..]);
786
787         if self.token.kind == token::Eof {
788             // Not entirely sure that what we consumed were fn arguments, rollback.
789             *self = snapshot;
790             Err(())
791         } else {
792             // 99% certain that the suggestion is correct, continue parsing.
793             Ok(())
794         }
795     }
796
797     pub(super) fn maybe_report_ambiguous_plus(
798         &mut self,
799         allow_plus: AllowPlus,
800         impl_dyn_multi: bool,
801         ty: &Ty,
802     ) {
803         if matches!(allow_plus, AllowPlus::No) && impl_dyn_multi {
804             let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
805             self.struct_span_err(ty.span, "ambiguous `+` in a type")
806                 .span_suggestion(
807                     ty.span,
808                     "use parentheses to disambiguate",
809                     sum_with_parens,
810                     Applicability::MachineApplicable,
811                 )
812                 .emit();
813         }
814     }
815
816     pub(super) fn maybe_recover_from_bad_type_plus(
817         &mut self,
818         allow_plus: AllowPlus,
819         ty: &Ty,
820     ) -> PResult<'a, ()> {
821         // Do not add `+` to expected tokens.
822         if matches!(allow_plus, AllowPlus::No) || !self.token.is_like_plus() {
823             return Ok(());
824         }
825
826         self.bump(); // `+`
827         let bounds = self.parse_generic_bounds(None)?;
828         let sum_span = ty.span.to(self.prev_token.span);
829
830         let mut err = struct_span_err!(
831             self.sess.span_diagnostic,
832             sum_span,
833             E0178,
834             "expected a path on the left-hand side of `+`, not `{}`",
835             pprust::ty_to_string(ty)
836         );
837
838         match ty.kind {
839             TyKind::Rptr(ref lifetime, ref mut_ty) => {
840                 let sum_with_parens = pprust::to_string(|s| {
841                     s.s.word("&");
842                     s.print_opt_lifetime(lifetime);
843                     s.print_mutability(mut_ty.mutbl, false);
844                     s.popen();
845                     s.print_type(&mut_ty.ty);
846                     s.print_type_bounds(" +", &bounds);
847                     s.pclose()
848                 });
849                 err.span_suggestion(
850                     sum_span,
851                     "try adding parentheses",
852                     sum_with_parens,
853                     Applicability::MachineApplicable,
854                 );
855             }
856             TyKind::Ptr(..) | TyKind::BareFn(..) => {
857                 err.span_label(sum_span, "perhaps you forgot parentheses?");
858             }
859             _ => {
860                 err.span_label(sum_span, "expected a path");
861             }
862         }
863         err.emit();
864         Ok(())
865     }
866
867     /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
868     /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
869     /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
870     pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
871         &mut self,
872         base: P<T>,
873         allow_recovery: bool,
874     ) -> PResult<'a, P<T>> {
875         // Do not add `::` to expected tokens.
876         if allow_recovery && self.token == token::ModSep {
877             if let Some(ty) = base.to_ty() {
878                 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
879             }
880         }
881         Ok(base)
882     }
883
884     /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
885     /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
886     pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
887         &mut self,
888         ty_span: Span,
889         ty: P<Ty>,
890     ) -> PResult<'a, P<T>> {
891         self.expect(&token::ModSep)?;
892
893         let mut path = ast::Path { segments: Vec::new(), span: DUMMY_SP };
894         self.parse_path_segments(&mut path.segments, T::PATH_STYLE)?;
895         path.span = ty_span.to(self.prev_token.span);
896
897         let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
898         self.struct_span_err(path.span, "missing angle brackets in associated item path")
899             .span_suggestion(
900                 // This is a best-effort recovery.
901                 path.span,
902                 "try",
903                 format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
904                 Applicability::MaybeIncorrect,
905             )
906             .emit();
907
908         let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
909         Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path)))
910     }
911
912     pub(super) fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
913         if self.eat(&token::Semi) {
914             let mut err = self.struct_span_err(self.prev_token.span, "expected item, found `;`");
915             err.span_suggestion_short(
916                 self.prev_token.span,
917                 "remove this semicolon",
918                 String::new(),
919                 Applicability::MachineApplicable,
920             );
921             if !items.is_empty() {
922                 let previous_item = &items[items.len() - 1];
923                 let previous_item_kind_name = match previous_item.kind {
924                     // Say "braced struct" because tuple-structs and
925                     // braceless-empty-struct declarations do take a semicolon.
926                     ItemKind::Struct(..) => Some("braced struct"),
927                     ItemKind::Enum(..) => Some("enum"),
928                     ItemKind::Trait(..) => Some("trait"),
929                     ItemKind::Union(..) => Some("union"),
930                     _ => None,
931                 };
932                 if let Some(name) = previous_item_kind_name {
933                     err.help(&format!("{} declarations are not followed by a semicolon", name));
934                 }
935             }
936             err.emit();
937             true
938         } else {
939             false
940         }
941     }
942
943     /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
944     /// closing delimiter.
945     pub(super) fn unexpected_try_recover(
946         &mut self,
947         t: &TokenKind,
948     ) -> PResult<'a, bool /* recovered */> {
949         let token_str = pprust::token_kind_to_string(t);
950         let this_token_str = super::token_descr(&self.token);
951         let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
952             // Point at the end of the macro call when reaching end of macro arguments.
953             (token::Eof, Some(_)) => {
954                 let sp = self.sess.source_map().next_point(self.token.span);
955                 (sp, sp)
956             }
957             // We don't want to point at the following span after DUMMY_SP.
958             // This happens when the parser finds an empty TokenStream.
959             _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
960             // EOF, don't want to point at the following char, but rather the last token.
961             (token::Eof, None) => (self.prev_token.span, self.token.span),
962             _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
963         };
964         let msg = format!(
965             "expected `{}`, found {}",
966             token_str,
967             match (&self.token.kind, self.subparser_name) {
968                 (token::Eof, Some(origin)) => format!("end of {}", origin),
969                 _ => this_token_str,
970             },
971         );
972         let mut err = self.struct_span_err(sp, &msg);
973         let label_exp = format!("expected `{}`", token_str);
974         match self.recover_closing_delimiter(&[t.clone()], err) {
975             Err(e) => err = e,
976             Ok(recovered) => {
977                 return Ok(recovered);
978             }
979         }
980         let sm = self.sess.source_map();
981         if !sm.is_multiline(prev_sp.until(sp)) {
982             // When the spans are in the same line, it means that the only content
983             // between them is whitespace, point only at the found token.
984             err.span_label(sp, label_exp);
985         } else {
986             err.span_label(prev_sp, label_exp);
987             err.span_label(sp, "unexpected token");
988         }
989         Err(err)
990     }
991
992     pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
993         if self.eat(&token::Semi) {
994             return Ok(());
995         }
996         let sm = self.sess.source_map();
997         let msg = format!("expected `;`, found {}", super::token_descr(&self.token));
998         let appl = Applicability::MachineApplicable;
999         if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
1000             // Likely inside a macro, can't provide meaningful suggestions.
1001             return self.expect(&token::Semi).map(drop);
1002         } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
1003             // The current token is in the same line as the prior token, not recoverable.
1004         } else if [token::Comma, token::Colon].contains(&self.token.kind)
1005             && self.prev_token.kind == token::CloseDelim(token::Paren)
1006         {
1007             // Likely typo: The current token is on a new line and is expected to be
1008             // `.`, `;`, `?`, or an operator after a close delimiter token.
1009             //
1010             // let a = std::process::Command::new("echo")
1011             //         .arg("1")
1012             //         ,arg("2")
1013             //         ^
1014             // https://github.com/rust-lang/rust/issues/72253
1015             self.expect(&token::Semi)?;
1016             return Ok(());
1017         } else if self.look_ahead(1, |t| {
1018             t == &token::CloseDelim(token::Brace) || t.can_begin_expr() && t.kind != token::Colon
1019         }) && [token::Comma, token::Colon].contains(&self.token.kind)
1020         {
1021             // Likely typo: `,` â†’ `;` or `:` â†’ `;`. This is triggered if the current token is
1022             // either `,` or `:`, and the next token could either start a new statement or is a
1023             // block close. For example:
1024             //
1025             //   let x = 32:
1026             //   let y = 42;
1027             self.bump();
1028             let sp = self.prev_token.span;
1029             self.struct_span_err(sp, &msg)
1030                 .span_suggestion_short(sp, "change this to `;`", ";".to_string(), appl)
1031                 .emit();
1032             return Ok(());
1033         } else if self.look_ahead(0, |t| {
1034             t == &token::CloseDelim(token::Brace)
1035                 || (
1036                     t.can_begin_expr() && t != &token::Semi && t != &token::Pound
1037                     // Avoid triggering with too many trailing `#` in raw string.
1038                 )
1039         }) {
1040             // Missing semicolon typo. This is triggered if the next token could either start a
1041             // new statement or is a block close. For example:
1042             //
1043             //   let x = 32
1044             //   let y = 42;
1045             let sp = self.prev_token.span.shrink_to_hi();
1046             self.struct_span_err(sp, &msg)
1047                 .span_label(self.token.span, "unexpected token")
1048                 .span_suggestion_short(sp, "add `;` here", ";".to_string(), appl)
1049                 .emit();
1050             return Ok(());
1051         }
1052         self.expect(&token::Semi).map(drop) // Error unconditionally
1053     }
1054
1055     /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
1056     /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
1057     pub(super) fn recover_incorrect_await_syntax(
1058         &mut self,
1059         lo: Span,
1060         await_sp: Span,
1061         attrs: AttrVec,
1062     ) -> PResult<'a, P<Expr>> {
1063         let (hi, expr, is_question) = if self.token == token::Not {
1064             // Handle `await!(<expr>)`.
1065             self.recover_await_macro()?
1066         } else {
1067             self.recover_await_prefix(await_sp)?
1068         };
1069         let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
1070         let expr = self.mk_expr(lo.to(sp), ExprKind::Await(expr), attrs);
1071         self.maybe_recover_from_bad_qpath(expr, true)
1072     }
1073
1074     fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1075         self.expect(&token::Not)?;
1076         self.expect(&token::OpenDelim(token::Paren))?;
1077         let expr = self.parse_expr()?;
1078         self.expect(&token::CloseDelim(token::Paren))?;
1079         Ok((self.prev_token.span, expr, false))
1080     }
1081
1082     fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
1083         let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
1084         let expr = if self.token == token::OpenDelim(token::Brace) {
1085             // Handle `await { <expr> }`.
1086             // This needs to be handled separatedly from the next arm to avoid
1087             // interpreting `await { <expr> }?` as `<expr>?.await`.
1088             self.parse_block_expr(None, self.token.span, BlockCheckMode::Default, AttrVec::new())
1089         } else {
1090             self.parse_expr()
1091         }
1092         .map_err(|mut err| {
1093             err.span_label(await_sp, "while parsing this incorrect await expression");
1094             err
1095         })?;
1096         Ok((expr.span, expr, is_question))
1097     }
1098
1099     fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
1100         let expr_str =
1101             self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr));
1102         let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" });
1103         let sp = lo.to(hi);
1104         let app = match expr.kind {
1105             ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
1106             _ => Applicability::MachineApplicable,
1107         };
1108         self.struct_span_err(sp, "incorrect use of `await`")
1109             .span_suggestion(sp, "`await` is a postfix operation", suggestion, app)
1110             .emit();
1111         sp
1112     }
1113
1114     /// If encountering `future.await()`, consumes and emits an error.
1115     pub(super) fn recover_from_await_method_call(&mut self) {
1116         if self.token == token::OpenDelim(token::Paren)
1117             && self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren))
1118         {
1119             // future.await()
1120             let lo = self.token.span;
1121             self.bump(); // (
1122             let sp = lo.to(self.token.span);
1123             self.bump(); // )
1124             self.struct_span_err(sp, "incorrect use of `await`")
1125                 .span_suggestion(
1126                     sp,
1127                     "`await` is not a method call, remove the parentheses",
1128                     String::new(),
1129                     Applicability::MachineApplicable,
1130                 )
1131                 .emit();
1132         }
1133     }
1134
1135     pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, P<Expr>> {
1136         let is_try = self.token.is_keyword(kw::Try);
1137         let is_questionmark = self.look_ahead(1, |t| t == &token::Not); //check for !
1138         let is_open = self.look_ahead(2, |t| t == &token::OpenDelim(token::Paren)); //check for (
1139
1140         if is_try && is_questionmark && is_open {
1141             let lo = self.token.span;
1142             self.bump(); //remove try
1143             self.bump(); //remove !
1144             let try_span = lo.to(self.token.span); //we take the try!( span
1145             self.bump(); //remove (
1146             let is_empty = self.token == token::CloseDelim(token::Paren); //check if the block is empty
1147             self.consume_block(token::Paren, ConsumeClosingDelim::No); //eat the block
1148             let hi = self.token.span;
1149             self.bump(); //remove )
1150             let mut err = self.struct_span_err(lo.to(hi), "use of deprecated `try` macro");
1151             err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
1152             let prefix = if is_empty { "" } else { "alternatively, " };
1153             if !is_empty {
1154                 err.multipart_suggestion(
1155                     "you can use the `?` operator instead",
1156                     vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
1157                     Applicability::MachineApplicable,
1158                 );
1159             }
1160             err.span_suggestion(lo.shrink_to_lo(), &format!("{}you can still access the deprecated `try!()` macro using the \"raw identifier\" syntax", prefix), "r#".to_string(), Applicability::MachineApplicable);
1161             err.emit();
1162             Ok(self.mk_expr_err(lo.to(hi)))
1163         } else {
1164             Err(self.expected_expression_found()) // The user isn't trying to invoke the try! macro
1165         }
1166     }
1167
1168     /// Recovers a situation like `for ( $pat in $expr )`
1169     /// and suggest writing `for $pat in $expr` instead.
1170     ///
1171     /// This should be called before parsing the `$block`.
1172     pub(super) fn recover_parens_around_for_head(
1173         &mut self,
1174         pat: P<Pat>,
1175         expr: &Expr,
1176         begin_paren: Option<Span>,
1177     ) -> P<Pat> {
1178         match (&self.token.kind, begin_paren) {
1179             (token::CloseDelim(token::Paren), Some(begin_par_sp)) => {
1180                 self.bump();
1181
1182                 let pat_str = self
1183                     // Remove the `(` from the span of the pattern:
1184                     .span_to_snippet(pat.span.trim_start(begin_par_sp).unwrap())
1185                     .unwrap_or_else(|_| pprust::pat_to_string(&pat));
1186
1187                 self.struct_span_err(self.prev_token.span, "unexpected closing `)`")
1188                     .span_label(begin_par_sp, "opening `(`")
1189                     .span_suggestion(
1190                         begin_par_sp.to(self.prev_token.span),
1191                         "remove parenthesis in `for` loop",
1192                         format!("{} in {}", pat_str, pprust::expr_to_string(&expr)),
1193                         // With e.g. `for (x) in y)` this would replace `(x) in y)`
1194                         // with `x) in y)` which is syntactically invalid.
1195                         // However, this is prevented before we get here.
1196                         Applicability::MachineApplicable,
1197                     )
1198                     .emit();
1199
1200                 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1201                 pat.and_then(|pat| match pat.kind {
1202                     PatKind::Paren(pat) => pat,
1203                     _ => P(pat),
1204                 })
1205             }
1206             _ => pat,
1207         }
1208     }
1209
1210     pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1211         (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1212             self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1213             || self.token.is_ident() &&
1214             match node {
1215                 // `foo::` â†’ `foo:` or `foo.bar::` â†’ `foo.bar:`
1216                 ast::ExprKind::Path(..) | ast::ExprKind::Field(..) => true,
1217                 _ => false,
1218             } &&
1219             !self.token.is_reserved_ident() &&           // v `foo:bar(baz)`
1220             self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren))
1221             || self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) // `foo:bar {`
1222             || self.look_ahead(1, |t| t == &token::Colon) &&     // `foo:bar::<baz`
1223             self.look_ahead(2, |t| t == &token::Lt) &&
1224             self.look_ahead(3, |t| t.is_ident())
1225             || self.look_ahead(1, |t| t == &token::Colon) &&  // `foo:bar:baz`
1226             self.look_ahead(2, |t| t.is_ident())
1227             || self.look_ahead(1, |t| t == &token::ModSep)
1228                 && (self.look_ahead(2, |t| t.is_ident()) ||   // `foo:bar::baz`
1229             self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1230     }
1231
1232     pub(super) fn recover_seq_parse_error(
1233         &mut self,
1234         delim: token::DelimToken,
1235         lo: Span,
1236         result: PResult<'a, P<Expr>>,
1237     ) -> P<Expr> {
1238         match result {
1239             Ok(x) => x,
1240             Err(mut err) => {
1241                 err.emit();
1242                 // Recover from parse error, callers expect the closing delim to be consumed.
1243                 self.consume_block(delim, ConsumeClosingDelim::Yes);
1244                 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err, AttrVec::new())
1245             }
1246         }
1247     }
1248
1249     pub(super) fn recover_closing_delimiter(
1250         &mut self,
1251         tokens: &[TokenKind],
1252         mut err: DiagnosticBuilder<'a>,
1253     ) -> PResult<'a, bool> {
1254         let mut pos = None;
1255         // We want to use the last closing delim that would apply.
1256         for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1257             if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1258                 && Some(self.token.span) > unmatched.unclosed_span
1259             {
1260                 pos = Some(i);
1261             }
1262         }
1263         match pos {
1264             Some(pos) => {
1265                 // Recover and assume that the detected unclosed delimiter was meant for
1266                 // this location. Emit the diagnostic and act as if the delimiter was
1267                 // present for the parser's sake.
1268
1269                 // Don't attempt to recover from this unclosed delimiter more than once.
1270                 let unmatched = self.unclosed_delims.remove(pos);
1271                 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1272                 if unmatched.found_delim.is_none() {
1273                     // We encountered `Eof`, set this fact here to avoid complaining about missing
1274                     // `fn main()` when we found place to suggest the closing brace.
1275                     *self.sess.reached_eof.borrow_mut() = true;
1276                 }
1277
1278                 // We want to suggest the inclusion of the closing delimiter where it makes
1279                 // the most sense, which is immediately after the last token:
1280                 //
1281                 //  {foo(bar {}}
1282                 //      -      ^
1283                 //      |      |
1284                 //      |      help: `)` may belong here
1285                 //      |
1286                 //      unclosed delimiter
1287                 if let Some(sp) = unmatched.unclosed_span {
1288                     err.span_label(sp, "unclosed delimiter");
1289                 }
1290                 // Backticks should be removed to apply suggestions.
1291                 let mut delim = delim.to_string();
1292                 delim.retain(|c| c != '`');
1293                 err.span_suggestion_short(
1294                     self.prev_token.span.shrink_to_hi(),
1295                     &format!("`{}` may belong here", delim),
1296                     delim,
1297                     Applicability::MaybeIncorrect,
1298                 );
1299                 if unmatched.found_delim.is_none() {
1300                     // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1301                     // errors which would be emitted elsewhere in the parser and let other error
1302                     // recovery consume the rest of the file.
1303                     Err(err)
1304                 } else {
1305                     err.emit();
1306                     self.expected_tokens.clear(); // Reduce the number of errors.
1307                     Ok(true)
1308                 }
1309             }
1310             _ => Err(err),
1311         }
1312     }
1313
1314     /// Eats tokens until we can be relatively sure we reached the end of the
1315     /// statement. This is something of a best-effort heuristic.
1316     ///
1317     /// We terminate when we find an unmatched `}` (without consuming it).
1318     pub(super) fn recover_stmt(&mut self) {
1319         self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1320     }
1321
1322     /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1323     /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1324     /// approximate -- it can mean we break too early due to macros, but that
1325     /// should only lead to sub-optimal recovery, not inaccurate parsing).
1326     ///
1327     /// If `break_on_block` is `Break`, then we will stop consuming tokens
1328     /// after finding (and consuming) a brace-delimited block.
1329     pub(super) fn recover_stmt_(
1330         &mut self,
1331         break_on_semi: SemiColonMode,
1332         break_on_block: BlockMode,
1333     ) {
1334         let mut brace_depth = 0;
1335         let mut bracket_depth = 0;
1336         let mut in_block = false;
1337         debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1338         loop {
1339             debug!("recover_stmt_ loop {:?}", self.token);
1340             match self.token.kind {
1341                 token::OpenDelim(token::DelimToken::Brace) => {
1342                     brace_depth += 1;
1343                     self.bump();
1344                     if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1345                     {
1346                         in_block = true;
1347                     }
1348                 }
1349                 token::OpenDelim(token::DelimToken::Bracket) => {
1350                     bracket_depth += 1;
1351                     self.bump();
1352                 }
1353                 token::CloseDelim(token::DelimToken::Brace) => {
1354                     if brace_depth == 0 {
1355                         debug!("recover_stmt_ return - close delim {:?}", self.token);
1356                         break;
1357                     }
1358                     brace_depth -= 1;
1359                     self.bump();
1360                     if in_block && bracket_depth == 0 && brace_depth == 0 {
1361                         debug!("recover_stmt_ return - block end {:?}", self.token);
1362                         break;
1363                     }
1364                 }
1365                 token::CloseDelim(token::DelimToken::Bracket) => {
1366                     bracket_depth -= 1;
1367                     if bracket_depth < 0 {
1368                         bracket_depth = 0;
1369                     }
1370                     self.bump();
1371                 }
1372                 token::Eof => {
1373                     debug!("recover_stmt_ return - Eof");
1374                     break;
1375                 }
1376                 token::Semi => {
1377                     self.bump();
1378                     if break_on_semi == SemiColonMode::Break
1379                         && brace_depth == 0
1380                         && bracket_depth == 0
1381                     {
1382                         debug!("recover_stmt_ return - Semi");
1383                         break;
1384                     }
1385                 }
1386                 token::Comma
1387                     if break_on_semi == SemiColonMode::Comma
1388                         && brace_depth == 0
1389                         && bracket_depth == 0 =>
1390                 {
1391                     debug!("recover_stmt_ return - Semi");
1392                     break;
1393                 }
1394                 _ => self.bump(),
1395             }
1396         }
1397     }
1398
1399     pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1400         if self.eat_keyword(kw::In) {
1401             // a common typo: `for _ in in bar {}`
1402             self.struct_span_err(self.prev_token.span, "expected iterable, found keyword `in`")
1403                 .span_suggestion_short(
1404                     in_span.until(self.prev_token.span),
1405                     "remove the duplicated `in`",
1406                     String::new(),
1407                     Applicability::MachineApplicable,
1408                 )
1409                 .emit();
1410         }
1411     }
1412
1413     pub(super) fn expected_semi_or_open_brace<T>(&mut self) -> PResult<'a, T> {
1414         let token_str = super::token_descr(&self.token);
1415         let msg = &format!("expected `;` or `{{`, found {}", token_str);
1416         let mut err = self.struct_span_err(self.token.span, msg);
1417         err.span_label(self.token.span, "expected `;` or `{`");
1418         Err(err)
1419     }
1420
1421     pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1422         if let token::DocComment(..) = self.token.kind {
1423             self.struct_span_err(
1424                 self.token.span,
1425                 "documentation comments cannot be applied to a function parameter's type",
1426             )
1427             .span_label(self.token.span, "doc comments are not allowed here")
1428             .emit();
1429             self.bump();
1430         } else if self.token == token::Pound
1431             && self.look_ahead(1, |t| *t == token::OpenDelim(token::Bracket))
1432         {
1433             let lo = self.token.span;
1434             // Skip every token until next possible arg.
1435             while self.token != token::CloseDelim(token::Bracket) {
1436                 self.bump();
1437             }
1438             let sp = lo.to(self.token.span);
1439             self.bump();
1440             self.struct_span_err(sp, "attributes cannot be applied to a function parameter's type")
1441                 .span_label(sp, "attributes are not allowed here")
1442                 .emit();
1443         }
1444     }
1445
1446     pub(super) fn parameter_without_type(
1447         &mut self,
1448         err: &mut DiagnosticBuilder<'_>,
1449         pat: P<ast::Pat>,
1450         require_name: bool,
1451         first_param: bool,
1452     ) -> Option<Ident> {
1453         // If we find a pattern followed by an identifier, it could be an (incorrect)
1454         // C-style parameter declaration.
1455         if self.check_ident()
1456             && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseDelim(token::Paren))
1457         {
1458             // `fn foo(String s) {}`
1459             let ident = self.parse_ident().unwrap();
1460             let span = pat.span.with_hi(ident.span.hi());
1461
1462             err.span_suggestion(
1463                 span,
1464                 "declare the type after the parameter binding",
1465                 String::from("<identifier>: <type>"),
1466                 Applicability::HasPlaceholders,
1467             );
1468             return Some(ident);
1469         } else if let PatKind::Ident(_, ident, _) = pat.kind {
1470             if require_name
1471                 && (self.token == token::Comma
1472                     || self.token == token::Lt
1473                     || self.token == token::CloseDelim(token::Paren))
1474             {
1475                 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1476                 if first_param {
1477                     err.span_suggestion(
1478                         pat.span,
1479                         "if this is a `self` type, give it a parameter name",
1480                         format!("self: {}", ident),
1481                         Applicability::MaybeIncorrect,
1482                     );
1483                 }
1484                 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
1485                 // `fn foo(HashMap: TypeName<u32>)`.
1486                 if self.token != token::Lt {
1487                     err.span_suggestion(
1488                         pat.span,
1489                         "if this is a parameter name, give it a type",
1490                         format!("{}: TypeName", ident),
1491                         Applicability::HasPlaceholders,
1492                     );
1493                 }
1494                 err.span_suggestion(
1495                     pat.span,
1496                     "if this is a type, explicitly ignore the parameter name",
1497                     format!("_: {}", ident),
1498                     Applicability::MachineApplicable,
1499                 );
1500                 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1501
1502                 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
1503                 return if self.token == token::Lt { None } else { Some(ident) };
1504             }
1505         }
1506         None
1507     }
1508
1509     pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
1510         let pat = self.parse_pat(Some("argument name"))?;
1511         self.expect(&token::Colon)?;
1512         let ty = self.parse_ty()?;
1513
1514         struct_span_err!(
1515             self.diagnostic(),
1516             pat.span,
1517             E0642,
1518             "patterns aren't allowed in methods without bodies",
1519         )
1520         .span_suggestion_short(
1521             pat.span,
1522             "give this argument a name or use an underscore to ignore it",
1523             "_".to_owned(),
1524             Applicability::MachineApplicable,
1525         )
1526         .emit();
1527
1528         // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1529         let pat = P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID });
1530         Ok((pat, ty))
1531     }
1532
1533     pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
1534         let sp = param.pat.span;
1535         param.ty.kind = TyKind::Err;
1536         self.struct_span_err(sp, "unexpected `self` parameter in function")
1537             .span_label(sp, "must be the first parameter of an associated function")
1538             .emit();
1539         Ok(param)
1540     }
1541
1542     pub(super) fn consume_block(
1543         &mut self,
1544         delim: token::DelimToken,
1545         consume_close: ConsumeClosingDelim,
1546     ) {
1547         let mut brace_depth = 0;
1548         loop {
1549             if self.eat(&token::OpenDelim(delim)) {
1550                 brace_depth += 1;
1551             } else if self.check(&token::CloseDelim(delim)) {
1552                 if brace_depth == 0 {
1553                     if let ConsumeClosingDelim::Yes = consume_close {
1554                         // Some of the callers of this method expect to be able to parse the
1555                         // closing delimiter themselves, so we leave it alone. Otherwise we advance
1556                         // the parser.
1557                         self.bump();
1558                     }
1559                     return;
1560                 } else {
1561                     self.bump();
1562                     brace_depth -= 1;
1563                     continue;
1564                 }
1565             } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
1566                 return;
1567             } else {
1568                 self.bump();
1569             }
1570         }
1571     }
1572
1573     pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a> {
1574         let (span, msg) = match (&self.token.kind, self.subparser_name) {
1575             (&token::Eof, Some(origin)) => {
1576                 let sp = self.sess.source_map().next_point(self.token.span);
1577                 (sp, format!("expected expression, found end of {}", origin))
1578             }
1579             _ => (
1580                 self.token.span,
1581                 format!("expected expression, found {}", super::token_descr(&self.token),),
1582             ),
1583         };
1584         let mut err = self.struct_span_err(span, &msg);
1585         let sp = self.sess.source_map().start_point(self.token.span);
1586         if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
1587             self.sess.expr_parentheses_needed(&mut err, *sp, None);
1588         }
1589         err.span_label(span, "expected expression");
1590         err
1591     }
1592
1593     fn consume_tts(
1594         &mut self,
1595         mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
1596         // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
1597         modifier: &[(token::TokenKind, i64)],
1598     ) {
1599         while acc > 0 {
1600             if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
1601                 acc += *val;
1602             }
1603             if self.token.kind == token::Eof {
1604                 break;
1605             }
1606             self.bump();
1607         }
1608     }
1609
1610     /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
1611     ///
1612     /// This is necessary because at this point we don't know whether we parsed a function with
1613     /// anonymous parameters or a function with names but no types. In order to minimize
1614     /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
1615     /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
1616     /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
1617     /// we deduplicate them to not complain about duplicated parameter names.
1618     pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
1619         let mut seen_inputs = FxHashSet::default();
1620         for input in fn_inputs.iter_mut() {
1621             let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
1622                 (&input.pat.kind, &input.ty.kind)
1623             {
1624                 Some(*ident)
1625             } else {
1626                 None
1627             };
1628             if let Some(ident) = opt_ident {
1629                 if seen_inputs.contains(&ident) {
1630                     input.pat.kind = PatKind::Wild;
1631                 }
1632                 seen_inputs.insert(ident);
1633             }
1634         }
1635     }
1636 }