Skip to content

Commit 46818d4

Browse files
committed
Struct literals
1 parent 972f494 commit 46818d4

File tree

7 files changed

+111
-4
lines changed

7 files changed

+111
-4
lines changed

src/bin/rustfmt.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ fn main() {
2424
let mut def_config = String::new();
2525
def_config_file.read_to_string(&mut def_config).unwrap();
2626

27-
run(args, WriteMode::Display, &def_config);
28-
//run(args, WriteMode::Overwrite, &def_config);
27+
//run(args, WriteMode::Display, &def_config);
28+
run(args, WriteMode::Overwrite, &def_config);
2929

3030
std::env::set_exit_status(0);
3131

src/config.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ pub struct Config {
2020
pub fn_brace_style: ::BraceStyle,
2121
pub fn_return_indent: ::ReturnIndent,
2222
pub struct_trailing_comma: bool,
23+
pub struct_lit_trailing_comma: ::lists::SeparatorTactic,
2324
}
2425

2526
impl Config {

src/default.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ newline_style = "Unix"
66
fn_brace_style = "SameLineWhere"
77
fn_return_indent = "WithArgs"
88
struct_trailing_comma = true
9+
struct_lit_trailing_comma = "Vertical"

src/expr.rs

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ use utils::*;
1313
use lists::{write_list, ListFormatting, SeparatorTactic, ListTactic};
1414

1515
use syntax::{ast, ptr};
16-
use syntax::codemap::{Span, Pos};
16+
use syntax::codemap::{Pos, Span};
17+
use syntax::parse::token;
18+
use syntax::print::pprust;
1719

1820
use MIN_STRING;
1921

@@ -134,6 +136,64 @@ impl<'a> FmtVisitor<'a> {
134136
format!("({})", subexpr_str)
135137
}
136138

139+
fn rewrite_struct_lit(&mut self,
140+
path: &ast::Path,
141+
fields: &[ast::Field],
142+
base: Option<&ast::Expr>,
143+
width: usize,
144+
offset: usize)
145+
-> String
146+
{
147+
debug!("rewrite_struct_lit: width {}, offset {}", width, offset);
148+
assert!(fields.len() > 0 || base.is_some());
149+
150+
let path_str = pprust::path_to_string(path);
151+
// Foo { a: Foo } - indent is +3, width is -5.
152+
let indent = offset + path_str.len() + 3;
153+
let budget = width - (path_str.len() + 5);
154+
155+
let mut field_strs: Vec<_> =
156+
fields.iter().map(|f| self.rewrite_field(f, budget, indent)).collect();
157+
if let Some(expr) = base {
158+
// Another 2 on the width/indent for the ..
159+
field_strs.push(format!("..{}", self.rewrite_expr(expr, budget - 2, indent + 2)))
160+
}
161+
162+
// FIXME comments
163+
let field_strs: Vec<_> = field_strs.into_iter().map(|s| (s, String::new())).collect();
164+
let tactics = if field_strs.iter().any(|&(ref s, _)| s.contains('\n')) {
165+
ListTactic::Vertical
166+
} else {
167+
ListTactic::HorizontalVertical
168+
};
169+
let fmt = ListFormatting {
170+
tactic: tactics,
171+
separator: ",",
172+
trailing_separator: if base.is_some() {
173+
SeparatorTactic::Never
174+
} else {
175+
config!(struct_lit_trailing_comma)
176+
},
177+
indent: indent,
178+
h_width: budget,
179+
v_width: budget,
180+
};
181+
let fields_str = write_list(&field_strs, &fmt);
182+
format!("{} {{ {} }}", path_str, fields_str)
183+
184+
// FIXME if the usual multi-line layout is too wide, we should fall back to
185+
// Foo {
186+
// a: ...,
187+
// }
188+
}
189+
190+
fn rewrite_field(&mut self, field: &ast::Field, width: usize, offset: usize) -> String {
191+
let name = &token::get_ident(field.ident.node);
192+
let overhead = name.len() + 2;
193+
let expr = self.rewrite_expr(&field.expr, width - overhead, offset + overhead);
194+
format!("{}: {}", name, expr)
195+
}
196+
137197
pub fn rewrite_expr(&mut self, expr: &ast::Expr, width: usize, offset: usize) -> String {
138198
match expr.node {
139199
ast::Expr_::ExprLit(ref l) => {
@@ -152,6 +212,13 @@ impl<'a> FmtVisitor<'a> {
152212
ast::Expr_::ExprParen(ref subexpr) => {
153213
return self.rewrite_paren(subexpr, width, offset);
154214
}
215+
ast::Expr_::ExprStruct(ref path, ref fields, ref base) => {
216+
return self.rewrite_struct_lit(path,
217+
fields,
218+
base.as_ref().map(|e| &**e),
219+
width,
220+
offset);
221+
}
155222
_ => {}
156223
}
157224

src/imports.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ impl<'a> FmtVisitor<'a> {
4747
path: &ast::Path,
4848
path_list: &[ast::PathListItem],
4949
visibility: ast::Visibility) -> String {
50-
let path_str = pprust::path_to_string(&path);
50+
let path_str = pprust::path_to_string(path);
5151

5252
let vis = match visibility {
5353
ast::Public => "pub ",

src/lists.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
// except according to those terms.
1010

1111
use utils::make_indent;
12+
use rustc_serialize::{Decodable, Decoder};
1213

1314
#[derive(Eq, PartialEq, Debug, Copy, Clone)]
1415
pub enum ListTactic {
@@ -29,6 +30,19 @@ pub enum SeparatorTactic {
2930
Vertical,
3031
}
3132

33+
// TODO could use a macro for all these Decodable impls.
34+
impl Decodable for SeparatorTactic {
35+
fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
36+
let s = try!(d.read_str());
37+
match &*s {
38+
"Always" => Ok(SeparatorTactic::Always),
39+
"Never" => Ok(SeparatorTactic::Never),
40+
"Vertical" => Ok(SeparatorTactic::Vertical),
41+
_ => Err(d.error("Bad variant")),
42+
}
43+
}
44+
}
45+
3246
// TODO having some helpful ctors for ListFormatting would be nice.
3347
pub struct ListFormatting<'a> {
3448
pub tactic: ListTactic,

tests/idem/struct_lits.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Struct literal expressions.
2+
3+
fn main() {
4+
let x = Bar;
5+
6+
// Comment
7+
let y = Foo { a: x };
8+
9+
Foo { a: Bar, b: foo() };
10+
11+
Foo { a: foo(), b: bar(), ..something };
12+
13+
Foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo { a: foo(), b: bar() };
14+
Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo { a: foo(),
15+
b: bar(), };
16+
17+
Fooooooooooooooooooooooooooooooooooooooooooooooooooooo { a: foo(),
18+
b: bar(),
19+
c: bar(),
20+
d: bar(),
21+
e: bar(),
22+
f: bar(),
23+
..baz() };
24+
}

0 commit comments

Comments
 (0)