Improve hir_pretty for struct expressions.

Before:

    let a =
        StructWithSomeFields{
            field_1: 1,

            field_2: 2,

            field_3: 3,

            field_4: 4,

            field_5: 5,

            field_6: 6,};

    let a = StructWithSomeFields{ field_1: 1,  field_2: 2, ..a};

After:

    let a =
        StructWithSomeFields {
            field_1: 1,
            field_2: 2,
            field_3: 3,
            field_4: 4,
            field_5: 5,
            field_6: 6 };

    let a = StructWithSomeFields { field_1: 1, field_2: 2, ..a };
This commit is contained in:
Mara Bos 2025-03-30 11:19:07 +02:00
parent 5cc60728e7
commit d035ca7db3
4 changed files with 59 additions and 13 deletions

View file

@ -1193,7 +1193,8 @@ impl<'a> State<'a> {
wth: hir::StructTailExpr<'_>,
) {
self.print_qpath(qpath, true);
self.word("{");
self.nbsp();
self.word_space("{");
self.commasep_cmnt(Consistent, fields, |s, field| s.print_expr_field(field), |f| f.span);
match wth {
hir::StructTailExpr::Base(expr) => {
@ -1215,20 +1216,13 @@ impl<'a> State<'a> {
self.word("..");
self.end();
}
hir::StructTailExpr::None => {
if !fields.is_empty() {
self.word(",");
hir::StructTailExpr::None => {}
}
}
}
self.space();
self.word("}");
}
fn print_expr_field(&mut self, field: &hir::ExprField<'_>) {
if self.attrs(field.hir_id).is_empty() {
self.space();
}
self.cbox(INDENT_UNIT);
self.print_attrs_as_outer(self.attrs(field.hir_id));
if !field.is_shorthand {

View file

@ -30,10 +30,10 @@ impl Foo<'_> {
// FIXME: impl Traits printed as just `/*impl Trait*/`, ugh
fn iter1<'a>(&self)
-> /*impl Trait*/ { #[lang = "Range"]{ start: 0, end: 1,} }
-> /*impl Trait*/ { #[lang = "Range"] { start: 0, end: 1 } }
fn iter2(&self)
-> /*impl Trait*/ { #[lang = "Range"]{ start: 0, end: 1,} }
-> /*impl Trait*/ { #[lang = "Range"] { start: 0, end: 1 } }
}
fn a(x: Foo<'_>) { }
@ -82,7 +82,7 @@ struct St<'a> {
x: &'a u32,
}
fn f() { { let _ = St{ x: &0,}; }; { let _ = St{ x: &0,}; }; }
fn f() { { let _ = St { x: &0 }; }; { let _ = St { x: &0 }; }; }
struct Name<'a>(&'a str);

View file

@ -0,0 +1,28 @@
#[prelude_import]
use ::std::prelude::rust_2015::*;
#[macro_use]
extern crate std;
//@ pretty-compare-only
//@ pretty-mode:hir
//@ pp-exact:hir-struct-expr.pp
struct StructWithSomeFields {
field_1: i32,
field_2: i32,
field_3: i32,
field_4: i32,
field_5: i32,
field_6: i32,
}
fn main() {
let a =
StructWithSomeFields {
field_1: 1,
field_2: 2,
field_3: 3,
field_4: 4,
field_5: 5,
field_6: 6 };
let a = StructWithSomeFields { field_1: 1, field_2: 2, ..a };
}

View file

@ -0,0 +1,24 @@
//@ pretty-compare-only
//@ pretty-mode:hir
//@ pp-exact:hir-struct-expr.pp
struct StructWithSomeFields {
field_1: i32,
field_2: i32,
field_3: i32,
field_4: i32,
field_5: i32,
field_6: i32,
}
fn main() {
let a = StructWithSomeFields {
field_1: 1,
field_2: 2,
field_3: 3,
field_4: 4,
field_5: 5,
field_6: 6,
};
let a = StructWithSomeFields { field_1: 1, field_2: 2, ..a };
}