Skip to content

Commit dd6f03d

Browse files
authored
Rollup merge of #108715 - chenyukang:yukang/cleanup-parser-delims, r=compiler-errors
Remove unclosed_delims from parser After landing #108297 we could remove `unclosed_delims` from the parser now.
2 parents 538f19d + d1073fa commit dd6f03d

File tree

4 files changed

+12
-158
lines changed

4 files changed

+12
-158
lines changed

compiler/rustc_parse/src/parser/diagnostics.rs

+3-113
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ use crate::errors::{
1919
};
2020

2121
use crate::fluent_generated as fluent;
22-
use crate::lexer::UnmatchedDelim;
2322
use crate::parser;
2423
use rustc_ast as ast;
2524
use rustc_ast::ptr::P;
@@ -220,7 +219,6 @@ impl MultiSugg {
220219
/// is dropped.
221220
pub struct SnapshotParser<'a> {
222221
parser: Parser<'a>,
223-
unclosed_delims: Vec<UnmatchedDelim>,
224222
}
225223

226224
impl<'a> Deref for SnapshotParser<'a> {
@@ -255,27 +253,15 @@ impl<'a> Parser<'a> {
255253
&self.sess.span_diagnostic
256254
}
257255

258-
/// Replace `self` with `snapshot.parser` and extend `unclosed_delims` with `snapshot.unclosed_delims`.
259-
/// This is to avoid losing unclosed delims errors `create_snapshot_for_diagnostic` clears.
256+
/// Replace `self` with `snapshot.parser`.
260257
pub(super) fn restore_snapshot(&mut self, snapshot: SnapshotParser<'a>) {
261258
*self = snapshot.parser;
262-
self.unclosed_delims.extend(snapshot.unclosed_delims);
263-
}
264-
265-
pub fn unclosed_delims(&self) -> &[UnmatchedDelim] {
266-
&self.unclosed_delims
267259
}
268260

269261
/// Create a snapshot of the `Parser`.
270262
pub fn create_snapshot_for_diagnostic(&self) -> SnapshotParser<'a> {
271-
let mut snapshot = self.clone();
272-
let unclosed_delims = self.unclosed_delims.clone();
273-
// Clear `unclosed_delims` in snapshot to avoid
274-
// duplicate errors being emitted when the `Parser`
275-
// is dropped (which may or may not happen, depending
276-
// if the parsing the snapshot is created for is successful)
277-
snapshot.unclosed_delims.clear();
278-
SnapshotParser { parser: snapshot, unclosed_delims }
263+
let snapshot = self.clone();
264+
SnapshotParser { parser: snapshot }
279265
}
280266

281267
pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
@@ -579,21 +565,6 @@ impl<'a> Parser<'a> {
579565
} else {
580566
label_sp
581567
};
582-
match self.recover_closing_delimiter(
583-
&expected
584-
.iter()
585-
.filter_map(|tt| match tt {
586-
TokenType::Token(t) => Some(t.clone()),
587-
_ => None,
588-
})
589-
.collect::<Vec<_>>(),
590-
err,
591-
) {
592-
Err(e) => err = e,
593-
Ok(recovered) => {
594-
return Ok(recovered);
595-
}
596-
}
597568

598569
if self.check_too_many_raw_str_terminators(&mut err) {
599570
if expected.contains(&TokenType::Token(token::Semi)) && self.eat(&token::Semi) {
@@ -1573,12 +1544,6 @@ impl<'a> Parser<'a> {
15731544
);
15741545
let mut err = self.struct_span_err(sp, &msg);
15751546
let label_exp = format!("expected `{token_str}`");
1576-
match self.recover_closing_delimiter(&[t.clone()], err) {
1577-
Err(e) => err = e,
1578-
Ok(recovered) => {
1579-
return Ok(recovered);
1580-
}
1581-
}
15821547
let sm = self.sess.source_map();
15831548
if !sm.is_multiline(prev_sp.until(sp)) {
15841549
// When the spans are in the same line, it means that the only content
@@ -1795,81 +1760,6 @@ impl<'a> Parser<'a> {
17951760
}
17961761
}
17971762

1798-
pub(super) fn recover_closing_delimiter(
1799-
&mut self,
1800-
tokens: &[TokenKind],
1801-
mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
1802-
) -> PResult<'a, bool> {
1803-
let mut pos = None;
1804-
// We want to use the last closing delim that would apply.
1805-
for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1806-
if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1807-
&& Some(self.token.span) > unmatched.unclosed_span
1808-
{
1809-
pos = Some(i);
1810-
}
1811-
}
1812-
match pos {
1813-
Some(pos) => {
1814-
// Recover and assume that the detected unclosed delimiter was meant for
1815-
// this location. Emit the diagnostic and act as if the delimiter was
1816-
// present for the parser's sake.
1817-
1818-
// Don't attempt to recover from this unclosed delimiter more than once.
1819-
let unmatched = self.unclosed_delims.remove(pos);
1820-
let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1821-
if unmatched.found_delim.is_none() {
1822-
// We encountered `Eof`, set this fact here to avoid complaining about missing
1823-
// `fn main()` when we found place to suggest the closing brace.
1824-
*self.sess.reached_eof.borrow_mut() = true;
1825-
}
1826-
1827-
// We want to suggest the inclusion of the closing delimiter where it makes
1828-
// the most sense, which is immediately after the last token:
1829-
//
1830-
// {foo(bar {}}
1831-
// ^ ^
1832-
// | |
1833-
// | help: `)` may belong here
1834-
// |
1835-
// unclosed delimiter
1836-
if let Some(sp) = unmatched.unclosed_span {
1837-
let mut primary_span: Vec<Span> =
1838-
err.span.primary_spans().iter().cloned().collect();
1839-
primary_span.push(sp);
1840-
let mut primary_span: MultiSpan = primary_span.into();
1841-
for span_label in err.span.span_labels() {
1842-
if let Some(label) = span_label.label {
1843-
primary_span.push_span_label(span_label.span, label);
1844-
}
1845-
}
1846-
err.set_span(primary_span);
1847-
err.span_label(sp, "unclosed delimiter");
1848-
}
1849-
// Backticks should be removed to apply suggestions.
1850-
let mut delim = delim.to_string();
1851-
delim.retain(|c| c != '`');
1852-
err.span_suggestion_short(
1853-
self.prev_token.span.shrink_to_hi(),
1854-
&format!("`{delim}` may belong here"),
1855-
delim,
1856-
Applicability::MaybeIncorrect,
1857-
);
1858-
if unmatched.found_delim.is_none() {
1859-
// Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1860-
// errors which would be emitted elsewhere in the parser and let other error
1861-
// recovery consume the rest of the file.
1862-
Err(err)
1863-
} else {
1864-
err.emit();
1865-
self.expected_tokens.clear(); // Reduce the number of errors.
1866-
Ok(true)
1867-
}
1868-
}
1869-
_ => Err(err),
1870-
}
1871-
}
1872-
18731763
/// Eats tokens until we can be relatively sure we reached the end of the
18741764
/// statement. This is something of a best-effort heuristic.
18751765
///

compiler/rustc_parse/src/parser/expr.rs

-13
Original file line numberDiff line numberDiff line change
@@ -1394,19 +1394,6 @@ impl<'a> Parser<'a> {
13941394
self.parse_expr_let()
13951395
} else if self.eat_keyword(kw::Underscore) {
13961396
Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore))
1397-
} else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1398-
// Don't complain about bare semicolons after unclosed braces
1399-
// recovery in order to keep the error count down. Fixing the
1400-
// delimiters will possibly also fix the bare semicolon found in
1401-
// expression context. For example, silence the following error:
1402-
//
1403-
// error: expected expression, found `;`
1404-
// --> file.rs:2:13
1405-
// |
1406-
// 2 | foo(bar(;
1407-
// | ^ expected expression
1408-
self.bump();
1409-
Ok(self.mk_expr_err(self.token.span))
14101397
} else if self.token.uninterpolated_span().rust_2018() {
14111398
// `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
14121399
if self.check_keyword(kw::Async) {

compiler/rustc_parse/src/parser/item.rs

+6-18
Original file line numberDiff line numberDiff line change
@@ -125,16 +125,13 @@ impl<'a> Parser<'a> {
125125
return Ok(Some(item.into_inner()));
126126
};
127127

128-
let mut unclosed_delims = vec![];
129128
let item =
130129
self.collect_tokens_trailing_token(attrs, force_collect, |this: &mut Self, attrs| {
131130
let item =
132131
this.parse_item_common_(attrs, mac_allowed, attrs_allowed, fn_parse_mode);
133-
unclosed_delims.append(&mut this.unclosed_delims);
134132
Ok((item?, TrailingToken::None))
135133
})?;
136134

137-
self.unclosed_delims.append(&mut unclosed_delims);
138135
Ok(item)
139136
}
140137

@@ -1960,21 +1957,12 @@ impl<'a> Parser<'a> {
19601957
// FIXME: This will make us not emit the help even for declarative
19611958
// macros within the same crate (that we can fix), which is sad.
19621959
if !span.from_expansion() {
1963-
if self.unclosed_delims.is_empty() {
1964-
let DelimSpan { open, close } = args.dspan;
1965-
err.multipart_suggestion(
1966-
"change the delimiters to curly braces",
1967-
vec![(open, "{".to_string()), (close, '}'.to_string())],
1968-
Applicability::MaybeIncorrect,
1969-
);
1970-
} else {
1971-
err.span_suggestion(
1972-
span,
1973-
"change the delimiters to curly braces",
1974-
" { /* items */ }",
1975-
Applicability::HasPlaceholders,
1976-
);
1977-
}
1960+
let DelimSpan { open, close } = args.dspan;
1961+
err.multipart_suggestion(
1962+
"change the delimiters to curly braces",
1963+
vec![(open, "{".to_string()), (close, '}'.to_string())],
1964+
Applicability::MaybeIncorrect,
1965+
);
19781966
err.span_suggestion(
19791967
span.shrink_to_hi(),
19801968
"add a semicolon",

compiler/rustc_parse/src/parser/mod.rs

+3-14
Original file line numberDiff line numberDiff line change
@@ -146,10 +146,7 @@ pub struct Parser<'a> {
146146
/// See the comments in the `parse_path_segment` function for more details.
147147
unmatched_angle_bracket_count: u32,
148148
max_angle_bracket_count: u32,
149-
/// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
150-
/// it gets removed from here. Every entry left at the end gets emitted as an independent
151-
/// error.
152-
pub(super) unclosed_delims: Vec<UnmatchedDelim>,
149+
153150
last_unexpected_token_span: Option<Span>,
154151
/// Span pointing at the `:` for the last type ascription the parser has seen, and whether it
155152
/// looked like it could have been a mistyped path or literal `Option:Some(42)`).
@@ -168,7 +165,7 @@ pub struct Parser<'a> {
168165
// This type is used a lot, e.g. it's cloned when matching many declarative macro rules with nonterminals. Make sure
169166
// it doesn't unintentionally get bigger.
170167
#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
171-
rustc_data_structures::static_assert_size!(Parser<'_>, 312);
168+
rustc_data_structures::static_assert_size!(Parser<'_>, 288);
172169

173170
/// Stores span information about a closure.
174171
#[derive(Clone)]
@@ -215,12 +212,6 @@ struct CaptureState {
215212
inner_attr_ranges: FxHashMap<AttrId, ReplaceRange>,
216213
}
217214

218-
impl<'a> Drop for Parser<'a> {
219-
fn drop(&mut self) {
220-
emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
221-
}
222-
}
223-
224215
/// Iterator over a `TokenStream` that produces `Token`s. It's a bit odd that
225216
/// we (a) lex tokens into a nice tree structure (`TokenStream`), and then (b)
226217
/// use this type to emit them as a linear sequence. But a linear sequence is
@@ -478,7 +469,6 @@ impl<'a> Parser<'a> {
478469
desugar_doc_comments,
479470
unmatched_angle_bracket_count: 0,
480471
max_angle_bracket_count: 0,
481-
unclosed_delims: Vec::new(),
482472
last_unexpected_token_span: None,
483473
last_type_ascription: None,
484474
subparser_name,
@@ -859,7 +849,6 @@ impl<'a> Parser<'a> {
859849
let mut recovered = false;
860850
let mut trailing = false;
861851
let mut v = ThinVec::new();
862-
let unclosed_delims = !self.unclosed_delims.is_empty();
863852

864853
while !self.expect_any_with_type(kets, expect) {
865854
if let token::CloseDelim(..) | token::Eof = self.token.kind {
@@ -901,7 +890,7 @@ impl<'a> Parser<'a> {
901890
_ => {
902891
// Attempt to keep parsing if it was a similar separator.
903892
if let Some(tokens) = t.similar_tokens() {
904-
if tokens.contains(&self.token.kind) && !unclosed_delims {
893+
if tokens.contains(&self.token.kind) {
905894
self.bump();
906895
}
907896
}

0 commit comments

Comments
 (0)