Skip to content

Commit b7579f6

Browse files
committed
Merge pull request #75 from nrc/structs
Structs
2 parents c385688 + 46818d4 commit b7579f6

File tree

11 files changed

+288
-9
lines changed

11 files changed

+288
-9
lines changed

src/config.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,12 @@ pub struct Config {
1919
pub newline_style: ::NewlineStyle,
2020
pub fn_brace_style: ::BraceStyle,
2121
pub fn_return_indent: ::ReturnIndent,
22+
pub struct_trailing_comma: bool,
23+
pub struct_lit_trailing_comma: ::lists::SeparatorTactic,
2224
}
2325

2426
impl Config {
2527
fn from_toml(toml: &str) -> Config {
26-
println!("About to parse: {}", toml);
2728
let parsed = toml.parse().unwrap();
2829
toml::decode(parsed).unwrap()
2930
}

src/default.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,5 @@ tab_spaces = 4
55
newline_style = "Unix"
66
fn_brace_style = "SameLineWhere"
77
fn_return_indent = "WithArgs"
8+
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/functions.rs renamed to src/items.rs

Lines changed: 128 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11+
// Formatting top-level items - functions, structs, enums, traits, impls.
12+
1113
use {ReturnIndent, BraceStyle};
1214
use utils::make_indent;
1315
use lists::{write_list, ListFormatting, SeparatorTactic, ListTactic};
@@ -123,7 +125,7 @@ impl<'a> FmtVisitor<'a> {
123125
let generics_indent = indent + result.len();
124126
result.push_str(&self.rewrite_generics(generics,
125127
generics_indent,
126-
span_for_return(&fd.output)));
128+
span_for_return(&fd.output).lo));
127129

128130
let ret_str = self.rewrite_return(&fd.output);
129131

@@ -388,7 +390,130 @@ impl<'a> FmtVisitor<'a> {
388390
}
389391
}
390392

391-
fn rewrite_generics(&self, generics: &ast::Generics, indent: usize, ret_span: Span) -> String {
393+
pub fn visit_struct(&mut self,
394+
ident: ast::Ident,
395+
vis: ast::Visibility,
396+
struct_def: &ast::StructDef,
397+
generics: &ast::Generics,
398+
span: Span)
399+
{
400+
let header_str = self.struct_header(ident, vis);
401+
self.changes.push_str_span(span, &header_str);
402+
403+
if struct_def.fields.len() == 0 {
404+
assert!(generics.where_clause.predicates.len() == 0,
405+
"No-field struct with where clause?");
406+
assert!(generics.lifetimes.len() == 0, "No-field struct with generics?");
407+
assert!(generics.ty_params.len() == 0, "No-field struct with generics?");
408+
409+
self.changes.push_str_span(span, ";");
410+
return;
411+
}
412+
413+
let mut generics_buf = String::new();
414+
let generics_str = self.rewrite_generics(generics, self.block_indent, struct_def.fields[0].span.lo);
415+
generics_buf.push_str(&generics_str);
416+
417+
if generics.where_clause.predicates.len() > 0 {
418+
generics_buf.push_str(&self.rewrite_where_clause(&generics.where_clause,
419+
self.block_indent,
420+
struct_def.fields[0].span.lo));
421+
generics_buf.push_str(&make_indent(self.block_indent));
422+
generics_buf.push_str("\n{");
423+
424+
} else {
425+
generics_buf.push_str(" {");
426+
}
427+
self.changes.push_str_span(span, &generics_buf);
428+
429+
let struct_snippet = self.snippet(span);
430+
// FIXME this will give incorrect results if there is a { in a commet.
431+
self.last_pos = span.lo + BytePos(struct_snippet.find('{').unwrap() as u32 + 1);
432+
433+
self.block_indent += config!(tab_spaces);
434+
for (i, f) in struct_def.fields.iter().enumerate() {
435+
self.visit_field(f, i == struct_def.fields.len() - 1, span.lo, &struct_snippet);
436+
}
437+
self.block_indent -= config!(tab_spaces);
438+
439+
self.format_missing_with_indent(span.lo + BytePos(struct_snippet.rfind('}').unwrap() as u32));
440+
self.changes.push_str_span(span, "}");
441+
}
442+
443+
fn struct_header(&self,
444+
ident: ast::Ident,
445+
vis: ast::Visibility)
446+
-> String
447+
{
448+
let vis = if vis == ast::Visibility::Public {
449+
"pub "
450+
} else {
451+
""
452+
};
453+
454+
format!("{}struct {}", vis, &token::get_ident(ident))
455+
}
456+
457+
// Field of a struct
458+
fn visit_field(&mut self,
459+
field: &ast::StructField,
460+
last_field: bool,
461+
// These two args are for missing spans hacks.
462+
struct_start: BytePos,
463+
struct_snippet: &str)
464+
{
465+
if self.visit_attrs(&field.node.attrs) {
466+
return;
467+
}
468+
self.format_missing_with_indent(field.span.lo);
469+
470+
let name = match field.node.kind {
471+
ast::StructFieldKind::NamedField(ident, _) => Some(token::get_ident(ident)),
472+
ast::StructFieldKind::UnnamedField(_) => None,
473+
};
474+
let vis = match field.node.kind {
475+
ast::StructFieldKind::NamedField(_, vis) |
476+
ast::StructFieldKind::UnnamedField(vis) => if vis == ast::Visibility::Public {
477+
"pub "
478+
} else {
479+
""
480+
}
481+
};
482+
let typ = pprust::ty_to_string(&field.node.ty);
483+
484+
let mut field_str = match name {
485+
Some(name) => {
486+
let budget = config!(ideal_width) - self.block_indent;
487+
// 3 is being conservative and assuming that there will be a trailing comma.
488+
if self.block_indent + vis.len() + name.len() + typ.len() + 3 > budget {
489+
format!("{}{}:\n{}{}",
490+
vis,
491+
name,
492+
&make_indent(self.block_indent + config!(tab_spaces)),
493+
typ)
494+
} else {
495+
format!("{}{}: {}", vis, name, typ)
496+
}
497+
}
498+
None => format!("{}{}", vis, typ),
499+
};
500+
if !last_field || config!(struct_trailing_comma) {
501+
field_str.push(',');
502+
}
503+
self.changes.push_str_span(field.span, &field_str);
504+
505+
// This hack makes sure we only add comments etc. after the comma, and
506+
// makes sure we don't repeat any commas.
507+
let hi = field.span.hi;
508+
// FIXME a comma in a comment will break this hack.
509+
let comma_pos = match struct_snippet[(hi.0 - struct_start.0) as usize..].find(',') {
510+
Some(i) => i,
511+
None => 0,
512+
};
513+
self.last_pos = hi + BytePos(comma_pos as u32 + 1);
514+
}
515+
516+
fn rewrite_generics(&self, generics: &ast::Generics, indent: usize, span_end: BytePos) -> String {
392517
// FIXME convert bounds to where clauses where they get too big or if
393518
// there is a where clause at all.
394519
let mut result = String::new();
@@ -422,7 +547,7 @@ impl<'a> FmtVisitor<'a> {
422547
">",
423548
|sp| sp.lo,
424549
|sp| sp.hi,
425-
ret_span.lo);
550+
span_end);
426551

427552
// If there are // comments, keep them multi-line.
428553
let mut list_tactic = ListTactic::HorizontalVertical;

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ use visitor::FmtVisitor;
5050
mod config;
5151
mod changes;
5252
mod visitor;
53-
mod functions;
53+
mod items;
5454
mod missed_spans;
5555
mod lists;
5656
mod utils;

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,

src/visitor.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,15 @@ impl<'a, 'v> visit::Visitor<'v> for FmtVisitor<'a> {
180180
self.changes.push_str_span(item.span, &new_str);
181181
self.last_pos = item.span.hi;
182182
}
183+
ast::Item_::ItemStruct(ref def, ref generics) => {
184+
self.format_missing_with_indent(item.span.lo);
185+
self.visit_struct(item.ident,
186+
item.vis,
187+
def,
188+
generics,
189+
item.span);
190+
self.last_pos = item.span.hi;
191+
}
183192
_ => {
184193
visit::walk_item(self, item);
185194
}
@@ -252,7 +261,7 @@ impl<'a> FmtVisitor<'a> {
252261
}
253262

254263
// Returns true if we should skip the following item.
255-
fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
264+
pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
256265
if attrs.len() == 0 {
257266
return false;
258267
}

tests/idem.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ fn idempotent_tests() {
5757

5858
// Compare output to input.
5959
fn print_mismatches(result: HashMap<String, String>) {
60-
for (file_name, fmt_text) in result {
60+
for (_, fmt_text) in result {
6161
println!("{}", fmt_text);
6262
}
6363
}

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)