fix parentheses surrounding spacing issue in parser

This commit is contained in:
yukang 2022-10-24 18:24:10 +08:00
parent c0447b489b
commit a46af18cb1
6 changed files with 52 additions and 16 deletions

View file

@ -1122,10 +1122,12 @@ pub(crate) struct ParenthesesInForHead {
#[derive(Subdiagnostic)]
#[multipart_suggestion(suggestion, applicability = "machine-applicable")]
pub(crate) struct ParenthesesInForHeadSugg {
#[suggestion_part(code = "")]
#[suggestion_part(code = "{left_snippet}")]
pub left: Span,
#[suggestion_part(code = "")]
pub left_snippet: String,
#[suggestion_part(code = "{right_snippet}")]
pub right: Span,
pub right_snippet: String,
}
#[derive(Diagnostic)]

View file

@ -1641,15 +1641,29 @@ impl<'a> Parser<'a> {
(token::CloseDelim(Delimiter::Parenthesis), Some(begin_par_sp)) => {
self.bump();
let sm = self.sess.source_map();
let left = begin_par_sp;
let right = self.prev_token.span;
let left_snippet = if let Ok(snip) = sm.span_to_prev_source(left) &&
!snip.ends_with(" ") {
" ".to_string()
} else {
"".to_string()
};
let right_snippet = if let Ok(snip) = sm.span_to_next_source(right) &&
!snip.starts_with(" ") {
" ".to_string()
} else {
"".to_string()
};
self.sess.emit_err(ParenthesesInForHead {
span: vec![begin_par_sp, self.prev_token.span],
span: vec![left, right],
// With e.g. `for (x) in y)` this would replace `(x) in y)`
// with `x) in y)` which is syntactically invalid.
// However, this is prevented before we get here.
sugg: ParenthesesInForHeadSugg {
left: begin_par_sp,
right: self.prev_token.span,
},
sugg: ParenthesesInForHeadSugg { left, right, left_snippet, right_snippet },
});
// Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.