Preserve braces around self in use tree pretty printing

The AST pretty printer strips braces from single-item `use` sub-groups,
simplifying `use foo::{Bar}` to `use foo::Bar`. However, when the single
item is `self`, this produces `use foo::self` which is not valid Rust
(E0429) — the grammar requires `use foo::{self}`.

This affects both `stringify!` and `rustc -Zunpretty=expanded`, causing
`cargo expand` output to be unparseable when a crate uses `use
path::{self}` imports (a common pattern in the ecosystem).

The fix checks whether the single nested item's path starts with `self`
before stripping braces. If so, the braces are preserved.

Signed-off-by: Andrew V. Teylu <andrew.teylu@vector.com>
This commit is contained in:
Andrew V. Teylu
2026-03-19 10:27:40 +00:00
parent fd0c901b00
commit 082cdf7c48
2 changed files with 17 additions and 1 deletions
@@ -881,7 +881,13 @@ fn print_use_tree(&mut self, tree: &ast::UseTree) {
}
if items.is_empty() {
self.word("{}");
} else if let [(item, _)] = items.as_slice() {
} else if let [(item, _)] = items.as_slice()
&& !item
.prefix
.segments
.first()
.is_some_and(|seg| seg.ident.name == rustc_span::symbol::kw::SelfLower)
{
self.print_use_tree(item);
} else {
let cb = self.cbox(INDENT_UNIT);
+10
View File
@@ -0,0 +1,10 @@
//@ pp-exact
//@ edition:2021
#![allow(unused_imports)]
// Braces around `self` must be preserved, because `use foo::self` is not valid Rust.
use std::io::{self};
use std::fmt::{self, Debug};
fn main() {}