]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_parse/src/parser/diagnostics.rs
New upstream version 1.68.2+dfsg1
[rustc.git] / compiler / rustc_parse / src / parser / diagnostics.rs
CommitLineData
a2a8927a 1use super::pat::Expected;
a2a8927a 2use super::{
923072b8
FG
3 BlockMode, CommaRecoveryMode, Parser, PathStyle, Restrictions, SemiColonMode, SeqSep,
4 TokenExpectType, TokenType,
a2a8927a 5};
2b03887a
FG
6use crate::errors::{
7 AmbiguousPlus, AttributeOnParamType, BadQPathStage2, BadTypePlus, BadTypePlusSub,
8 ComparisonOperatorsCannotBeChained, ComparisonOperatorsCannotBeChainedSugg,
9 ConstGenericWithoutBraces, ConstGenericWithoutBracesSugg, DocCommentOnParamType,
10 DoubleColonInBound, ExpectedIdentifier, ExpectedSemi, ExpectedSemiSugg,
11 GenericParamsWithoutAngleBrackets, GenericParamsWithoutAngleBracketsSugg, InInTypo,
12 IncorrectAwait, IncorrectSemicolon, IncorrectUseOfAwait, ParenthesesInForHead,
13 ParenthesesInForHeadSugg, PatternMethodParamWithoutBody, QuestionMarkInType,
14 QuestionMarkInTypeSugg, SelfParamNotFirst, StructLiteralBodyWithoutPath,
9c376795
FG
15 StructLiteralBodyWithoutPathSugg, StructLiteralNeedingParens, StructLiteralNeedingParensSugg,
16 SuggEscapeToUseAsIdentifier, SuggRemoveComma, UnexpectedConstInGenericParam,
17 UnexpectedConstParamDeclaration, UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets,
18 UseEqInstead,
2b03887a 19};
60c5eb7d 20
5e7ed085 21use crate::lexer::UnmatchedBrace;
487cf647 22use crate::parser;
5869c6ff 23use rustc_ast as ast;
74b04a01 24use rustc_ast::ptr::P;
04454e1e 25use rustc_ast::token::{self, Delimiter, Lit, LitKind, TokenKind};
74b04a01 26use rustc_ast::util::parser::AssocOp;
3c0e092e 27use rustc_ast::{
f2b60f7d
FG
28 AngleBracketedArg, AngleBracketedArgs, AnonConst, AttrVec, BinOpKind, BindingAnnotation, Block,
29 BlockCheckMode, Expr, ExprKind, GenericArg, Generics, Item, ItemKind, Param, Pat, PatKind,
30 Path, PathSegment, QSelf, Ty, TyKind,
3c0e092e 31};
74b04a01 32use rustc_ast_pretty::pprust;
dc9dc135 33use rustc_data_structures::fx::FxHashSet;
04454e1e 34use rustc_errors::{
9c376795
FG
35 fluent, Applicability, DiagnosticBuilder, DiagnosticMessage, FatalError, Handler, MultiSpan,
36 PResult,
04454e1e 37};
2b03887a
FG
38use rustc_errors::{pluralize, Diagnostic, ErrorGuaranteed, IntoDiagnostic};
39use rustc_session::errors::ExprParenthesesNeeded;
dfeec247 40use rustc_span::source_map::Spanned;
f2b60f7d 41use rustc_span::symbol::{kw, sym, Ident};
04454e1e 42use rustc_span::{Span, SpanSnippetError, DUMMY_SP};
a2a8927a 43use std::mem::take;
487cf647
FG
44use std::ops::{Deref, DerefMut};
45use thin_vec::{thin_vec, ThinVec};
dc9dc135
XL
46
47/// Creates a placeholder argument.
e74abb32 48pub(super) fn dummy_arg(ident: Ident) -> Param {
dc9dc135
XL
49 let pat = P(Pat {
50 id: ast::DUMMY_NODE_ID,
f2b60f7d 51 kind: PatKind::Ident(BindingAnnotation::NONE, ident, None),
dc9dc135 52 span: ident.span,
3dfed10e 53 tokens: None,
dc9dc135 54 });
1b1a35ee 55 let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID, tokens: None };
e1599b0c 56 Param {
dfeec247 57 attrs: AttrVec::default(),
e1599b0c
XL
58 id: ast::DUMMY_NODE_ID,
59 pat,
60 span: ident.span,
61 ty: P(ty),
62 is_placeholder: false,
63 }
dc9dc135
XL
64}
65
e74abb32 66pub(super) trait RecoverQPath: Sized + 'static {
48663c56
XL
67 const PATH_STYLE: PathStyle = PathStyle::Expr;
68 fn to_ty(&self) -> Option<P<Ty>>;
487cf647 69 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self;
48663c56
XL
70}
71
72impl RecoverQPath for Ty {
73 const PATH_STYLE: PathStyle = PathStyle::Type;
74 fn to_ty(&self) -> Option<P<Ty>> {
75 Some(P(self.clone()))
76 }
487cf647 77 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
1b1a35ee
XL
78 Self {
79 span: path.span,
80 kind: TyKind::Path(qself, path),
81 id: ast::DUMMY_NODE_ID,
82 tokens: None,
83 }
48663c56
XL
84 }
85}
86
87impl RecoverQPath for Pat {
88 fn to_ty(&self) -> Option<P<Ty>> {
89 self.to_ty()
90 }
487cf647 91 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
3dfed10e
XL
92 Self {
93 span: path.span,
94 kind: PatKind::Path(qself, path),
95 id: ast::DUMMY_NODE_ID,
96 tokens: None,
97 }
48663c56
XL
98 }
99}
100
101impl RecoverQPath for Expr {
102 fn to_ty(&self) -> Option<P<Ty>> {
103 self.to_ty()
104 }
487cf647 105 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
48663c56
XL
106 Self {
107 span: path.span,
e74abb32 108 kind: ExprKind::Path(qself, path),
dfeec247 109 attrs: AttrVec::new(),
48663c56 110 id: ast::DUMMY_NODE_ID,
f9f354fc 111 tokens: None,
48663c56
XL
112 }
113 }
114}
115
e74abb32 116/// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
923072b8 117pub(crate) enum ConsumeClosingDelim {
e74abb32
XL
118 Yes,
119 No,
120}
121
29967ef6
XL
122#[derive(Clone, Copy)]
123pub enum AttemptLocalParseRecovery {
124 Yes,
125 No,
126}
127
128impl AttemptLocalParseRecovery {
129 pub fn yes(&self) -> bool {
130 match self {
131 AttemptLocalParseRecovery::Yes => true,
132 AttemptLocalParseRecovery::No => false,
133 }
134 }
135
136 pub fn no(&self) -> bool {
137 match self {
138 AttemptLocalParseRecovery::Yes => false,
139 AttemptLocalParseRecovery::No => true,
140 }
141 }
142}
143
5e7ed085
FG
144/// Information for emitting suggestions and recovering from
145/// C-style `i++`, `--i`, etc.
146#[derive(Debug, Copy, Clone)]
147struct IncDecRecovery {
148 /// Is this increment/decrement its own statement?
149 standalone: IsStandalone,
150 /// Is this an increment or decrement?
151 op: IncOrDec,
152 /// Is this pre- or postfix?
153 fixity: UnaryFixity,
154}
155
156/// Is an increment or decrement expression its own statement?
157#[derive(Debug, Copy, Clone)]
158enum IsStandalone {
159 /// It's standalone, i.e., its own statement.
160 Standalone,
161 /// It's a subexpression, i.e., *not* standalone.
162 Subexpr,
5e7ed085
FG
163}
164
165#[derive(Debug, Copy, Clone, PartialEq, Eq)]
166enum IncOrDec {
167 Inc,
168 // FIXME: `i--` recovery isn't implemented yet
169 #[allow(dead_code)]
170 Dec,
171}
172
173#[derive(Debug, Copy, Clone, PartialEq, Eq)]
174enum UnaryFixity {
175 Pre,
176 Post,
177}
178
179impl IncOrDec {
180 fn chr(&self) -> char {
181 match self {
182 Self::Inc => '+',
183 Self::Dec => '-',
184 }
185 }
186
187 fn name(&self) -> &'static str {
188 match self {
189 Self::Inc => "increment",
190 Self::Dec => "decrement",
191 }
192 }
193}
194
195impl std::fmt::Display for UnaryFixity {
196 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197 match self {
198 Self::Pre => write!(f, "prefix"),
199 Self::Post => write!(f, "postfix"),
200 }
201 }
202}
203
204struct MultiSugg {
205 msg: String,
206 patches: Vec<(Span, String)>,
207 applicability: Applicability,
208}
209
210impl MultiSugg {
f2b60f7d 211 fn emit(self, err: &mut Diagnostic) {
5e7ed085
FG
212 err.multipart_suggestion(&self.msg, self.patches, self.applicability);
213 }
214
9c376795
FG
215 fn emit_verbose(self, err: &mut Diagnostic) {
216 err.multipart_suggestion_verbose(&self.msg, self.patches, self.applicability);
5e7ed085
FG
217 }
218}
04454e1e 219
487cf647
FG
220/// SnapshotParser is used to create a snapshot of the parser
221/// without causing duplicate errors being emitted when the `Parser`
222/// is dropped.
923072b8 223pub struct SnapshotParser<'a> {
5e7ed085
FG
224 parser: Parser<'a>,
225 unclosed_delims: Vec<UnmatchedBrace>,
226}
227
228impl<'a> Deref for SnapshotParser<'a> {
229 type Target = Parser<'a>;
230
231 fn deref(&self) -> &Self::Target {
232 &self.parser
233 }
234}
235
236impl<'a> DerefMut for SnapshotParser<'a> {
237 fn deref_mut(&mut self) -> &mut Self::Target {
238 &mut self.parser
239 }
240}
241
48663c56 242impl<'a> Parser<'a> {
064997fb 243 #[rustc_lint_diagnostics]
5e7ed085
FG
244 pub fn struct_span_err<S: Into<MultiSpan>>(
245 &self,
246 sp: S,
04454e1e 247 m: impl Into<DiagnosticMessage>,
5e7ed085 248 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
dc9dc135
XL
249 self.sess.span_diagnostic.struct_span_err(sp, m)
250 }
251
04454e1e 252 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: impl Into<DiagnosticMessage>) -> ! {
dc9dc135
XL
253 self.sess.span_diagnostic.span_bug(sp, m)
254 }
255
60c5eb7d 256 pub(super) fn diagnostic(&self) -> &'a Handler {
dc9dc135
XL
257 &self.sess.span_diagnostic
258 }
259
5e7ed085
FG
260 /// Replace `self` with `snapshot.parser` and extend `unclosed_delims` with `snapshot.unclosed_delims`.
261 /// This is to avoid losing unclosed delims errors `create_snapshot_for_diagnostic` clears.
262 pub(super) fn restore_snapshot(&mut self, snapshot: SnapshotParser<'a>) {
263 *self = snapshot.parser;
f2b60f7d 264 self.unclosed_delims.extend(snapshot.unclosed_delims);
5e7ed085
FG
265 }
266
267 pub fn unclosed_delims(&self) -> &[UnmatchedBrace] {
268 &self.unclosed_delims
269 }
270
271 /// Create a snapshot of the `Parser`.
923072b8 272 pub fn create_snapshot_for_diagnostic(&self) -> SnapshotParser<'a> {
5e7ed085
FG
273 let mut snapshot = self.clone();
274 let unclosed_delims = self.unclosed_delims.clone();
275 // Clear `unclosed_delims` in snapshot to avoid
276 // duplicate errors being emitted when the `Parser`
277 // is dropped (which may or may not happen, depending
278 // if the parsing the snapshot is created for is successful)
279 snapshot.unclosed_delims.clear();
280 SnapshotParser { parser: snapshot, unclosed_delims }
281 }
282
e74abb32 283 pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
416331ca
XL
284 self.sess.source_map().span_to_snippet(span)
285 }
286
5e7ed085 287 pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
60c5eb7d
XL
288 let valid_follow = &[
289 TokenKind::Eq,
290 TokenKind::Colon,
291 TokenKind::Comma,
292 TokenKind::Semi,
293 TokenKind::ModSep,
04454e1e
FG
294 TokenKind::OpenDelim(Delimiter::Brace),
295 TokenKind::OpenDelim(Delimiter::Parenthesis),
296 TokenKind::CloseDelim(Delimiter::Brace),
297 TokenKind::CloseDelim(Delimiter::Parenthesis),
60c5eb7d 298 ];
2b03887a 299 let suggest_raw = match self.token.ident() {
74b04a01
XL
300 Some((ident, false))
301 if ident.is_raw_guess()
302 && self.look_ahead(1, |t| valid_follow.contains(&t.kind)) =>
60c5eb7d 303 {
2b03887a
FG
304 Some(SuggEscapeToUseAsIdentifier {
305 span: ident.span.shrink_to_lo(),
306 // `Symbol::to_string()` is different from `Symbol::into_diagnostic_arg()`,
307 // which uses `Symbol::to_ident_string()` and "helpfully" adds an implicit `r#`
308 ident_name: ident.name.to_string(),
309 })
dc9dc135 310 }
2b03887a
FG
311 _ => None,
312 };
313
314 let suggest_remove_comma =
dc9dc135 315 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
2b03887a
FG
316 Some(SuggRemoveComma { span: self.token.span })
317 } else {
318 None
319 };
320
321 let err = ExpectedIdentifier {
322 span: self.token.span,
323 token: self.token.clone(),
324 suggest_raw,
325 suggest_remove_comma,
326 };
327 err.into_diagnostic(&self.sess.span_diagnostic)
dc9dc135
XL
328 }
329
e74abb32 330 pub(super) fn expected_one_of_not_found(
dc9dc135
XL
331 &mut self,
332 edible: &[TokenKind],
333 inedible: &[TokenKind],
334 ) -> PResult<'a, bool /* recovered */> {
5869c6ff 335 debug!("expected_one_of_not_found(edible: {:?}, inedible: {:?})", edible, inedible);
dc9dc135
XL
336 fn tokens_to_string(tokens: &[TokenType]) -> String {
337 let mut i = tokens.iter();
e1599b0c 338 // This might be a sign we need a connect method on `Iterator`.
6a06907d 339 let b = i.next().map_or_else(String::new, |t| t.to_string());
dc9dc135
XL
340 i.enumerate().fold(b, |mut b, (i, a)| {
341 if tokens.len() > 2 && i == tokens.len() - 2 {
342 b.push_str(", or ");
343 } else if tokens.len() == 2 && i == tokens.len() - 2 {
344 b.push_str(" or ");
345 } else {
346 b.push_str(", ");
347 }
348 b.push_str(&a.to_string());
349 b
350 })
351 }
352
dfeec247
XL
353 let mut expected = edible
354 .iter()
dc9dc135
XL
355 .map(|x| TokenType::Token(x.clone()))
356 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
357 .chain(self.expected_tokens.iter().cloned())
923072b8
FG
358 .filter_map(|token| {
359 // filter out suggestions which suggest the same token which was found and deemed incorrect
360 fn is_ident_eq_keyword(found: &TokenKind, expected: &TokenType) -> bool {
361 if let TokenKind::Ident(current_sym, _) = found {
362 if let TokenType::Keyword(suggested_sym) = expected {
363 return current_sym == suggested_sym;
364 }
365 }
366 false
367 }
368 if token != parser::TokenType::Token(self.token.kind.clone()) {
369 let eq = is_ident_eq_keyword(&self.token.kind, &token);
370 // if the suggestion is a keyword and the found token is an ident,
371 // the content of which are equal to the suggestion's content,
372 // we can remove that suggestion (see the return None statement below)
373
374 // if this isn't the case however, and the suggestion is a token the
375 // content of which is the same as the found token's, we remove it as well
376 if !eq {
377 if let TokenType::Token(kind) = &token {
378 if kind == &self.token.kind {
379 return None;
380 }
381 }
382 return Some(token);
383 }
384 }
385 return None;
386 })
dc9dc135
XL
387 .collect::<Vec<_>>();
388 expected.sort_by_cached_key(|x| x.to_string());
389 expected.dedup();
5869c6ff 390
94222f64 391 let sm = self.sess.source_map();
2b03887a
FG
392
393 // Special-case "expected `;`" errors
94222f64
XL
394 if expected.contains(&TokenType::Token(token::Semi)) {
395 if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
396 // Likely inside a macro, can't provide meaningful suggestions.
397 } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
398 // The current token is in the same line as the prior token, not recoverable.
399 } else if [token::Comma, token::Colon].contains(&self.token.kind)
04454e1e 400 && self.prev_token.kind == token::CloseDelim(Delimiter::Parenthesis)
94222f64
XL
401 {
402 // Likely typo: The current token is on a new line and is expected to be
403 // `.`, `;`, `?`, or an operator after a close delimiter token.
404 //
405 // let a = std::process::Command::new("echo")
406 // .arg("1")
407 // ,arg("2")
408 // ^
409 // https://github.com/rust-lang/rust/issues/72253
410 } else if self.look_ahead(1, |t| {
04454e1e 411 t == &token::CloseDelim(Delimiter::Brace)
94222f64
XL
412 || t.can_begin_expr() && t.kind != token::Colon
413 }) && [token::Comma, token::Colon].contains(&self.token.kind)
414 {
415 // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is
416 // either `,` or `:`, and the next token could either start a new statement or is a
417 // block close. For example:
418 //
419 // let x = 32:
420 // let y = 42;
2b03887a
FG
421 self.sess.emit_err(ExpectedSemi {
422 span: self.token.span,
423 token: self.token.clone(),
424 unexpected_token_label: None,
425 sugg: ExpectedSemiSugg::ChangeToSemi(self.token.span),
426 });
94222f64 427 self.bump();
c295e0f8 428 return Ok(true);
94222f64 429 } else if self.look_ahead(0, |t| {
04454e1e 430 t == &token::CloseDelim(Delimiter::Brace)
f2b60f7d
FG
431 || ((t.can_begin_expr() || t.can_begin_item())
432 && t != &token::Semi
433 && t != &token::Pound)
04454e1e
FG
434 // Avoid triggering with too many trailing `#` in raw string.
435 || (sm.is_multiline(
f2b60f7d 436 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
04454e1e 437 ) && t == &token::Pound)
064997fb
FG
438 }) && !expected.contains(&TokenType::Token(token::Comma))
439 {
94222f64
XL
440 // Missing semicolon typo. This is triggered if the next token could either start a
441 // new statement or is a block close. For example:
442 //
443 // let x = 32
444 // let y = 42;
2b03887a
FG
445 let span = self.prev_token.span.shrink_to_hi();
446 self.sess.emit_err(ExpectedSemi {
447 span,
448 token: self.token.clone(),
449 unexpected_token_label: Some(self.token.span),
450 sugg: ExpectedSemiSugg::AddSemi(span),
451 });
c295e0f8 452 return Ok(true);
94222f64
XL
453 }
454 }
455
f2b60f7d
FG
456 if self.token.kind == TokenKind::EqEq
457 && self.prev_token.is_ident()
458 && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Eq)))
459 {
460 // Likely typo: `=` → `==` in let expr or enum item
461 return Err(self.sess.create_err(UseEqInstead { span: self.token.span }));
462 }
463
a2a8927a 464 let expect = tokens_to_string(&expected);
dfeec247 465 let actual = super::token_descr(&self.token);
dc9dc135
XL
466 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
467 let short_expect = if expected.len() > 6 {
468 format!("{} possible tokens", expected.len())
469 } else {
470 expect.clone()
471 };
dfeec247 472 (
5e7ed085
FG
473 format!("expected one of {expect}, found {actual}"),
474 (self.prev_token.span.shrink_to_hi(), format!("expected one of {short_expect}")),
dfeec247 475 )
dc9dc135 476 } else if expected.is_empty() {
dfeec247 477 (
f2b60f7d 478 format!("unexpected token: {actual}"),
74b04a01 479 (self.prev_token.span, "unexpected token after this".to_string()),
dfeec247 480 )
dc9dc135 481 } else {
dfeec247 482 (
5e7ed085
FG
483 format!("expected {expect}, found {actual}"),
484 (self.prev_token.span.shrink_to_hi(), format!("expected {expect}")),
dfeec247 485 )
dc9dc135
XL
486 };
487 self.last_unexpected_token_span = Some(self.token.span);
2b03887a 488 // FIXME: translation requires list formatting (for `expect`)
dfeec247 489 let mut err = self.struct_span_err(self.token.span, &msg_exp);
5869c6ff 490
064997fb 491 if let TokenKind::Ident(symbol, _) = &self.prev_token.kind {
f2b60f7d 492 if ["def", "fun", "func", "function"].contains(&symbol.as_str()) {
064997fb
FG
493 err.span_suggestion_short(
494 self.prev_token.span,
f2b60f7d
FG
495 &format!("write `fn` instead of `{symbol}` to declare a function"),
496 "fn",
2b03887a 497 Applicability::MachineApplicable,
064997fb
FG
498 );
499 }
500 }
501
f2b60f7d
FG
502 // `pub` may be used for an item or `pub(crate)`
503 if self.prev_token.is_ident_named(sym::public)
504 && (self.token.can_begin_item()
505 || self.token.kind == TokenKind::OpenDelim(Delimiter::Parenthesis))
506 {
507 err.span_suggestion_short(
508 self.prev_token.span,
509 "write `pub` instead of `public` to make the item public",
510 "pub",
2b03887a 511 Applicability::MachineApplicable,
f2b60f7d
FG
512 );
513 }
514
5869c6ff
XL
515 // Add suggestion for a missing closing angle bracket if '>' is included in expected_tokens
516 // there are unclosed angle brackets
517 if self.unmatched_angle_bracket_count > 0
518 && self.token.kind == TokenKind::Eq
519 && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Gt)))
520 {
521 err.span_label(self.prev_token.span, "maybe try to close unmatched angle bracket");
522 }
523
dc9dc135 524 let sp = if self.token == token::Eof {
e1599b0c 525 // This is EOF; don't want to point at the following char, but rather the last token.
74b04a01 526 self.prev_token.span
dc9dc135
XL
527 } else {
528 label_sp
529 };
dfeec247
XL
530 match self.recover_closing_delimiter(
531 &expected
532 .iter()
533 .filter_map(|tt| match tt {
534 TokenType::Token(t) => Some(t.clone()),
535 _ => None,
536 })
537 .collect::<Vec<_>>(),
538 err,
539 ) {
dc9dc135
XL
540 Err(e) => err = e,
541 Ok(recovered) => {
542 return Ok(recovered);
543 }
544 }
545
ba9703b0 546 if self.check_too_many_raw_str_terminators(&mut err) {
04454e1e
FG
547 if expected.contains(&TokenType::Token(token::Semi)) && self.eat(&token::Semi) {
548 err.emit();
549 return Ok(true);
550 } else {
551 return Err(err);
552 }
ba9703b0
XL
553 }
554
74b04a01 555 if self.prev_token.span == DUMMY_SP {
e74abb32
XL
556 // Account for macro context where the previous span might not be
557 // available to avoid incorrect output (#54841).
558 err.span_label(self.token.span, label_exp);
559 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
560 // When the spans are in the same line, it means that the only content between
561 // them is whitespace, point at the found token in that case:
562 //
563 // X | () => { syntax error };
564 // | ^^^^^ expected one of 8 possible tokens here
565 //
566 // instead of having:
567 //
568 // X | () => { syntax error };
569 // | -^^^^^ unexpected token
570 // | |
571 // | expected one of 8 possible tokens here
572 err.span_label(self.token.span, label_exp);
573 } else {
574 err.span_label(sp, label_exp);
575 err.span_label(self.token.span, "unexpected token");
dc9dc135 576 }
416331ca 577 self.maybe_annotate_with_ascription(&mut err, false);
dc9dc135
XL
578 Err(err)
579 }
580
5e7ed085 581 fn check_too_many_raw_str_terminators(&mut self, err: &mut Diagnostic) -> bool {
04454e1e 582 let sm = self.sess.source_map();
ba9703b0
XL
583 match (&self.prev_token.kind, &self.token.kind) {
584 (
585 TokenKind::Literal(Lit {
586 kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
587 ..
588 }),
589 TokenKind::Pound,
04454e1e
FG
590 ) if !sm.is_multiline(
591 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
592 ) =>
593 {
594 let n_hashes: u8 = *n_hashes;
ba9703b0 595 err.set_primary_message("too many `#` when terminating raw string");
04454e1e
FG
596 let str_span = self.prev_token.span;
597 let mut span = self.token.span;
598 let mut count = 0;
599 while self.token.kind == TokenKind::Pound
600 && !sm.is_multiline(span.shrink_to_hi().until(self.token.span.shrink_to_lo()))
601 {
602 span = span.with_hi(self.token.span.hi());
603 self.bump();
604 count += 1;
605 }
606 err.set_span(span);
ba9703b0 607 err.span_suggestion(
04454e1e
FG
608 span,
609 &format!("remove the extra `#`{}", pluralize!(count)),
923072b8 610 "",
ba9703b0
XL
611 Applicability::MachineApplicable,
612 );
04454e1e
FG
613 err.span_label(
614 str_span,
615 &format!("this raw string started with {n_hashes} `#`{}", pluralize!(n_hashes)),
616 );
ba9703b0
XL
617 true
618 }
619 _ => false,
620 }
621 }
622
29967ef6
XL
623 pub fn maybe_suggest_struct_literal(
624 &mut self,
625 lo: Span,
626 s: BlockCheckMode,
9c376795
FG
627 maybe_struct_name: token::Token,
628 can_be_struct_literal: bool,
29967ef6
XL
629 ) -> Option<PResult<'a, P<Block>>> {
630 if self.token.is_ident() && self.look_ahead(1, |t| t == &token::Colon) {
631 // We might be having a struct literal where people forgot to include the path:
632 // fn foo() -> Foo {
633 // field: value,
634 // }
9c376795 635 info!(?maybe_struct_name, ?self.token);
5e7ed085 636 let mut snapshot = self.create_snapshot_for_diagnostic();
487cf647
FG
637 let path = Path {
638 segments: ThinVec::new(),
639 span: self.prev_token.span.shrink_to_lo(),
640 tokens: None,
641 };
f2b60f7d 642 let struct_expr = snapshot.parse_struct_expr(None, path, false);
29967ef6
XL
643 let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No);
644 return Some(match (struct_expr, block_tail) {
645 (Ok(expr), Err(mut err)) => {
646 // We have encountered the following:
647 // fn foo() -> Foo {
648 // field: value,
649 // }
650 // Suggest:
651 // fn foo() -> Foo { Path {
652 // field: value,
653 // } }
654 err.delay_as_bug();
5e7ed085 655 self.restore_snapshot(snapshot);
94222f64 656 let mut tail = self.mk_block(
29967ef6
XL
657 vec![self.mk_stmt_err(expr.span)],
658 s,
659 lo.to(self.prev_token.span),
94222f64
XL
660 );
661 tail.could_be_bare_literal = true;
9c376795
FG
662 if maybe_struct_name.is_ident() && can_be_struct_literal {
663 // Account for `if Example { a: one(), }.is_pos() {}`.
664 Err(self.sess.create_err(StructLiteralNeedingParens {
665 span: maybe_struct_name.span.to(expr.span),
666 sugg: StructLiteralNeedingParensSugg {
667 before: maybe_struct_name.span.shrink_to_lo(),
668 after: expr.span.shrink_to_hi(),
669 },
670 }))
671 } else {
672 self.sess.emit_err(StructLiteralBodyWithoutPath {
673 span: expr.span,
674 sugg: StructLiteralBodyWithoutPathSugg {
675 before: expr.span.shrink_to_lo(),
676 after: expr.span.shrink_to_hi(),
677 },
678 });
679 Ok(tail)
680 }
29967ef6 681 }
5e7ed085 682 (Err(err), Ok(tail)) => {
29967ef6
XL
683 // We have a block tail that contains a somehow valid type ascription expr.
684 err.cancel();
685 Ok(tail)
686 }
5e7ed085 687 (Err(snapshot_err), Err(err)) => {
29967ef6
XL
688 // We don't know what went wrong, emit the normal error.
689 snapshot_err.cancel();
04454e1e 690 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
29967ef6
XL
691 Err(err)
692 }
94222f64
XL
693 (Ok(_), Ok(mut tail)) => {
694 tail.could_be_bare_literal = true;
695 Ok(tail)
696 }
29967ef6
XL
697 });
698 }
699 None
700 }
701
416331ca 702 pub fn maybe_annotate_with_ascription(
60c5eb7d 703 &mut self,
5e7ed085 704 err: &mut Diagnostic,
416331ca
XL
705 maybe_expected_semicolon: bool,
706 ) {
60c5eb7d 707 if let Some((sp, likely_path)) = self.last_type_ascription.take() {
416331ca
XL
708 let sm = self.sess.source_map();
709 let next_pos = sm.lookup_char_pos(self.token.span.lo());
710 let op_pos = sm.lookup_char_pos(sp.hi());
711
e74abb32
XL
712 let allow_unstable = self.sess.unstable_features.is_nightly_build();
713
416331ca
XL
714 if likely_path {
715 err.span_suggestion(
716 sp,
717 "maybe write a path separator here",
923072b8 718 "::",
e74abb32
XL
719 if allow_unstable {
720 Applicability::MaybeIncorrect
721 } else {
722 Applicability::MachineApplicable
416331ca
XL
723 },
724 );
3dfed10e 725 self.sess.type_ascription_path_suggestions.borrow_mut().insert(sp);
416331ca
XL
726 } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
727 err.span_suggestion(
728 sp,
729 "try using a semicolon",
923072b8 730 ";",
416331ca
XL
731 Applicability::MaybeIncorrect,
732 );
e74abb32 733 } else if allow_unstable {
416331ca 734 err.span_label(sp, "tried to parse a type due to this type ascription");
e74abb32
XL
735 } else {
736 err.span_label(sp, "tried to parse a type due to this");
416331ca 737 }
e74abb32 738 if allow_unstable {
416331ca 739 // Give extra information about type ascription only if it's a nightly compiler.
dfeec247 740 err.note(
f035d41b
XL
741 "`#![feature(type_ascription)]` lets you annotate an expression with a type: \
742 `<expr>: <type>`",
dfeec247 743 );
f035d41b
XL
744 if !likely_path {
745 // Avoid giving too much info when it was likely an unrelated typo.
746 err.note(
747 "see issue #23416 <https://github.com/rust-lang/rust/issues/23416> \
748 for more information",
749 );
750 }
416331ca
XL
751 }
752 }
753 }
754
dc9dc135
XL
755 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
756 /// passes through any errors encountered. Used for error recovery.
e74abb32 757 pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
5e7ed085 758 if let Err(err) =
dfeec247
XL
759 self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
760 Ok(p.parse_token_tree())
761 })
762 {
e1599b0c 763 err.cancel();
dc9dc135
XL
764 }
765 }
766
767 /// This function checks if there are trailing angle brackets and produces
768 /// a diagnostic to suggest removing them.
769 ///
770 /// ```ignore (diagnostic)
5099ac24
FG
771 /// let _ = [1, 2, 3].into_iter().collect::<Vec<usize>>>>();
772 /// ^^ help: remove extra angle brackets
dc9dc135 773 /// ```
f035d41b
XL
774 ///
775 /// If `true` is returned, then trailing brackets were recovered, tokens were consumed
776 /// up until one of the tokens in 'end' was encountered, and an error was emitted.
777 pub(super) fn check_trailing_angle_brackets(
778 &mut self,
779 segment: &PathSegment,
780 end: &[&TokenKind],
781 ) -> bool {
487cf647
FG
782 if !self.may_recover() {
783 return false;
784 }
785
dc9dc135
XL
786 // This function is intended to be invoked after parsing a path segment where there are two
787 // cases:
788 //
789 // 1. A specific token is expected after the path segment.
790 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
791 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
792 // 2. No specific token is expected after the path segment.
793 // eg. `x.foo` (field access)
794 //
795 // This function is called after parsing `.foo` and before parsing the token `end` (if
796 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
797 // `Foo::<Bar>`.
798
799 // We only care about trailing angle brackets if we previously parsed angle bracket
800 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
801 // removed in this case:
802 //
803 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
804 //
805 // This case is particularly tricky as we won't notice it just looking at the tokens -
806 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
807 // have already been parsed):
808 //
809 // `x.foo::<u32>>>(3)`
dfeec247 810 let parsed_angle_bracket_args =
5869c6ff 811 segment.args.as_ref().map_or(false, |args| args.is_angle_bracketed());
dc9dc135
XL
812
813 debug!(
814 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
815 parsed_angle_bracket_args,
816 );
817 if !parsed_angle_bracket_args {
f035d41b 818 return false;
dc9dc135
XL
819 }
820
821 // Keep the span at the start so we can highlight the sequence of `>` characters to be
822 // removed.
823 let lo = self.token.span;
824
825 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
826 // (since we might have the field access case and the characters we're eating are
827 // actual operators and not trailing characters - ie `x.foo >> 3`).
828 let mut position = 0;
829
830 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
831 // many of each (so we can correctly pluralize our error messages) and continue to
832 // advance.
833 let mut number_of_shr = 0;
834 let mut number_of_gt = 0;
835 while self.look_ahead(position, |t| {
836 trace!("check_trailing_angle_brackets: t={:?}", t);
837 if *t == token::BinOp(token::BinOpToken::Shr) {
838 number_of_shr += 1;
839 true
840 } else if *t == token::Gt {
841 number_of_gt += 1;
842 true
843 } else {
844 false
845 }
846 }) {
847 position += 1;
848 }
849
850 // If we didn't find any trailing `>` characters, then we have nothing to error about.
851 debug!(
852 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
853 number_of_gt, number_of_shr,
854 );
855 if number_of_gt < 1 && number_of_shr < 1 {
f035d41b 856 return false;
dc9dc135
XL
857 }
858
859 // Finally, double check that we have our end token as otherwise this is the
860 // second case.
861 if self.look_ahead(position, |t| {
862 trace!("check_trailing_angle_brackets: t={:?}", t);
f035d41b 863 end.contains(&&t.kind)
dc9dc135
XL
864 }) {
865 // Eat from where we started until the end token so that parsing can continue
866 // as if we didn't have those extra angle brackets.
f035d41b 867 self.eat_to_tokens(end);
dc9dc135
XL
868 let span = lo.until(self.token.span);
869
2b03887a
FG
870 let num_extra_brackets = number_of_gt + number_of_shr * 2;
871 self.sess.emit_err(UnmatchedAngleBrackets { span, num_extra_brackets });
f035d41b 872 return true;
dfeec247 873 }
f035d41b 874 false
dfeec247
XL
875 }
876
3dfed10e
XL
877 /// Check if a method call with an intended turbofish has been written without surrounding
878 /// angle brackets.
879 pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
487cf647
FG
880 if !self.may_recover() {
881 return;
882 }
883
3dfed10e 884 if token::ModSep == self.token.kind && segment.args.is_none() {
5e7ed085 885 let snapshot = self.create_snapshot_for_diagnostic();
3dfed10e
XL
886 self.bump();
887 let lo = self.token.span;
3c0e092e 888 match self.parse_angle_args(None) {
3dfed10e
XL
889 Ok(args) => {
890 let span = lo.to(self.prev_token.span);
891 // Detect trailing `>` like in `x.collect::Vec<_>>()`.
892 let mut trailing_span = self.prev_token.span.shrink_to_hi();
893 while self.token.kind == token::BinOp(token::Shr)
894 || self.token.kind == token::Gt
895 {
896 trailing_span = trailing_span.to(self.token.span);
897 self.bump();
898 }
04454e1e 899 if self.token.kind == token::OpenDelim(Delimiter::Parenthesis) {
3dfed10e
XL
900 // Recover from bad turbofish: `foo.collect::Vec<_>()`.
901 let args = AngleBracketedArgs { args, span }.into();
902 segment.args = args;
903
2b03887a 904 self.sess.emit_err(GenericParamsWithoutAngleBrackets {
3dfed10e 905 span,
2b03887a
FG
906 sugg: GenericParamsWithoutAngleBracketsSugg {
907 left: span.shrink_to_lo(),
908 right: trailing_span,
909 },
910 });
3dfed10e
XL
911 } else {
912 // This doesn't look like an invalid turbofish, can't recover parse state.
5e7ed085 913 self.restore_snapshot(snapshot);
3dfed10e
XL
914 }
915 }
5e7ed085 916 Err(err) => {
6a06907d 917 // We couldn't parse generic parameters, unlikely to be a turbofish. Rely on
3dfed10e
XL
918 // generic parse error instead.
919 err.cancel();
5e7ed085 920 self.restore_snapshot(snapshot);
3dfed10e
XL
921 }
922 }
923 }
924 }
925
1b1a35ee
XL
926 /// When writing a turbofish with multiple type parameters missing the leading `::`, we will
927 /// encounter a parse error when encountering the first `,`.
928 pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
929 &mut self,
5e7ed085 930 mut e: DiagnosticBuilder<'a, ErrorGuaranteed>,
1b1a35ee
XL
931 expr: &mut P<Expr>,
932 ) -> PResult<'a, ()> {
5e7ed085
FG
933 if let ExprKind::Binary(binop, _, _) = &expr.kind
934 && let ast::BinOpKind::Lt = binop.node
935 && self.eat(&token::Comma)
936 {
937 let x = self.parse_seq_to_before_end(
938 &token::Gt,
939 SeqSep::trailing_allowed(token::Comma),
940 |p| p.parse_generic_arg(None),
941 );
942 match x {
943 Ok((_, _, false)) => {
944 if self.eat(&token::Gt) {
945 e.span_suggestion_verbose(
946 binop.span.shrink_to_lo(),
487cf647 947 fluent::parse_sugg_turbofish_syntax,
923072b8 948 "::",
5e7ed085
FG
949 Applicability::MaybeIncorrect,
950 )
951 .emit();
952 match self.parse_expr() {
953 Ok(_) => {
954 *expr =
955 self.mk_expr_err(expr.span.to(self.prev_token.span));
956 return Ok(());
957 }
958 Err(err) => {
959 *expr = self.mk_expr_err(expr.span);
960 err.cancel();
1b1a35ee
XL
961 }
962 }
1b1a35ee
XL
963 }
964 }
5e7ed085
FG
965 Err(err) => {
966 err.cancel();
967 }
968 _ => {}
1b1a35ee
XL
969 }
970 }
971 Err(e)
972 }
973
dfeec247
XL
974 /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
975 /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
976 /// parenthesising the leftmost comparison.
977 fn attempt_chained_comparison_suggestion(
978 &mut self,
2b03887a 979 err: &mut ComparisonOperatorsCannotBeChained,
dfeec247
XL
980 inner_op: &Expr,
981 outer_op: &Spanned<AssocOp>,
ba9703b0 982 ) -> bool /* advanced the cursor */ {
487cf647 983 if let ExprKind::Binary(op, l1, r1) = &inner_op.kind {
5e7ed085
FG
984 if let ExprKind::Field(_, ident) = l1.kind
985 && ident.as_str().parse::<i32>().is_err()
986 && !matches!(r1.kind, ExprKind::Lit(_))
987 {
988 // The parser has encountered `foo.bar<baz`, the likelihood of the turbofish
989 // suggestion being the only one to apply is high.
990 return false;
ba9703b0 991 }
ba9703b0
XL
992 return match (op.node, &outer_op.node) {
993 // `x == y == z`
994 (BinOpKind::Eq, AssocOp::Equal) |
dfeec247 995 // `x < y < z` and friends.
ba9703b0
XL
996 (BinOpKind::Lt, AssocOp::Less | AssocOp::LessEqual) |
997 (BinOpKind::Le, AssocOp::LessEqual | AssocOp::Less) |
dfeec247 998 // `x > y > z` and friends.
ba9703b0
XL
999 (BinOpKind::Gt, AssocOp::Greater | AssocOp::GreaterEqual) |
1000 (BinOpKind::Ge, AssocOp::GreaterEqual | AssocOp::Greater) => {
dfeec247
XL
1001 let expr_to_str = |e: &Expr| {
1002 self.span_to_snippet(e.span)
1003 .unwrap_or_else(|_| pprust::expr_to_string(&e))
1004 };
2b03887a
FG
1005 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::SplitComparison {
1006 span: inner_op.span.shrink_to_hi(),
1007 middle_term: expr_to_str(&r1),
1008 });
ba9703b0 1009 false // Keep the current parse behavior, where the AST is `(x < y) < z`.
dfeec247 1010 }
ba9703b0
XL
1011 // `x == y < z`
1012 (BinOpKind::Eq, AssocOp::Less | AssocOp::LessEqual | AssocOp::Greater | AssocOp::GreaterEqual) => {
1013 // Consume `z`/outer-op-rhs.
5e7ed085 1014 let snapshot = self.create_snapshot_for_diagnostic();
ba9703b0
XL
1015 match self.parse_expr() {
1016 Ok(r2) => {
1017 // We are sure that outer-op-rhs could be consumed, the suggestion is
1018 // likely correct.
2b03887a
FG
1019 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1020 left: r1.span.shrink_to_lo(),
1021 right: r2.span.shrink_to_hi(),
1022 });
ba9703b0
XL
1023 true
1024 }
5e7ed085 1025 Err(expr_err) => {
ba9703b0 1026 expr_err.cancel();
5e7ed085 1027 self.restore_snapshot(snapshot);
ba9703b0
XL
1028 false
1029 }
1030 }
1031 }
1032 // `x > y == z`
1033 (BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge, AssocOp::Equal) => {
5e7ed085 1034 let snapshot = self.create_snapshot_for_diagnostic();
ba9703b0
XL
1035 // At this point it is always valid to enclose the lhs in parentheses, no
1036 // further checks are necessary.
1037 match self.parse_expr() {
1038 Ok(_) => {
2b03887a
FG
1039 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1040 left: l1.span.shrink_to_lo(),
1041 right: r1.span.shrink_to_hi(),
1042 });
ba9703b0
XL
1043 true
1044 }
5e7ed085 1045 Err(expr_err) => {
ba9703b0 1046 expr_err.cancel();
5e7ed085 1047 self.restore_snapshot(snapshot);
ba9703b0
XL
1048 false
1049 }
1050 }
1051 }
1052 _ => false,
1053 };
dc9dc135 1054 }
ba9703b0 1055 false
dc9dc135
XL
1056 }
1057
e1599b0c 1058 /// Produces an error if comparison operators are chained (RFC #558).
e74abb32
XL
1059 /// We only need to check the LHS, not the RHS, because all comparison ops have same
1060 /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
1061 ///
1062 /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
1063 /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
1064 /// case.
1065 ///
1066 /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
1067 /// associative we can infer that we have:
1068 ///
ba9703b0 1069 /// ```text
e74abb32
XL
1070 /// outer_op
1071 /// / \
1072 /// inner_op r2
1073 /// / \
dfeec247 1074 /// l1 r1
ba9703b0 1075 /// ```
e74abb32
XL
1076 pub(super) fn check_no_chained_comparison(
1077 &mut self,
dfeec247
XL
1078 inner_op: &Expr,
1079 outer_op: &Spanned<AssocOp>,
e74abb32
XL
1080 ) -> PResult<'a, Option<P<Expr>>> {
1081 debug_assert!(
dfeec247 1082 outer_op.node.is_comparison(),
e74abb32 1083 "check_no_chained_comparison: {:?} is not comparison",
dfeec247 1084 outer_op.node,
e74abb32
XL
1085 );
1086
f2b60f7d 1087 let mk_err_expr = |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err)));
e74abb32 1088
487cf647
FG
1089 match &inner_op.kind {
1090 ExprKind::Binary(op, l1, r1) if op.node.is_comparison() => {
2b03887a
FG
1091 let mut err = ComparisonOperatorsCannotBeChained {
1092 span: vec![op.span, self.prev_token.span],
1093 suggest_turbofish: None,
1094 help_turbofish: None,
1095 chaining_sugg: None,
e74abb32
XL
1096 };
1097
ba9703b0
XL
1098 // Include `<` to provide this recommendation even in a case like
1099 // `Foo<Bar<Baz<Qux, ()>>>`
1100 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Less
1101 || outer_op.node == AssocOp::Greater
dfeec247 1102 {
dfeec247 1103 if outer_op.node == AssocOp::Less {
5e7ed085 1104 let snapshot = self.create_snapshot_for_diagnostic();
e74abb32
XL
1105 self.bump();
1106 // So far we have parsed `foo<bar<`, consume the rest of the type args.
dfeec247
XL
1107 let modifiers =
1108 [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
a2a8927a 1109 self.consume_tts(1, &modifiers);
e74abb32 1110
04454e1e 1111 if !&[token::OpenDelim(Delimiter::Parenthesis), token::ModSep]
dfeec247
XL
1112 .contains(&self.token.kind)
1113 {
e74abb32
XL
1114 // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
1115 // parser and bail out.
5e7ed085 1116 self.restore_snapshot(snapshot);
e74abb32
XL
1117 }
1118 }
1119 return if token::ModSep == self.token.kind {
1120 // We have some certainty that this was a bad turbofish at this point.
1121 // `foo< bar >::`
9c376795
FG
1122 if let ExprKind::Binary(o, ..) = inner_op.kind && o.node == BinOpKind::Lt {
1123 err.suggest_turbofish = Some(op.span.shrink_to_lo());
1124 } else {
1125 err.help_turbofish = Some(());
1126 }
e74abb32 1127
5e7ed085 1128 let snapshot = self.create_snapshot_for_diagnostic();
e74abb32
XL
1129 self.bump(); // `::`
1130
1131 // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
1132 match self.parse_expr() {
1133 Ok(_) => {
1134 // 99% certain that the suggestion is correct, continue parsing.
2b03887a 1135 self.sess.emit_err(err);
e74abb32
XL
1136 // FIXME: actually check that the two expressions in the binop are
1137 // paths and resynthesize new fn call expression instead of using
1138 // `ExprKind::Err` placeholder.
74b04a01 1139 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
e74abb32 1140 }
5e7ed085 1141 Err(expr_err) => {
e74abb32
XL
1142 expr_err.cancel();
1143 // Not entirely sure now, but we bubble the error up with the
1144 // suggestion.
5e7ed085 1145 self.restore_snapshot(snapshot);
2b03887a 1146 Err(err.into_diagnostic(&self.sess.span_diagnostic))
e74abb32
XL
1147 }
1148 }
04454e1e 1149 } else if token::OpenDelim(Delimiter::Parenthesis) == self.token.kind {
e74abb32
XL
1150 // We have high certainty that this was a bad turbofish at this point.
1151 // `foo< bar >(`
9c376795
FG
1152 if let ExprKind::Binary(o, ..) = inner_op.kind && o.node == BinOpKind::Lt {
1153 err.suggest_turbofish = Some(op.span.shrink_to_lo());
1154 } else {
1155 err.help_turbofish = Some(());
1156 }
e74abb32
XL
1157 // Consume the fn call arguments.
1158 match self.consume_fn_args() {
2b03887a 1159 Err(()) => Err(err.into_diagnostic(&self.sess.span_diagnostic)),
e74abb32 1160 Ok(()) => {
2b03887a 1161 self.sess.emit_err(err);
e74abb32
XL
1162 // FIXME: actually check that the two expressions in the binop are
1163 // paths and resynthesize new fn call expression instead of using
1164 // `ExprKind::Err` placeholder.
74b04a01 1165 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
e74abb32
XL
1166 }
1167 }
1168 } else {
ba9703b0
XL
1169 if !matches!(l1.kind, ExprKind::Lit(_))
1170 && !matches!(r1.kind, ExprKind::Lit(_))
1171 {
1172 // All we know is that this is `foo < bar >` and *nothing* else. Try to
1173 // be helpful, but don't attempt to recover.
2b03887a 1174 err.help_turbofish = Some(());
ba9703b0
XL
1175 }
1176
1177 // If it looks like a genuine attempt to chain operators (as opposed to a
1178 // misformatted turbofish, for instance), suggest a correct form.
1179 if self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op)
1180 {
2b03887a 1181 self.sess.emit_err(err);
ba9703b0
XL
1182 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1183 } else {
1184 // These cases cause too many knock-down errors, bail out (#61329).
2b03887a 1185 Err(err.into_diagnostic(&self.sess.span_diagnostic))
ba9703b0 1186 }
e74abb32 1187 };
dc9dc135 1188 }
ba9703b0
XL
1189 let recover =
1190 self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
2b03887a 1191 self.sess.emit_err(err);
ba9703b0
XL
1192 if recover {
1193 return mk_err_expr(self, inner_op.span.to(self.prev_token.span));
1194 }
dc9dc135
XL
1195 }
1196 _ => {}
1197 }
e74abb32
XL
1198 Ok(None)
1199 }
1200
1201 fn consume_fn_args(&mut self) -> Result<(), ()> {
5e7ed085 1202 let snapshot = self.create_snapshot_for_diagnostic();
e74abb32
XL
1203 self.bump(); // `(`
1204
1205 // Consume the fn call arguments.
04454e1e
FG
1206 let modifiers = [
1207 (token::OpenDelim(Delimiter::Parenthesis), 1),
1208 (token::CloseDelim(Delimiter::Parenthesis), -1),
1209 ];
a2a8927a 1210 self.consume_tts(1, &modifiers);
e74abb32
XL
1211
1212 if self.token.kind == token::Eof {
1213 // Not entirely sure that what we consumed were fn arguments, rollback.
5e7ed085 1214 self.restore_snapshot(snapshot);
e74abb32
XL
1215 Err(())
1216 } else {
1217 // 99% certain that the suggestion is correct, continue parsing.
1218 Ok(())
1219 }
dc9dc135
XL
1220 }
1221
923072b8
FG
1222 pub(super) fn maybe_report_ambiguous_plus(&mut self, impl_dyn_multi: bool, ty: &Ty) {
1223 if impl_dyn_multi {
04454e1e 1224 self.sess.emit_err(AmbiguousPlus { sum_ty: pprust::ty_to_string(&ty), span: ty.span });
48663c56
XL
1225 }
1226 }
1227
5099ac24 1228 /// Swift lets users write `Ty?` to mean `Option<Ty>`. Parse the construct and recover from it.
923072b8 1229 pub(super) fn maybe_recover_from_question_mark(&mut self, ty: P<Ty>) -> P<Ty> {
5099ac24
FG
1230 if self.token == token::Question {
1231 self.bump();
2b03887a
FG
1232 self.sess.emit_err(QuestionMarkInType {
1233 span: self.prev_token.span,
1234 sugg: QuestionMarkInTypeSugg {
1235 left: ty.span.shrink_to_lo(),
1236 right: self.prev_token.span,
1237 },
1238 });
5099ac24
FG
1239 self.mk_ty(ty.span.to(self.prev_token.span), TyKind::Err)
1240 } else {
1241 ty
1242 }
1243 }
1244
923072b8 1245 pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> {
48663c56 1246 // Do not add `+` to expected tokens.
923072b8 1247 if !self.token.is_like_plus() {
48663c56
XL
1248 return Ok(());
1249 }
1250
1251 self.bump(); // `+`
1252 let bounds = self.parse_generic_bounds(None)?;
74b04a01 1253 let sum_span = ty.span.to(self.prev_token.span);
48663c56 1254
487cf647 1255 let sub = match &ty.kind {
9c376795 1256 TyKind::Ref(lifetime, mut_ty) => {
48663c56 1257 let sum_with_parens = pprust::to_string(|s| {
416331ca
XL
1258 s.s.word("&");
1259 s.print_opt_lifetime(lifetime);
60c5eb7d 1260 s.print_mutability(mut_ty.mutbl, false);
416331ca
XL
1261 s.popen();
1262 s.print_type(&mut_ty.ty);
923072b8
FG
1263 if !bounds.is_empty() {
1264 s.word(" + ");
1265 s.print_type_bounds(&bounds);
1266 }
48663c56
XL
1267 s.pclose()
1268 });
923072b8
FG
1269
1270 BadTypePlusSub::AddParen { sum_with_parens, span: sum_span }
48663c56 1271 }
923072b8
FG
1272 TyKind::Ptr(..) | TyKind::BareFn(..) => BadTypePlusSub::ForgotParen { span: sum_span },
1273 _ => BadTypePlusSub::ExpectPath { span: sum_span },
1274 };
1275
1276 self.sess.emit_err(BadTypePlus { ty: pprust::ty_to_string(ty), span: sum_span, sub });
1277
48663c56
XL
1278 Ok(())
1279 }
1280
5e7ed085
FG
1281 pub(super) fn recover_from_prefix_increment(
1282 &mut self,
1283 operand_expr: P<Expr>,
1284 op_span: Span,
9c376795 1285 start_stmt: bool,
5e7ed085 1286 ) -> PResult<'a, P<Expr>> {
9c376795 1287 let standalone = if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr };
5e7ed085 1288 let kind = IncDecRecovery { standalone, op: IncOrDec::Inc, fixity: UnaryFixity::Pre };
5e7ed085
FG
1289 self.recover_from_inc_dec(operand_expr, kind, op_span)
1290 }
1291
1292 pub(super) fn recover_from_postfix_increment(
1293 &mut self,
1294 operand_expr: P<Expr>,
1295 op_span: Span,
9c376795 1296 start_stmt: bool,
5e7ed085
FG
1297 ) -> PResult<'a, P<Expr>> {
1298 let kind = IncDecRecovery {
9c376795 1299 standalone: if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr },
5e7ed085
FG
1300 op: IncOrDec::Inc,
1301 fixity: UnaryFixity::Post,
1302 };
5e7ed085
FG
1303 self.recover_from_inc_dec(operand_expr, kind, op_span)
1304 }
1305
1306 fn recover_from_inc_dec(
1307 &mut self,
1308 base: P<Expr>,
1309 kind: IncDecRecovery,
1310 op_span: Span,
1311 ) -> PResult<'a, P<Expr>> {
1312 let mut err = self.struct_span_err(
1313 op_span,
1314 &format!("Rust has no {} {} operator", kind.fixity, kind.op.name()),
1315 );
1316 err.span_label(op_span, &format!("not a valid {} operator", kind.fixity));
1317
1318 let help_base_case = |mut err: DiagnosticBuilder<'_, _>, base| {
1319 err.help(&format!("use `{}= 1` instead", kind.op.chr()));
1320 err.emit();
1321 Ok(base)
1322 };
1323
1324 // (pre, post)
1325 let spans = match kind.fixity {
1326 UnaryFixity::Pre => (op_span, base.span.shrink_to_hi()),
1327 UnaryFixity::Post => (base.span.shrink_to_lo(), op_span),
1328 };
1329
1330 match kind.standalone {
9c376795
FG
1331 IsStandalone::Standalone => {
1332 self.inc_dec_standalone_suggest(kind, spans).emit_verbose(&mut err)
1333 }
5e7ed085
FG
1334 IsStandalone::Subexpr => {
1335 let Ok(base_src) = self.span_to_snippet(base.span)
9c376795 1336 else { return help_base_case(err, base) };
5e7ed085
FG
1337 match kind.fixity {
1338 UnaryFixity::Pre => {
1339 self.prefix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1340 }
1341 UnaryFixity::Post => {
9c376795
FG
1342 // won't suggest since we can not handle the precedences
1343 // for example: `a + b++` has been parsed (a + b)++ and we can not suggest here
1344 if !matches!(base.kind, ExprKind::Binary(_, _, _)) {
1345 self.postfix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1346 }
5e7ed085
FG
1347 }
1348 }
1349 }
5e7ed085
FG
1350 }
1351 Err(err)
1352 }
1353
1354 fn prefix_inc_dec_suggest(
1355 &mut self,
1356 base_src: String,
1357 kind: IncDecRecovery,
1358 (pre_span, post_span): (Span, Span),
1359 ) -> MultiSugg {
1360 MultiSugg {
1361 msg: format!("use `{}= 1` instead", kind.op.chr()),
1362 patches: vec![
1363 (pre_span, "{ ".to_string()),
1364 (post_span, format!(" {}= 1; {} }}", kind.op.chr(), base_src)),
1365 ],
1366 applicability: Applicability::MachineApplicable,
1367 }
1368 }
1369
1370 fn postfix_inc_dec_suggest(
1371 &mut self,
1372 base_src: String,
1373 kind: IncDecRecovery,
1374 (pre_span, post_span): (Span, Span),
1375 ) -> MultiSugg {
1376 let tmp_var = if base_src.trim() == "tmp" { "tmp_" } else { "tmp" };
1377 MultiSugg {
1378 msg: format!("use `{}= 1` instead", kind.op.chr()),
1379 patches: vec![
f2b60f7d 1380 (pre_span, format!("{{ let {tmp_var} = ")),
5e7ed085
FG
1381 (post_span, format!("; {} {}= 1; {} }}", base_src, kind.op.chr(), tmp_var)),
1382 ],
1383 applicability: Applicability::HasPlaceholders,
1384 }
1385 }
1386
1387 fn inc_dec_standalone_suggest(
1388 &mut self,
1389 kind: IncDecRecovery,
1390 (pre_span, post_span): (Span, Span),
1391 ) -> MultiSugg {
2b03887a
FG
1392 let mut patches = Vec::new();
1393
1394 if !pre_span.is_empty() {
1395 patches.push((pre_span, String::new()));
1396 }
1397
1398 patches.push((post_span, format!(" {}= 1", kind.op.chr())));
5e7ed085
FG
1399 MultiSugg {
1400 msg: format!("use `{}= 1` instead", kind.op.chr()),
2b03887a 1401 patches,
5e7ed085
FG
1402 applicability: Applicability::MachineApplicable,
1403 }
1404 }
1405
e1599b0c
XL
1406 /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
1407 /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
1408 /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
e74abb32 1409 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
48663c56
XL
1410 &mut self,
1411 base: P<T>,
48663c56 1412 ) -> PResult<'a, P<T>> {
487cf647
FG
1413 if !self.may_recover() {
1414 return Ok(base);
1415 }
1416
48663c56 1417 // Do not add `::` to expected tokens.
923072b8 1418 if self.token == token::ModSep {
48663c56
XL
1419 if let Some(ty) = base.to_ty() {
1420 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1421 }
1422 }
1423 Ok(base)
1424 }
1425
e1599b0c
XL
1426 /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
1427 /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
e74abb32 1428 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
48663c56
XL
1429 &mut self,
1430 ty_span: Span,
1431 ty: P<Ty>,
1432 ) -> PResult<'a, P<T>> {
1433 self.expect(&token::ModSep)?;
1434
487cf647 1435 let mut path = ast::Path { segments: ThinVec::new(), span: DUMMY_SP, tokens: None };
3c0e092e 1436 self.parse_path_segments(&mut path.segments, T::PATH_STYLE, None)?;
74b04a01 1437 path.span = ty_span.to(self.prev_token.span);
48663c56 1438
dfeec247 1439 let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
923072b8
FG
1440 self.sess.emit_err(BadQPathStage2 {
1441 span: path.span,
1442 ty: format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
1443 });
48663c56 1444
e1599b0c 1445 let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
487cf647 1446 Ok(P(T::recovered(Some(P(QSelf { ty, path_span, position: 0 })), path)))
48663c56
XL
1447 }
1448
3c0e092e 1449 pub fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
a2a8927a
XL
1450 if self.token.kind == TokenKind::Semi {
1451 self.bump();
923072b8
FG
1452
1453 let mut err =
1454 IncorrectSemicolon { span: self.prev_token.span, opt_help: None, name: "" };
1455
48663c56
XL
1456 if !items.is_empty() {
1457 let previous_item = &items[items.len() - 1];
e74abb32 1458 let previous_item_kind_name = match previous_item.kind {
e1599b0c
XL
1459 // Say "braced struct" because tuple-structs and
1460 // braceless-empty-struct declarations do take a semicolon.
48663c56
XL
1461 ItemKind::Struct(..) => Some("braced struct"),
1462 ItemKind::Enum(..) => Some("enum"),
1463 ItemKind::Trait(..) => Some("trait"),
1464 ItemKind::Union(..) => Some("union"),
1465 _ => None,
1466 };
1467 if let Some(name) = previous_item_kind_name {
923072b8
FG
1468 err.opt_help = Some(());
1469 err.name = name;
48663c56
XL
1470 }
1471 }
923072b8 1472 self.sess.emit_err(err);
48663c56
XL
1473 true
1474 } else {
1475 false
1476 }
1477 }
1478
e1599b0c 1479 /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
dc9dc135 1480 /// closing delimiter.
e74abb32 1481 pub(super) fn unexpected_try_recover(
dc9dc135
XL
1482 &mut self,
1483 t: &TokenKind,
1484 ) -> PResult<'a, bool /* recovered */> {
1485 let token_str = pprust::token_kind_to_string(t);
dfeec247 1486 let this_token_str = super::token_descr(&self.token);
dc9dc135
XL
1487 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1488 // Point at the end of the macro call when reaching end of macro arguments.
1489 (token::Eof, Some(_)) => {
2b03887a 1490 let sp = self.prev_token.span.shrink_to_hi();
dc9dc135
XL
1491 (sp, sp)
1492 }
1493 // We don't want to point at the following span after DUMMY_SP.
1494 // This happens when the parser finds an empty TokenStream.
74b04a01 1495 _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
dc9dc135 1496 // EOF, don't want to point at the following char, but rather the last token.
74b04a01
XL
1497 (token::Eof, None) => (self.prev_token.span, self.token.span),
1498 _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
dc9dc135
XL
1499 };
1500 let msg = format!(
1501 "expected `{}`, found {}",
1502 token_str,
1503 match (&self.token.kind, self.subparser_name) {
5e7ed085 1504 (token::Eof, Some(origin)) => format!("end of {origin}"),
dc9dc135
XL
1505 _ => this_token_str,
1506 },
1507 );
1508 let mut err = self.struct_span_err(sp, &msg);
5e7ed085 1509 let label_exp = format!("expected `{token_str}`");
dc9dc135
XL
1510 match self.recover_closing_delimiter(&[t.clone()], err) {
1511 Err(e) => err = e,
1512 Ok(recovered) => {
1513 return Ok(recovered);
1514 }
1515 }
416331ca 1516 let sm = self.sess.source_map();
e74abb32
XL
1517 if !sm.is_multiline(prev_sp.until(sp)) {
1518 // When the spans are in the same line, it means that the only content
1519 // between them is whitespace, point only at the found token.
1520 err.span_label(sp, label_exp);
1521 } else {
1522 err.span_label(prev_sp, label_exp);
1523 err.span_label(sp, "unexpected token");
dc9dc135
XL
1524 }
1525 Err(err)
1526 }
1527
e74abb32
XL
1528 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1529 if self.eat(&token::Semi) {
1530 return Ok(());
1531 }
dfeec247 1532 self.expect(&token::Semi).map(drop) // Error unconditionally
e74abb32
XL
1533 }
1534
e1599b0c 1535 /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
416331ca 1536 /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
dfeec247 1537 pub(super) fn recover_incorrect_await_syntax(
48663c56
XL
1538 &mut self,
1539 lo: Span,
1540 await_sp: Span,
dfeec247
XL
1541 ) -> PResult<'a, P<Expr>> {
1542 let (hi, expr, is_question) = if self.token == token::Not {
416331ca 1543 // Handle `await!(<expr>)`.
dfeec247
XL
1544 self.recover_await_macro()?
1545 } else {
1546 self.recover_await_prefix(await_sp)?
1547 };
1548 let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
29967ef6
XL
1549 let kind = match expr.kind {
1550 // Avoid knock-down errors as we don't know whether to interpret this as `foo().await?`
1551 // or `foo()?.await` (the very reason we went with postfix syntax 😅).
1552 ExprKind::Try(_) => ExprKind::Err,
1553 _ => ExprKind::Await(expr),
1554 };
f2b60f7d 1555 let expr = self.mk_expr(lo.to(sp), kind);
923072b8 1556 self.maybe_recover_from_bad_qpath(expr)
dfeec247
XL
1557 }
1558
1559 fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1560 self.expect(&token::Not)?;
04454e1e 1561 self.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
dfeec247 1562 let expr = self.parse_expr()?;
04454e1e 1563 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
74b04a01 1564 Ok((self.prev_token.span, expr, false))
dfeec247 1565 }
416331ca 1566
dfeec247 1567 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
48663c56 1568 let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
04454e1e 1569 let expr = if self.token == token::OpenDelim(Delimiter::Brace) {
48663c56 1570 // Handle `await { <expr> }`.
6a06907d 1571 // This needs to be handled separately from the next arm to avoid
48663c56 1572 // interpreting `await { <expr> }?` as `<expr>?.await`.
f2b60f7d 1573 self.parse_block_expr(None, self.token.span, BlockCheckMode::Default)
48663c56
XL
1574 } else {
1575 self.parse_expr()
dfeec247
XL
1576 }
1577 .map_err(|mut err| {
48663c56
XL
1578 err.span_label(await_sp, "while parsing this incorrect await expression");
1579 err
1580 })?;
dfeec247 1581 Ok((expr.span, expr, is_question))
416331ca
XL
1582 }
1583
1584 fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
923072b8
FG
1585 let span = lo.to(hi);
1586 let applicability = match expr.kind {
48663c56
XL
1587 ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
1588 _ => Applicability::MachineApplicable,
1589 };
923072b8
FG
1590
1591 self.sess.emit_err(IncorrectAwait {
1592 span,
1593 sugg_span: (span, applicability),
1594 expr: self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr)),
1595 question_mark: if is_question { "?" } else { "" },
1596 });
1597
1598 span
48663c56
XL
1599 }
1600
e1599b0c 1601 /// If encountering `future.await()`, consumes and emits an error.
e74abb32 1602 pub(super) fn recover_from_await_method_call(&mut self) {
04454e1e
FG
1603 if self.token == token::OpenDelim(Delimiter::Parenthesis)
1604 && self.look_ahead(1, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
48663c56
XL
1605 {
1606 // future.await()
dc9dc135 1607 let lo = self.token.span;
48663c56 1608 self.bump(); // (
923072b8 1609 let span = lo.to(self.token.span);
48663c56 1610 self.bump(); // )
923072b8
FG
1611
1612 self.sess.emit_err(IncorrectUseOfAwait { span });
48663c56
XL
1613 }
1614 }
1615
ba9703b0
XL
1616 pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, P<Expr>> {
1617 let is_try = self.token.is_keyword(kw::Try);
1618 let is_questionmark = self.look_ahead(1, |t| t == &token::Not); //check for !
04454e1e 1619 let is_open = self.look_ahead(2, |t| t == &token::OpenDelim(Delimiter::Parenthesis)); //check for (
ba9703b0
XL
1620
1621 if is_try && is_questionmark && is_open {
1622 let lo = self.token.span;
1623 self.bump(); //remove try
1624 self.bump(); //remove !
1625 let try_span = lo.to(self.token.span); //we take the try!( span
1626 self.bump(); //remove (
04454e1e
FG
1627 let is_empty = self.token == token::CloseDelim(Delimiter::Parenthesis); //check if the block is empty
1628 self.consume_block(Delimiter::Parenthesis, ConsumeClosingDelim::No); //eat the block
ba9703b0
XL
1629 let hi = self.token.span;
1630 self.bump(); //remove )
1631 let mut err = self.struct_span_err(lo.to(hi), "use of deprecated `try` macro");
1632 err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
1633 let prefix = if is_empty { "" } else { "alternatively, " };
1634 if !is_empty {
1635 err.multipart_suggestion(
1636 "you can use the `?` operator instead",
1637 vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
1638 Applicability::MachineApplicable,
1639 );
1640 }
923072b8 1641 err.span_suggestion(lo.shrink_to_lo(), &format!("{prefix}you can still access the deprecated `try!()` macro using the \"raw identifier\" syntax"), "r#", Applicability::MachineApplicable);
ba9703b0
XL
1642 err.emit();
1643 Ok(self.mk_expr_err(lo.to(hi)))
1644 } else {
1645 Err(self.expected_expression_found()) // The user isn't trying to invoke the try! macro
1646 }
1647 }
1648
e1599b0c 1649 /// Recovers a situation like `for ( $pat in $expr )`
416331ca
XL
1650 /// and suggest writing `for $pat in $expr` instead.
1651 ///
1652 /// This should be called before parsing the `$block`.
e74abb32 1653 pub(super) fn recover_parens_around_for_head(
416331ca
XL
1654 &mut self,
1655 pat: P<Pat>,
416331ca
XL
1656 begin_paren: Option<Span>,
1657 ) -> P<Pat> {
1658 match (&self.token.kind, begin_paren) {
04454e1e 1659 (token::CloseDelim(Delimiter::Parenthesis), Some(begin_par_sp)) => {
416331ca
XL
1660 self.bump();
1661
487cf647
FG
1662 let sm = self.sess.source_map();
1663 let left = begin_par_sp;
1664 let right = self.prev_token.span;
1665 let left_snippet = if let Ok(snip) = sm.span_to_prev_source(left) &&
1666 !snip.ends_with(' ') {
1667 " ".to_string()
1668 } else {
1669 "".to_string()
1670 };
1671
1672 let right_snippet = if let Ok(snip) = sm.span_to_next_source(right) &&
1673 !snip.starts_with(' ') {
1674 " ".to_string()
1675 } else {
1676 "".to_string()
1677 };
1678
2b03887a 1679 self.sess.emit_err(ParenthesesInForHead {
487cf647 1680 span: vec![left, right],
c295e0f8
XL
1681 // With e.g. `for (x) in y)` this would replace `(x) in y)`
1682 // with `x) in y)` which is syntactically invalid.
1683 // However, this is prevented before we get here.
487cf647 1684 sugg: ParenthesesInForHeadSugg { left, right, left_snippet, right_snippet },
2b03887a 1685 });
416331ca
XL
1686
1687 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
e74abb32 1688 pat.and_then(|pat| match pat.kind {
416331ca
XL
1689 PatKind::Paren(pat) => pat,
1690 _ => P(pat),
1691 })
1692 }
1693 _ => pat,
1694 }
1695 }
1696
e74abb32 1697 pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
60c5eb7d 1698 (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
dfeec247
XL
1699 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1700 || self.token.is_ident() &&
29967ef6 1701 matches!(node, ast::ExprKind::Path(..) | ast::ExprKind::Field(..)) &&
48663c56 1702 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
04454e1e
FG
1703 self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Parenthesis))
1704 || self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Brace)) // `foo:bar {`
f035d41b
XL
1705 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar::<baz`
1706 self.look_ahead(2, |t| t == &token::Lt) &&
1707 self.look_ahead(3, |t| t.is_ident())
dfeec247
XL
1708 || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
1709 self.look_ahead(2, |t| t.is_ident())
1710 || self.look_ahead(1, |t| t == &token::ModSep)
1711 && (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz`
ba9703b0 1712 self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
48663c56
XL
1713 }
1714
e74abb32 1715 pub(super) fn recover_seq_parse_error(
48663c56 1716 &mut self,
04454e1e 1717 delim: Delimiter,
48663c56
XL
1718 lo: Span,
1719 result: PResult<'a, P<Expr>>,
1720 ) -> P<Expr> {
1721 match result {
1722 Ok(x) => x,
1723 Err(mut err) => {
1724 err.emit();
e74abb32
XL
1725 // Recover from parse error, callers expect the closing delim to be consumed.
1726 self.consume_block(delim, ConsumeClosingDelim::Yes);
f2b60f7d 1727 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err)
48663c56
XL
1728 }
1729 }
1730 }
1731
e74abb32 1732 pub(super) fn recover_closing_delimiter(
48663c56 1733 &mut self,
dc9dc135 1734 tokens: &[TokenKind],
5e7ed085 1735 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
48663c56
XL
1736 ) -> PResult<'a, bool> {
1737 let mut pos = None;
e1599b0c 1738 // We want to use the last closing delim that would apply.
48663c56
XL
1739 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1740 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
dc9dc135 1741 && Some(self.token.span) > unmatched.unclosed_span
48663c56
XL
1742 {
1743 pos = Some(i);
1744 }
1745 }
1746 match pos {
1747 Some(pos) => {
1748 // Recover and assume that the detected unclosed delimiter was meant for
1749 // this location. Emit the diagnostic and act as if the delimiter was
1750 // present for the parser's sake.
1751
dfeec247 1752 // Don't attempt to recover from this unclosed delimiter more than once.
48663c56
XL
1753 let unmatched = self.unclosed_delims.remove(pos);
1754 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
e74abb32
XL
1755 if unmatched.found_delim.is_none() {
1756 // We encountered `Eof`, set this fact here to avoid complaining about missing
1757 // `fn main()` when we found place to suggest the closing brace.
1758 *self.sess.reached_eof.borrow_mut() = true;
1759 }
48663c56 1760
e1599b0c 1761 // We want to suggest the inclusion of the closing delimiter where it makes
48663c56
XL
1762 // the most sense, which is immediately after the last token:
1763 //
1764 // {foo(bar {}}
94222f64 1765 // ^ ^
48663c56 1766 // | |
dc9dc135 1767 // | help: `)` may belong here
48663c56
XL
1768 // |
1769 // unclosed delimiter
1770 if let Some(sp) = unmatched.unclosed_span {
94222f64
XL
1771 let mut primary_span: Vec<Span> =
1772 err.span.primary_spans().iter().cloned().collect();
1773 primary_span.push(sp);
1774 let mut primary_span: MultiSpan = primary_span.into();
1775 for span_label in err.span.span_labels() {
1776 if let Some(label) = span_label.label {
1777 primary_span.push_span_label(span_label.span, label);
1778 }
1779 }
1780 err.set_span(primary_span);
48663c56
XL
1781 err.span_label(sp, "unclosed delimiter");
1782 }
f035d41b
XL
1783 // Backticks should be removed to apply suggestions.
1784 let mut delim = delim.to_string();
1785 delim.retain(|c| c != '`');
48663c56 1786 err.span_suggestion_short(
74b04a01 1787 self.prev_token.span.shrink_to_hi(),
5e7ed085 1788 &format!("`{delim}` may belong here"),
f035d41b 1789 delim,
48663c56
XL
1790 Applicability::MaybeIncorrect,
1791 );
e74abb32
XL
1792 if unmatched.found_delim.is_none() {
1793 // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1794 // errors which would be emitted elsewhere in the parser and let other error
1795 // recovery consume the rest of the file.
1796 Err(err)
1797 } else {
1798 err.emit();
dfeec247 1799 self.expected_tokens.clear(); // Reduce the number of errors.
e74abb32
XL
1800 Ok(true)
1801 }
48663c56
XL
1802 }
1803 _ => Err(err),
1804 }
1805 }
1806
e1599b0c
XL
1807 /// Eats tokens until we can be relatively sure we reached the end of the
1808 /// statement. This is something of a best-effort heuristic.
1809 ///
1810 /// We terminate when we find an unmatched `}` (without consuming it).
e74abb32 1811 pub(super) fn recover_stmt(&mut self) {
48663c56
XL
1812 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1813 }
1814
e1599b0c
XL
1815 /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1816 /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1817 /// approximate -- it can mean we break too early due to macros, but that
1818 /// should only lead to sub-optimal recovery, not inaccurate parsing).
1819 ///
1820 /// If `break_on_block` is `Break`, then we will stop consuming tokens
1821 /// after finding (and consuming) a brace-delimited block.
e74abb32
XL
1822 pub(super) fn recover_stmt_(
1823 &mut self,
1824 break_on_semi: SemiColonMode,
1825 break_on_block: BlockMode,
1826 ) {
48663c56
XL
1827 let mut brace_depth = 0;
1828 let mut bracket_depth = 0;
1829 let mut in_block = false;
dfeec247 1830 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
48663c56
XL
1831 loop {
1832 debug!("recover_stmt_ loop {:?}", self.token);
dc9dc135 1833 match self.token.kind {
04454e1e 1834 token::OpenDelim(Delimiter::Brace) => {
48663c56
XL
1835 brace_depth += 1;
1836 self.bump();
dfeec247
XL
1837 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1838 {
48663c56
XL
1839 in_block = true;
1840 }
1841 }
04454e1e 1842 token::OpenDelim(Delimiter::Bracket) => {
48663c56
XL
1843 bracket_depth += 1;
1844 self.bump();
1845 }
04454e1e 1846 token::CloseDelim(Delimiter::Brace) => {
48663c56
XL
1847 if brace_depth == 0 {
1848 debug!("recover_stmt_ return - close delim {:?}", self.token);
1849 break;
1850 }
1851 brace_depth -= 1;
1852 self.bump();
1853 if in_block && bracket_depth == 0 && brace_depth == 0 {
1854 debug!("recover_stmt_ return - block end {:?}", self.token);
1855 break;
1856 }
1857 }
04454e1e 1858 token::CloseDelim(Delimiter::Bracket) => {
48663c56
XL
1859 bracket_depth -= 1;
1860 if bracket_depth < 0 {
1861 bracket_depth = 0;
1862 }
1863 self.bump();
1864 }
1865 token::Eof => {
1866 debug!("recover_stmt_ return - Eof");
1867 break;
1868 }
1869 token::Semi => {
1870 self.bump();
dfeec247
XL
1871 if break_on_semi == SemiColonMode::Break
1872 && brace_depth == 0
1873 && bracket_depth == 0
1874 {
48663c56
XL
1875 debug!("recover_stmt_ return - Semi");
1876 break;
1877 }
1878 }
dfeec247
XL
1879 token::Comma
1880 if break_on_semi == SemiColonMode::Comma
1881 && brace_depth == 0
1882 && bracket_depth == 0 =>
48663c56
XL
1883 {
1884 debug!("recover_stmt_ return - Semi");
1885 break;
1886 }
dfeec247 1887 _ => self.bump(),
48663c56
XL
1888 }
1889 }
1890 }
1891
e74abb32 1892 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
dc9dc135
XL
1893 if self.eat_keyword(kw::In) {
1894 // a common typo: `for _ in in bar {}`
923072b8
FG
1895 self.sess.emit_err(InInTypo {
1896 span: self.prev_token.span,
1897 sugg_span: in_span.until(self.prev_token.span),
1898 });
dc9dc135
XL
1899 }
1900 }
1901
e74abb32 1902 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
3dfed10e 1903 if let token::DocComment(..) = self.token.kind {
2b03887a 1904 self.sess.emit_err(DocCommentOnParamType { span: self.token.span });
dc9dc135 1905 self.bump();
dfeec247 1906 } else if self.token == token::Pound
04454e1e 1907 && self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Bracket))
dfeec247 1908 {
dc9dc135
XL
1909 let lo = self.token.span;
1910 // Skip every token until next possible arg.
04454e1e 1911 while self.token != token::CloseDelim(Delimiter::Bracket) {
dc9dc135
XL
1912 self.bump();
1913 }
1914 let sp = lo.to(self.token.span);
1915 self.bump();
2b03887a 1916 self.sess.emit_err(AttributeOnParamType { span: sp });
dc9dc135
XL
1917 }
1918 }
1919
e74abb32 1920 pub(super) fn parameter_without_type(
dc9dc135 1921 &mut self,
5e7ed085 1922 err: &mut Diagnostic,
dc9dc135
XL
1923 pat: P<ast::Pat>,
1924 require_name: bool,
74b04a01 1925 first_param: bool,
dc9dc135
XL
1926 ) -> Option<Ident> {
1927 // If we find a pattern followed by an identifier, it could be an (incorrect)
1928 // C-style parameter declaration.
dfeec247 1929 if self.check_ident()
04454e1e
FG
1930 && self.look_ahead(1, |t| {
1931 *t == token::Comma || *t == token::CloseDelim(Delimiter::Parenthesis)
1932 })
dfeec247
XL
1933 {
1934 // `fn foo(String s) {}`
dc9dc135
XL
1935 let ident = self.parse_ident().unwrap();
1936 let span = pat.span.with_hi(ident.span.hi());
1937
1938 err.span_suggestion(
1939 span,
1940 "declare the type after the parameter binding",
923072b8 1941 "<identifier>: <type>",
dc9dc135
XL
1942 Applicability::HasPlaceholders,
1943 );
1944 return Some(ident);
6a06907d
XL
1945 } else if require_name
1946 && (self.token == token::Comma
1947 || self.token == token::Lt
04454e1e 1948 || self.token == token::CloseDelim(Delimiter::Parenthesis))
6a06907d
XL
1949 {
1950 let rfc_note = "anonymous parameters are removed in the 2018 edition (see RFC 1685)";
1951
c295e0f8
XL
1952 let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
1953 match pat.kind {
1954 PatKind::Ident(_, ident, _) => (
1955 ident,
923072b8 1956 "self: ",
c295e0f8 1957 ": TypeName".to_string(),
923072b8 1958 "_: ",
c295e0f8
XL
1959 pat.span.shrink_to_lo(),
1960 pat.span.shrink_to_hi(),
1961 pat.span.shrink_to_lo(),
1962 ),
1963 // Also catches `fn foo(&a)`.
1964 PatKind::Ref(ref inner_pat, mutab)
1965 if matches!(inner_pat.clone().into_inner().kind, PatKind::Ident(..)) =>
1966 {
1967 match inner_pat.clone().into_inner().kind {
1968 PatKind::Ident(_, ident, _) => {
1969 let mutab = mutab.prefix_str();
1970 (
1971 ident,
923072b8 1972 "self: ",
5e7ed085 1973 format!("{ident}: &{mutab}TypeName"),
923072b8 1974 "_: ",
c295e0f8
XL
1975 pat.span.shrink_to_lo(),
1976 pat.span,
1977 pat.span.shrink_to_lo(),
1978 )
1979 }
1980 _ => unreachable!(),
6a06907d 1981 }
6a06907d 1982 }
c295e0f8
XL
1983 _ => {
1984 // Otherwise, try to get a type and emit a suggestion.
1985 if let Some(ty) = pat.to_ty() {
1986 err.span_suggestion_verbose(
1987 pat.span,
1988 "explicitly ignore the parameter name",
1989 format!("_: {}", pprust::ty_to_string(&ty)),
1990 Applicability::MachineApplicable,
1991 );
1992 err.note(rfc_note);
1993 }
6a06907d 1994
c295e0f8
XL
1995 return None;
1996 }
1997 };
6a06907d
XL
1998
1999 // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
2000 if first_param {
dc9dc135 2001 err.span_suggestion(
c295e0f8 2002 self_span,
6a06907d
XL
2003 "if this is a `self` type, give it a parameter name",
2004 self_sugg,
2005 Applicability::MaybeIncorrect,
dc9dc135 2006 );
dc9dc135 2007 }
6a06907d
XL
2008 // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
2009 // `fn foo(HashMap: TypeName<u32>)`.
2010 if self.token != token::Lt {
2011 err.span_suggestion(
c295e0f8 2012 param_span,
6a06907d
XL
2013 "if this is a parameter name, give it a type",
2014 param_sugg,
2015 Applicability::HasPlaceholders,
2016 );
2017 }
2018 err.span_suggestion(
c295e0f8 2019 type_span,
6a06907d
XL
2020 "if this is a type, explicitly ignore the parameter name",
2021 type_sugg,
2022 Applicability::MachineApplicable,
2023 );
2024 err.note(rfc_note);
2025
2026 // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
2027 return if self.token == token::Lt { None } else { Some(ident) };
dc9dc135
XL
2028 }
2029 None
2030 }
2031
e74abb32 2032 pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
6a06907d 2033 let pat = self.parse_pat_no_top_alt(Some("argument name"))?;
dc9dc135
XL
2034 self.expect(&token::Colon)?;
2035 let ty = self.parse_ty()?;
2036
2b03887a 2037 self.sess.emit_err(PatternMethodParamWithoutBody { span: pat.span });
dc9dc135
XL
2038
2039 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
3dfed10e
XL
2040 let pat =
2041 P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID, tokens: None });
dc9dc135
XL
2042 Ok((pat, ty))
2043 }
2044
74b04a01 2045 pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
2b03887a 2046 let span = param.pat.span;
e74abb32 2047 param.ty.kind = TyKind::Err;
2b03887a 2048 self.sess.emit_err(SelfParamNotFirst { span });
e1599b0c 2049 Ok(param)
dc9dc135
XL
2050 }
2051
04454e1e 2052 pub(super) fn consume_block(&mut self, delim: Delimiter, consume_close: ConsumeClosingDelim) {
48663c56
XL
2053 let mut brace_depth = 0;
2054 loop {
2055 if self.eat(&token::OpenDelim(delim)) {
2056 brace_depth += 1;
e74abb32 2057 } else if self.check(&token::CloseDelim(delim)) {
48663c56 2058 if brace_depth == 0 {
e74abb32
XL
2059 if let ConsumeClosingDelim::Yes = consume_close {
2060 // Some of the callers of this method expect to be able to parse the
2061 // closing delimiter themselves, so we leave it alone. Otherwise we advance
2062 // the parser.
2063 self.bump();
2064 }
48663c56
XL
2065 return;
2066 } else {
e74abb32 2067 self.bump();
48663c56
XL
2068 brace_depth -= 1;
2069 continue;
2070 }
04454e1e 2071 } else if self.token == token::Eof {
48663c56
XL
2072 return;
2073 } else {
2074 self.bump();
2075 }
2076 }
2077 }
2078
5e7ed085 2079 pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
dc9dc135
XL
2080 let (span, msg) = match (&self.token.kind, self.subparser_name) {
2081 (&token::Eof, Some(origin)) => {
2b03887a 2082 let sp = self.prev_token.span.shrink_to_hi();
5e7ed085 2083 (sp, format!("expected expression, found end of {origin}"))
dc9dc135 2084 }
dfeec247
XL
2085 _ => (
2086 self.token.span,
2087 format!("expected expression, found {}", super::token_descr(&self.token),),
2088 ),
dc9dc135
XL
2089 };
2090 let mut err = self.struct_span_err(span, &msg);
2091 let sp = self.sess.source_map().start_point(self.token.span);
2092 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
2b03887a 2093 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
dc9dc135
XL
2094 }
2095 err.span_label(span, "expected expression");
2096 err
2097 }
2098
e74abb32
XL
2099 fn consume_tts(
2100 &mut self,
2101 mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
2102 // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
2103 modifier: &[(token::TokenKind, i64)],
2104 ) {
2105 while acc > 0 {
2106 if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
2107 acc += *val;
2108 }
2109 if self.token.kind == token::Eof {
2110 break;
2111 }
2112 self.bump();
2113 }
2114 }
2115
60c5eb7d 2116 /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
dc9dc135
XL
2117 ///
2118 /// This is necessary because at this point we don't know whether we parsed a function with
e1599b0c 2119 /// anonymous parameters or a function with names but no types. In order to minimize
60c5eb7d 2120 /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
e1599b0c 2121 /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
dc9dc135 2122 /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
e1599b0c 2123 /// we deduplicate them to not complain about duplicated parameter names.
e74abb32 2124 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
dc9dc135
XL
2125 let mut seen_inputs = FxHashSet::default();
2126 for input in fn_inputs.iter_mut() {
dfeec247
XL
2127 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
2128 (&input.pat.kind, &input.ty.kind)
2129 {
dc9dc135
XL
2130 Some(*ident)
2131 } else {
2132 None
2133 };
2134 if let Some(ident) = opt_ident {
2135 if seen_inputs.contains(&ident) {
e74abb32 2136 input.pat.kind = PatKind::Wild;
dc9dc135
XL
2137 }
2138 seen_inputs.insert(ident);
2139 }
2140 }
2141 }
29967ef6
XL
2142
2143 /// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
2144 /// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
2145 /// like the user has forgotten them.
2146 pub fn handle_ambiguous_unbraced_const_arg(
2147 &mut self,
2148 args: &mut Vec<AngleBracketedArg>,
2149 ) -> PResult<'a, bool> {
2150 // If we haven't encountered a closing `>`, then the argument is malformed.
2151 // It's likely that the user has written a const expression without enclosing it
2152 // in braces, so we try to recover here.
2153 let arg = args.pop().unwrap();
2154 // FIXME: for some reason using `unexpected` or `expected_one_of_not_found` has
2155 // adverse side-effects to subsequent errors and seems to advance the parser.
2156 // We are causing this error here exclusively in case that a `const` expression
2157 // could be recovered from the current parser state, even if followed by more
2158 // arguments after a comma.
2159 let mut err = self.struct_span_err(
2160 self.token.span,
2161 &format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
2162 );
2163 err.span_label(self.token.span, "expected one of `,` or `>`");
2164 match self.recover_const_arg(arg.span(), err) {
2165 Ok(arg) => {
2166 args.push(AngleBracketedArg::Arg(arg));
2167 if self.eat(&token::Comma) {
2168 return Ok(true); // Continue
2169 }
2170 }
2171 Err(mut err) => {
2172 args.push(arg);
2173 // We will emit a more generic error later.
2174 err.delay_as_bug();
2175 }
2176 }
2177 return Ok(false); // Don't continue.
2178 }
2179
fc512014
XL
2180 /// Attempt to parse a generic const argument that has not been enclosed in braces.
2181 /// There are a limited number of expressions that are permitted without being encoded
2182 /// in braces:
2183 /// - Literals.
2184 /// - Single-segment paths (i.e. standalone generic const parameters).
2185 /// All other expressions that can be parsed will emit an error suggesting the expression be
2186 /// wrapped in braces.
29967ef6
XL
2187 pub fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
2188 let start = self.token.span;
2189 let expr = self.parse_expr_res(Restrictions::CONST_EXPR, None).map_err(|mut err| {
2190 err.span_label(
2191 start.shrink_to_lo(),
2192 "while parsing a const generic argument starting here",
2193 );
2194 err
2195 })?;
2196 if !self.expr_is_valid_const_arg(&expr) {
2b03887a
FG
2197 self.sess.emit_err(ConstGenericWithoutBraces {
2198 span: expr.span,
2199 sugg: ConstGenericWithoutBracesSugg {
2200 left: expr.span.shrink_to_lo(),
2201 right: expr.span.shrink_to_hi(),
2202 },
2203 });
29967ef6
XL
2204 }
2205 Ok(expr)
2206 }
2207
5e7ed085
FG
2208 fn recover_const_param_decl(&mut self, ty_generics: Option<&Generics>) -> Option<GenericArg> {
2209 let snapshot = self.create_snapshot_for_diagnostic();
f2b60f7d 2210 let param = match self.parse_const_param(AttrVec::new()) {
3c0e092e 2211 Ok(param) => param,
5e7ed085 2212 Err(err) => {
3c0e092e 2213 err.cancel();
5e7ed085
FG
2214 self.restore_snapshot(snapshot);
2215 return None;
3c0e092e
XL
2216 }
2217 };
2b03887a
FG
2218
2219 let ident = param.ident.to_string();
2220 let sugg = match (ty_generics, self.sess.source_map().span_to_snippet(param.span())) {
2221 (Some(Generics { params, span: impl_generics, .. }), Ok(snippet)) => {
2222 Some(match &params[..] {
2223 [] => UnexpectedConstParamDeclarationSugg::AddParam {
2224 impl_generics: *impl_generics,
2225 incorrect_decl: param.span(),
2226 snippet,
2227 ident,
2228 },
2229 [.., generic] => UnexpectedConstParamDeclarationSugg::AppendParam {
2230 impl_generics_end: generic.span().shrink_to_hi(),
2231 incorrect_decl: param.span(),
2232 snippet,
2233 ident,
2234 },
2235 })
2236 }
2237 _ => None,
2238 };
2239 self.sess.emit_err(UnexpectedConstParamDeclaration { span: param.span(), sugg });
2240
3c0e092e 2241 let value = self.mk_expr_err(param.span());
5e7ed085 2242 Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }))
3c0e092e
XL
2243 }
2244
2245 pub fn recover_const_param_declaration(
2246 &mut self,
2247 ty_generics: Option<&Generics>,
2248 ) -> PResult<'a, Option<GenericArg>> {
2249 // We have to check for a few different cases.
5e7ed085
FG
2250 if let Some(arg) = self.recover_const_param_decl(ty_generics) {
2251 return Ok(Some(arg));
3c0e092e
XL
2252 }
2253
2254 // We haven't consumed `const` yet.
2255 let start = self.token.span;
2256 self.bump(); // `const`
2257
2258 // Detect and recover from the old, pre-RFC2000 syntax for const generics.
2b03887a 2259 let mut err = UnexpectedConstInGenericParam { span: start, to_remove: None };
3c0e092e 2260 if self.check_const_arg() {
2b03887a
FG
2261 err.to_remove = Some(start.until(self.token.span));
2262 self.sess.emit_err(err);
3c0e092e
XL
2263 Ok(Some(GenericArg::Const(self.parse_const_arg()?)))
2264 } else {
2265 let after_kw_const = self.token.span;
2b03887a
FG
2266 self.recover_const_arg(after_kw_const, err.into_diagnostic(&self.sess.span_diagnostic))
2267 .map(Some)
3c0e092e
XL
2268 }
2269 }
2270
29967ef6
XL
2271 /// Try to recover from possible generic const argument without `{` and `}`.
2272 ///
2273 /// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
2274 /// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
2b03887a 2275 /// if we think that the resulting expression would be well formed.
29967ef6
XL
2276 pub fn recover_const_arg(
2277 &mut self,
2278 start: Span,
5e7ed085 2279 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
29967ef6 2280 ) -> PResult<'a, GenericArg> {
5e7ed085 2281 let is_op_or_dot = AssocOp::from_token(&self.token)
29967ef6
XL
2282 .and_then(|op| {
2283 if let AssocOp::Greater
2284 | AssocOp::Less
2285 | AssocOp::ShiftRight
2286 | AssocOp::GreaterEqual
2287 // Don't recover from `foo::<bar = baz>`, because this could be an attempt to
2288 // assign a value to a defaulted generic parameter.
2289 | AssocOp::Assign
2290 | AssocOp::AssignOp(_) = op
2291 {
2292 None
2293 } else {
2294 Some(op)
2295 }
2296 })
5e7ed085
FG
2297 .is_some()
2298 || self.token.kind == TokenKind::Dot;
29967ef6
XL
2299 // This will be true when a trait object type `Foo +` or a path which was a `const fn` with
2300 // type params has been parsed.
2301 let was_op =
2302 matches!(self.prev_token.kind, token::BinOp(token::Plus | token::Shr) | token::Gt);
5e7ed085 2303 if !is_op_or_dot && !was_op {
29967ef6
XL
2304 // We perform these checks and early return to avoid taking a snapshot unnecessarily.
2305 return Err(err);
2306 }
5e7ed085
FG
2307 let snapshot = self.create_snapshot_for_diagnostic();
2308 if is_op_or_dot {
29967ef6
XL
2309 self.bump();
2310 }
2311 match self.parse_expr_res(Restrictions::CONST_EXPR, None) {
2312 Ok(expr) => {
c295e0f8
XL
2313 // Find a mistake like `MyTrait<Assoc == S::Assoc>`.
2314 if token::EqEq == snapshot.token.kind {
2315 err.span_suggestion(
2316 snapshot.token.span,
2317 "if you meant to use an associated type binding, replace `==` with `=`",
923072b8 2318 "=",
c295e0f8
XL
2319 Applicability::MaybeIncorrect,
2320 );
2321 let value = self.mk_expr_err(start.to(expr.span));
2322 err.emit();
2323 return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
5e7ed085
FG
2324 } else if token::Colon == snapshot.token.kind
2325 && expr.span.lo() == snapshot.token.span.hi()
2326 && matches!(expr.kind, ExprKind::Path(..))
2327 {
2328 // Find a mistake like "foo::var:A".
2329 err.span_suggestion(
2330 snapshot.token.span,
2331 "write a path separator here",
923072b8 2332 "::",
5e7ed085
FG
2333 Applicability::MaybeIncorrect,
2334 );
2335 err.emit();
2336 return Ok(GenericArg::Type(self.mk_ty(start.to(expr.span), TyKind::Err)));
c295e0f8
XL
2337 } else if token::Comma == self.token.kind || self.token.kind.should_end_const_arg()
2338 {
29967ef6
XL
2339 // Avoid the following output by checking that we consumed a full const arg:
2340 // help: expressions must be enclosed in braces to be used as const generic
2341 // arguments
2342 // |
2343 // LL | let sr: Vec<{ (u32, _, _) = vec![] };
2344 // | ^ ^
5e7ed085 2345 return Ok(self.dummy_const_arg_needs_braces(err, start.to(expr.span)));
29967ef6
XL
2346 }
2347 }
5e7ed085 2348 Err(err) => {
29967ef6
XL
2349 err.cancel();
2350 }
2351 }
5e7ed085 2352 self.restore_snapshot(snapshot);
29967ef6
XL
2353 Err(err)
2354 }
fc512014 2355
5e7ed085
FG
2356 /// Creates a dummy const argument, and reports that the expression must be enclosed in braces
2357 pub fn dummy_const_arg_needs_braces(
2358 &self,
2359 mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2360 span: Span,
2361 ) -> GenericArg {
2362 err.multipart_suggestion(
2363 "expressions must be enclosed in braces to be used as const generic \
2364 arguments",
2365 vec![(span.shrink_to_lo(), "{ ".to_string()), (span.shrink_to_hi(), " }".to_string())],
2366 Applicability::MaybeIncorrect,
2367 );
2368 let value = self.mk_expr_err(span);
2369 err.emit();
2370 GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })
2371 }
2372
a2a8927a
XL
2373 /// Some special error handling for the "top-level" patterns in a match arm,
2374 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
923072b8 2375 pub(crate) fn maybe_recover_colon_colon_in_pat_typo(
a2a8927a
XL
2376 &mut self,
2377 mut first_pat: P<Pat>,
a2a8927a
XL
2378 expected: Expected,
2379 ) -> P<Pat> {
923072b8 2380 if token::Colon != self.token.kind {
a2a8927a
XL
2381 return first_pat;
2382 }
2383 if !matches!(first_pat.kind, PatKind::Ident(_, _, None) | PatKind::Path(..))
2384 || !self.look_ahead(1, |token| token.is_ident() && !token.is_reserved_ident())
2385 {
2386 return first_pat;
2387 }
2388 // The pattern looks like it might be a path with a `::` -> `:` typo:
2389 // `match foo { bar:baz => {} }`
2390 let span = self.token.span;
2391 // We only emit "unexpected `:`" error here if we can successfully parse the
2392 // whole pattern correctly in that case.
5e7ed085 2393 let snapshot = self.create_snapshot_for_diagnostic();
a2a8927a
XL
2394
2395 // Create error for "unexpected `:`".
2396 match self.expected_one_of_not_found(&[], &[]) {
2397 Err(mut err) => {
2398 self.bump(); // Skip the `:`.
2399 match self.parse_pat_no_top_alt(expected) {
5e7ed085 2400 Err(inner_err) => {
a2a8927a
XL
2401 // Carry on as if we had not done anything, callers will emit a
2402 // reasonable error.
2403 inner_err.cancel();
2404 err.cancel();
5e7ed085 2405 self.restore_snapshot(snapshot);
a2a8927a
XL
2406 }
2407 Ok(mut pat) => {
2408 // We've parsed the rest of the pattern.
2409 let new_span = first_pat.span.to(pat.span);
2410 let mut show_sugg = false;
2411 // Try to construct a recovered pattern.
2412 match &mut pat.kind {
2413 PatKind::Struct(qself @ None, path, ..)
2414 | PatKind::TupleStruct(qself @ None, path, _)
2415 | PatKind::Path(qself @ None, path) => match &first_pat.kind {
2416 PatKind::Ident(_, ident, _) => {
5099ac24 2417 path.segments.insert(0, PathSegment::from_ident(*ident));
a2a8927a
XL
2418 path.span = new_span;
2419 show_sugg = true;
2420 first_pat = pat;
2421 }
2422 PatKind::Path(old_qself, old_path) => {
2423 path.segments = old_path
2424 .segments
2425 .iter()
2426 .cloned()
2427 .chain(take(&mut path.segments))
2428 .collect();
2429 path.span = new_span;
2430 *qself = old_qself.clone();
2431 first_pat = pat;
2432 show_sugg = true;
2433 }
2434 _ => {}
2435 },
f2b60f7d 2436 PatKind::Ident(BindingAnnotation::NONE, ident, None) => {
a2a8927a
XL
2437 match &first_pat.kind {
2438 PatKind::Ident(_, old_ident, _) => {
2439 let path = PatKind::Path(
2440 None,
2441 Path {
2442 span: new_span,
487cf647 2443 segments: thin_vec![
5099ac24
FG
2444 PathSegment::from_ident(*old_ident),
2445 PathSegment::from_ident(*ident),
a2a8927a
XL
2446 ],
2447 tokens: None,
2448 },
2449 );
2450 first_pat = self.mk_pat(new_span, path);
2451 show_sugg = true;
2452 }
2453 PatKind::Path(old_qself, old_path) => {
2454 let mut segments = old_path.segments.clone();
5099ac24 2455 segments.push(PathSegment::from_ident(*ident));
a2a8927a
XL
2456 let path = PatKind::Path(
2457 old_qself.clone(),
2458 Path { span: new_span, segments, tokens: None },
2459 );
2460 first_pat = self.mk_pat(new_span, path);
2461 show_sugg = true;
2462 }
2463 _ => {}
2464 }
2465 }
2466 _ => {}
2467 }
2468 if show_sugg {
2469 err.span_suggestion(
2470 span,
2471 "maybe write a path separator here",
923072b8 2472 "::",
a2a8927a
XL
2473 Applicability::MaybeIncorrect,
2474 );
2475 } else {
2476 first_pat = self.mk_pat(new_span, PatKind::Wild);
2477 }
2478 err.emit();
2479 }
2480 }
2481 }
2482 _ => {
2483 // Carry on as if we had not done anything. This should be unreachable.
5e7ed085 2484 self.restore_snapshot(snapshot);
a2a8927a
XL
2485 }
2486 };
2487 first_pat
2488 }
2489
923072b8 2490 pub(crate) fn maybe_recover_unexpected_block_label(&mut self) -> bool {
2b03887a
FG
2491 // Check for `'a : {`
2492 if !(self.check_lifetime()
2493 && self.look_ahead(1, |tok| tok.kind == token::Colon)
2494 && self.look_ahead(2, |tok| tok.kind == token::OpenDelim(Delimiter::Brace)))
2495 {
5e7ed085 2496 return false;
2b03887a
FG
2497 }
2498 let label = self.eat_label().expect("just checked if a label exists");
2499 self.bump(); // eat `:`
5e7ed085
FG
2500 let span = label.ident.span.to(self.prev_token.span);
2501 let mut err = self.struct_span_err(span, "block label not supported here");
2502 err.span_label(span, "not supported here");
2503 err.tool_only_span_suggestion(
2504 label.ident.span.until(self.token.span),
2505 "remove this block label",
923072b8 2506 "",
5e7ed085
FG
2507 Applicability::MachineApplicable,
2508 );
2509 err.emit();
2510 true
2511 }
2512
a2a8927a
XL
2513 /// Some special error handling for the "top-level" patterns in a match arm,
2514 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
923072b8 2515 pub(crate) fn maybe_recover_unexpected_comma(
a2a8927a
XL
2516 &mut self,
2517 lo: Span,
5e7ed085 2518 rt: CommaRecoveryMode,
a2a8927a 2519 ) -> PResult<'a, ()> {
923072b8 2520 if self.token != token::Comma {
a2a8927a
XL
2521 return Ok(());
2522 }
2523
2524 // An unexpected comma after a top-level pattern is a clue that the
2525 // user (perhaps more accustomed to some other language) forgot the
2526 // parentheses in what should have been a tuple pattern; return a
2527 // suggestion-enhanced error here rather than choking on the comma later.
2528 let comma_span = self.token.span;
2529 self.bump();
5e7ed085 2530 if let Err(err) = self.skip_pat_list() {
a2a8927a
XL
2531 // We didn't expect this to work anyway; we just wanted to advance to the
2532 // end of the comma-sequence so we know the span to suggest parenthesizing.
2533 err.cancel();
2534 }
2535 let seq_span = lo.to(self.prev_token.span);
2536 let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
2537 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
5e7ed085
FG
2538 err.multipart_suggestion(
2539 &format!(
2540 "try adding parentheses to match on a tuple{}",
2541 if let CommaRecoveryMode::LikelyTuple = rt { "" } else { "..." },
2542 ),
2543 vec![
2544 (seq_span.shrink_to_lo(), "(".to_string()),
2545 (seq_span.shrink_to_hi(), ")".to_string()),
2546 ],
a2a8927a
XL
2547 Applicability::MachineApplicable,
2548 );
5e7ed085
FG
2549 if let CommaRecoveryMode::EitherTupleOrPipe = rt {
2550 err.span_suggestion(
2551 seq_span,
2552 "...or a vertical bar to match on multiple alternatives",
2553 seq_snippet.replace(',', " |"),
2554 Applicability::MachineApplicable,
2555 );
2556 }
a2a8927a
XL
2557 }
2558 Err(err)
2559 }
2560
923072b8 2561 pub(crate) fn maybe_recover_bounds_doubled_colon(&mut self, ty: &Ty) -> PResult<'a, ()> {
5e7ed085
FG
2562 let TyKind::Path(qself, path) = &ty.kind else { return Ok(()) };
2563 let qself_position = qself.as_ref().map(|qself| qself.position);
2564 for (i, segments) in path.segments.windows(2).enumerate() {
2565 if qself_position.map(|pos| i < pos).unwrap_or(false) {
2566 continue;
2567 }
2568 if let [a, b] = segments {
2569 let (a_span, b_span) = (a.span(), b.span());
2570 let between_span = a_span.shrink_to_hi().to(b_span.shrink_to_lo());
487cf647 2571 if self.span_to_snippet(between_span).as_deref() == Ok(":: ") {
2b03887a
FG
2572 return Err(DoubleColonInBound {
2573 span: path.span.shrink_to_hi(),
2574 between: between_span,
2575 }
2576 .into_diagnostic(&self.sess.span_diagnostic));
5e7ed085
FG
2577 }
2578 }
2579 }
2580 Ok(())
2581 }
2582
9c376795
FG
2583 pub fn is_diff_marker(&mut self, long_kind: &TokenKind, short_kind: &TokenKind) -> bool {
2584 (0..3).all(|i| self.look_ahead(i, |tok| tok == long_kind))
2585 && self.look_ahead(3, |tok| tok == short_kind)
2586 }
2587
2588 fn diff_marker(&mut self, long_kind: &TokenKind, short_kind: &TokenKind) -> Option<Span> {
2589 if self.is_diff_marker(long_kind, short_kind) {
2590 let lo = self.token.span;
2591 for _ in 0..4 {
2592 self.bump();
2593 }
2594 return Some(lo.to(self.prev_token.span));
2595 }
2596 None
2597 }
2598
2599 pub fn recover_diff_marker(&mut self) {
2600 let Some(start) = self.diff_marker(&TokenKind::BinOp(token::Shl), &TokenKind::Lt) else {
2601 return;
2602 };
2603 let mut spans = Vec::with_capacity(3);
2604 spans.push(start);
2605 let mut middlediff3 = None;
2606 let mut middle = None;
2607 let mut end = None;
2608 loop {
2609 if self.token.kind == TokenKind::Eof {
2610 break;
2611 }
2612 if let Some(span) = self.diff_marker(&TokenKind::OrOr, &TokenKind::BinOp(token::Or)) {
2613 middlediff3 = Some(span);
2614 }
2615 if let Some(span) = self.diff_marker(&TokenKind::EqEq, &TokenKind::Eq) {
2616 middle = Some(span);
2617 }
2618 if let Some(span) = self.diff_marker(&TokenKind::BinOp(token::Shr), &TokenKind::Gt) {
2619 spans.push(span);
2620 end = Some(span);
2621 break;
2622 }
2623 self.bump();
2624 }
2625 let mut err = self.struct_span_err(spans, "encountered diff marker");
2626 err.span_label(start, "after this is the code before the merge");
2627 if let Some(middle) = middlediff3 {
2628 err.span_label(middle, "");
2629 }
2630 if let Some(middle) = middle {
2631 err.span_label(middle, "");
2632 }
2633 if let Some(end) = end {
2634 err.span_label(end, "above this are the incoming code changes");
2635 }
2636 err.help(
2637 "if you're having merge conflicts after pulling new code, the top section is the code \
2638 you already had and the bottom section is the remote code",
2639 );
2640 err.help(
2641 "if you're in the middle of a rebase, the top section is the code being rebased onto \
2642 and the bottom section is the code coming from the current commit being rebased",
2643 );
2644 err.note(
2645 "for an explanation on these markers from the `git` documentation, visit \
2646 <https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging#_checking_out_conflicts>",
2647 );
2648 err.emit();
2649 FatalError.raise()
2650 }
2651
a2a8927a
XL
2652 /// Parse and throw away a parenthesized comma separated
2653 /// sequence of patterns until `)` is reached.
2654 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
04454e1e 2655 while !self.check(&token::CloseDelim(Delimiter::Parenthesis)) {
a2a8927a
XL
2656 self.parse_pat_no_top_alt(None)?;
2657 if !self.eat(&token::Comma) {
2658 return Ok(());
2659 }
2660 }
2661 Ok(())
2662 }
48663c56 2663}