Skip to content

Improve hir pretty printing #140606

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
May 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions compiler/rustc_ast_pretty/src/pp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,9 +244,6 @@ struct BufEntry {
// forgotten will trigger a panic in `drop`. (Closing a box more than once
// isn't possible because `BoxMarker` doesn't implement `Copy` or `Clone`.)
//
// FIXME(nnethercote): the panic in `drop` is currently disabled because a few
// places fail to close their boxes. It can be enabled once they are fixed.
//
// Note: it would be better to make open/close mismatching impossible and avoid
// the need for this marker type altogether by having functions like
// `with_ibox` that open a box, call a closure, and then close the box. That
Expand All @@ -261,8 +258,7 @@ impl !Copy for BoxMarker {}

impl Drop for BoxMarker {
fn drop(&mut self) {
// FIXME(nnethercote): enable once the bad cases are fixed
//panic!("BoxMarker not ended with `Printer::end()`");
panic!("BoxMarker not ended with `Printer::end()`");
}
}

Expand Down
15 changes: 3 additions & 12 deletions compiler/rustc_ast_pretty/src/pprust/state/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use rustc_ast::{

use crate::pp::Breaks::Inconsistent;
use crate::pprust::state::fixup::FixupContext;
use crate::pprust::state::{AnnNode, BoxMarker, INDENT_UNIT, PrintState, State};
use crate::pprust::state::{AnnNode, INDENT_UNIT, PrintState, State};

impl<'a> State<'a> {
fn print_else(&mut self, els: Option<&ast::Expr>) {
Expand Down Expand Up @@ -485,12 +485,12 @@ impl<'a> State<'a> {
self.print_block_with_attrs(body, attrs, cb, ib);
}
ast::ExprKind::Loop(blk, opt_label, _) => {
let cb = self.cbox(0);
let ib = self.ibox(0);
if let Some(label) = opt_label {
self.print_ident(label.ident);
self.word_space(":");
}
let cb = self.cbox(0);
let ib = self.ibox(0);
self.word_nbsp("loop");
self.print_block_with_attrs(blk, attrs, cb, ib);
}
Expand Down Expand Up @@ -542,15 +542,6 @@ impl<'a> State<'a> {
self.print_fn_params_and_ret(fn_decl, true);
self.space();
self.print_expr(body, FixupContext::default());
// FIXME(nnethercote): Bogus. Reduce visibility of `ended` once it's fixed.
let fake_ib = BoxMarker;
self.end(fake_ib);

// A box will be closed by print_expr, but we didn't want an overall
// wrapper so we closed the corresponding opening. so create an
// empty box to satisfy the close.
// FIXME(nnethercote): Bogus.
let _ib = self.ibox(0);
}
ast::ExprKind::Block(blk, opt_label) => {
if let Some(label) = opt_label {
Expand Down
37 changes: 12 additions & 25 deletions compiler/rustc_hir_pretty/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ impl<'a> State<'a> {
}
self.print_attr_item(&unparsed, unparsed.span);
self.word("]");
self.hardbreak()
}
hir::Attribute::Parsed(AttributeKind::DocComment { style, kind, comment, .. }) => {
self.word(rustc_ast_pretty::pprust::state::doc_comment_to_string(
Expand Down Expand Up @@ -183,7 +184,7 @@ impl<'a> State<'a> {
Node::Ty(a) => self.print_type(a),
Node::AssocItemConstraint(a) => self.print_assoc_item_constraint(a),
Node::TraitRef(a) => self.print_trait_ref(a),
Node::OpaqueTy(o) => self.print_opaque_ty(o),
Node::OpaqueTy(_) => panic!("cannot print Node::OpaqueTy"),
Node::Pat(a) => self.print_pat(a),
Node::TyPat(a) => self.print_ty_pat(a),
Node::PatField(a) => self.print_patfield(a),
Expand Down Expand Up @@ -654,10 +655,11 @@ impl<'a> State<'a> {
self.bclose(item.span, cb);
}
hir::ItemKind::GlobalAsm { asm, .. } => {
// FIXME(nnethercote): `ib` is unclosed
let (cb, _ib) = self.head("global_asm!");
let (cb, ib) = self.head("global_asm!");
self.print_inline_asm(asm);
self.end(cb)
self.word(";");
self.end(cb);
self.end(ib);
}
hir::ItemKind::TyAlias(ident, ty, generics) => {
let (cb, ib) = self.head("type");
Expand Down Expand Up @@ -764,14 +766,6 @@ impl<'a> State<'a> {
self.print_path(t.path, false);
}

fn print_opaque_ty(&mut self, o: &hir::OpaqueTy<'_>) {
// FIXME(nnethercote): `cb` and `ib` are unclosed
let (_cb, _ib) = self.head("opaque");
self.word("{");
self.print_bounds("impl", o.bounds);
self.word("}");
}

fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
if !generic_params.is_empty() {
self.word("for");
Expand Down Expand Up @@ -1509,7 +1503,7 @@ impl<'a> State<'a> {
}
hir::ExprKind::DropTemps(init) => {
// Print `{`:
let cb = self.cbox(INDENT_UNIT);
let cb = self.cbox(0);
let ib = self.ibox(0);
self.bopen(ib);

Expand All @@ -1532,16 +1526,18 @@ impl<'a> State<'a> {
self.print_if(test, blk, elseopt);
}
hir::ExprKind::Loop(blk, opt_label, _, _) => {
let cb = self.cbox(0);
let ib = self.ibox(0);
if let Some(label) = opt_label {
self.print_ident(label.ident);
self.word_space(":");
}
let (cb, ib) = self.head("loop");
self.word_nbsp("loop");
self.print_block(blk, cb, ib);
}
hir::ExprKind::Match(expr, arms, _) => {
let cb = self.cbox(INDENT_UNIT);
let ib = self.ibox(INDENT_UNIT);
let cb = self.cbox(0);
let ib = self.ibox(0);
self.word_nbsp("match");
self.print_expr_as_cond(expr);
self.space();
Expand Down Expand Up @@ -1572,15 +1568,6 @@ impl<'a> State<'a> {

// This is a bare expression.
self.ann.nested(self, Nested::Body(body));
// FIXME(nnethercote): this is bogus
let fake_ib = BoxMarker;
self.end(fake_ib);

// A box will be closed by `print_expr`, but we didn't want an overall
// wrapper so we closed the corresponding opening. so create an
// empty box to satisfy the close.
// FIXME(nnethercote): this is bogus, and `print_expr` is missing
let _ib = self.ibox(0);
}
hir::ExprKind::Block(blk, opt_label) => {
if let Some(label) = opt_label {
Expand Down
3 changes: 2 additions & 1 deletion tests/pretty/hir-delegation.pp
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
//@ pretty-mode:hir
//@ pp-exact:hir-delegation.pp

#![allow(incomplete_features)]#![feature(fn_delegation)]
#![allow(incomplete_features)]
#![feature(fn_delegation)]
#[prelude_import]
use ::std::prelude::rust_2015::*;
#[macro_use]
Expand Down
2 changes: 1 addition & 1 deletion tests/rustdoc-json/attrs/automatically_derived.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ impl Default for Manual {
}
}

//@ is '$.index[?(@.inner.impl.for.resolved_path.path == "Derive" && @.inner.impl.trait.path == "Default")].attrs' '["#[automatically_derived]"]'
//@ is '$.index[?(@.inner.impl.for.resolved_path.path == "Derive" && @.inner.impl.trait.path == "Default")].attrs' '["#[automatically_derived]\n"]'
//@ is '$.index[?(@.inner.impl.for.resolved_path.path == "Manual" && @.inner.impl.trait.path == "Default")].attrs' '[]'
2 changes: 1 addition & 1 deletion tests/rustdoc-json/attrs/export_name_2021.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//@ edition: 2021
#![no_std]

//@ is "$.index[?(@.name=='example')].attrs" '["#[export_name = \"altered\"]"]'
//@ is "$.index[?(@.name=='example')].attrs" '["#[export_name = \"altered\"]\n"]'
#[export_name = "altered"]
pub extern "C" fn example() {}
2 changes: 1 addition & 1 deletion tests/rustdoc-json/attrs/export_name_2024.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@
// The representation of `#[unsafe(export_name = ..)]` in rustdoc in edition 2024
// is still `#[export_name = ..]` without the `unsafe` attribute wrapper.

//@ is "$.index[?(@.name=='example')].attrs" '["#[export_name = \"altered\"]"]'
//@ is "$.index[?(@.name=='example')].attrs" '["#[export_name = \"altered\"]\n"]'
#[unsafe(export_name = "altered")]
pub extern "C" fn example() {}
4 changes: 2 additions & 2 deletions tests/rustdoc-json/attrs/must_use.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#![no_std]

//@ is "$.index[?(@.name=='example')].attrs" '["#[must_use]"]'
//@ is "$.index[?(@.name=='example')].attrs" '["#[must_use]\n"]'
#[must_use]
pub fn example() -> impl Iterator<Item = i64> {}

//@ is "$.index[?(@.name=='explicit_message')].attrs" '["#[must_use = \"does nothing if you do not use it\"]"]'
//@ is "$.index[?(@.name=='explicit_message')].attrs" '["#[must_use = \"does nothing if you do not use it\"]\n"]'
#[must_use = "does nothing if you do not use it"]
pub fn explicit_message() -> impl Iterator<Item = i64> {}
2 changes: 1 addition & 1 deletion tests/rustdoc-json/attrs/no_mangle_2021.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//@ edition: 2021
#![no_std]

//@ is "$.index[?(@.name=='example')].attrs" '["#[no_mangle]"]'
//@ is "$.index[?(@.name=='example')].attrs" '["#[no_mangle]\n"]'
#[no_mangle]
pub extern "C" fn example() {}
2 changes: 1 addition & 1 deletion tests/rustdoc-json/attrs/no_mangle_2024.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@
// The representation of `#[unsafe(no_mangle)]` in rustdoc in edition 2024
// is still `#[no_mangle]` without the `unsafe` attribute wrapper.

//@ is "$.index[?(@.name=='example')].attrs" '["#[no_mangle]"]'
//@ is "$.index[?(@.name=='example')].attrs" '["#[no_mangle]\n"]'
#[unsafe(no_mangle)]
pub extern "C" fn example() {}
6 changes: 3 additions & 3 deletions tests/rustdoc-json/attrs/non_exhaustive.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
#![no_std]

//@ is "$.index[?(@.name=='MyEnum')].attrs" '["#[non_exhaustive]"]'
//@ is "$.index[?(@.name=='MyEnum')].attrs" '["#[non_exhaustive]\n"]'
#[non_exhaustive]
pub enum MyEnum {
First,
}

pub enum NonExhaustiveVariant {
//@ is "$.index[?(@.name=='Variant')].attrs" '["#[non_exhaustive]"]'
//@ is "$.index[?(@.name=='Variant')].attrs" '["#[non_exhaustive]\n"]'
#[non_exhaustive]
Variant(i64),
}

//@ is "$.index[?(@.name=='MyStruct')].attrs" '["#[non_exhaustive]"]'
//@ is "$.index[?(@.name=='MyStruct')].attrs" '["#[non_exhaustive]\n"]'
#[non_exhaustive]
pub struct MyStruct {
pub x: i64,
Expand Down
4 changes: 2 additions & 2 deletions tests/rustdoc-json/keyword_private.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@

//@ !has "$.index[?(@.name=='match')]"
//@ has "$.index[?(@.name=='foo')]"
//@ is "$.index[?(@.name=='foo')].attrs" '["#[doc(keyword = \"match\")]"]'
//@ is "$.index[?(@.name=='foo')].attrs" '["#[doc(keyword = \"match\")]\n"]'
//@ is "$.index[?(@.name=='foo')].docs" '"this is a test!"'
#[doc(keyword = "match")]
/// this is a test!
pub mod foo {}

//@ !has "$.index[?(@.name=='break')]"
//@ has "$.index[?(@.name=='bar')]"
//@ is "$.index[?(@.name=='bar')].attrs" '["#[doc(keyword = \"break\")]"]'
//@ is "$.index[?(@.name=='bar')].attrs" '["#[doc(keyword = \"break\")]\n"]'
//@ is "$.index[?(@.name=='bar')].docs" '"hello"'
#[doc(keyword = "break")]
/// hello
Expand Down
4 changes: 2 additions & 2 deletions tests/ui-fulldeps/stable-mir/check_attribute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ fn test_stable_mir() -> ControlFlow<()> {
fn test_tool(items: &CrateItems) {
let rustfmt_fn = *get_item(&items, "do_not_format").unwrap();
let rustfmt_attrs = rustfmt_fn.tool_attrs(&["rustfmt".to_string(), "skip".to_string()]);
assert_eq!(rustfmt_attrs[0].as_str(), "#[rustfmt::skip]");
assert_eq!(rustfmt_attrs[0].as_str(), "#[rustfmt::skip]\n");

let clippy_fn = *get_item(&items, "complex_fn").unwrap();
let clippy_attrs = clippy_fn.tool_attrs(&["clippy".to_string(),
"cyclomatic_complexity".to_string()]);
assert_eq!(clippy_attrs[0].as_str(), "#[clippy::cyclomatic_complexity = \"100\"]");
assert_eq!(clippy_attrs[0].as_str(), "#[clippy::cyclomatic_complexity = \"100\"]\n");
}

fn get_item<'a>(
Expand Down
3 changes: 2 additions & 1 deletion tests/ui/unpretty/exhaustive-asm.hir.stdout
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,6 @@ mod expressions {
mod items {
/// ItemKind::GlobalAsm
mod item_global_asm {/// ItemKind::GlobalAsm
global_asm! (".globl my_asm_func") }
global_asm! (".globl my_asm_func");
}
}
Loading
Loading