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