Skip to content

Commit 5e67a37

Browse files
compiler: add Parser::debug_lookahead
I tried debugging a parser-related issue but found it annoying to not be able to easily peek into the Parser's token stream. Add a convenience fn that offers an opinionated view into the parser, but one that is useful for answering basic questions about parser state.
1 parent c70290d commit 5e67a37

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

compiler/rustc_parse/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#![allow(rustc::untranslatable_diagnostic)]
66
#![feature(array_windows)]
77
#![feature(box_patterns)]
8+
#![feature(debug_closure_helpers)]
89
#![feature(if_let_guard)]
910
#![feature(iter_intersperse)]
1011
#![feature(let_chains)]

compiler/rustc_parse/src/parser/mod.rs

+41
Original file line numberDiff line numberDiff line change
@@ -1537,6 +1537,47 @@ impl<'a> Parser<'a> {
15371537
})
15381538
}
15391539

1540+
// debug view of the parser's token stream, up to `{lookahead}` tokens
1541+
pub fn debug_lookahead(&self, lookahead: usize) -> impl fmt::Debug + '_ {
1542+
struct DebugParser<'dbg> {
1543+
parser: &'dbg Parser<'dbg>,
1544+
lookahead: usize,
1545+
}
1546+
1547+
impl fmt::Debug for DebugParser<'_> {
1548+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1549+
let Self { parser, lookahead } = self;
1550+
let mut dbg_fmt = f.debug_struct("Parser"); // or at least, one view of
1551+
1552+
// we don't need N spans, but we want at least one, so print all of prev_token
1553+
dbg_fmt.field("prev_token", &parser.prev_token);
1554+
// make it easier to peek farther ahead by taking TokenKinds only until EOF
1555+
let tokens = (0..*lookahead)
1556+
.map(|i| parser.look_ahead(i, |tok| tok.kind.clone()))
1557+
.scan(parser.prev_token == TokenKind::Eof, |eof, tok| {
1558+
let current = eof.then_some(tok.clone()); // include a trailing EOF token
1559+
*eof |= &tok == &TokenKind::Eof;
1560+
current
1561+
});
1562+
dbg_fmt.field_with("tokens", |field| field.debug_list().entries(tokens).finish());
1563+
dbg_fmt.field("approx_token_stream_pos", &parser.num_bump_calls);
1564+
1565+
// some fields are interesting for certain values, as they relate to macro parsing
1566+
if let Some(subparser) = parser.subparser_name {
1567+
dbg_fmt.field("subparser_name", &subparser);
1568+
}
1569+
if let Recovery::Forbidden = parser.recovery {
1570+
dbg_fmt.field("recovery", &parser.recovery);
1571+
}
1572+
1573+
// imply there's "more to know" than this view
1574+
dbg_fmt.finish_non_exhaustive()
1575+
}
1576+
}
1577+
1578+
DebugParser { parser: self, lookahead }
1579+
}
1580+
15401581
pub fn clear_expected_tokens(&mut self) {
15411582
self.expected_tokens.clear();
15421583
}

0 commit comments

Comments
 (0)