diff --git a/src/config.rs b/src/config.rs index 080926b03a2..6b3e8916e3b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -19,6 +19,7 @@ pub struct Config { pub newline_style: ::NewlineStyle, pub fn_brace_style: ::BraceStyle, pub fn_return_indent: ::ReturnIndent, + pub struct_trailing_comma: bool, } impl Config { diff --git a/src/default.toml b/src/default.toml index 218f2a04fb2..3d063398893 100644 --- a/src/default.toml +++ b/src/default.toml @@ -5,3 +5,4 @@ tab_spaces = 4 newline_style = "Unix" fn_brace_style = "SameLineWhere" fn_return_indent = "WithArgs" +struct_trailing_comma = true diff --git a/src/items.rs b/src/items.rs index a2027d89b88..55613ab1bb8 100644 --- a/src/items.rs +++ b/src/items.rs @@ -431,8 +431,8 @@ pub fn visit_struct(&mut self, self.last_pos = span.lo + BytePos(struct_snippet.find('{').unwrap() as u32 + 1); self.block_indent += config!(tab_spaces); - for f in &struct_def.fields { - self.visit_field(f, span.lo, &struct_snippet); + for (i, f) in struct_def.fields.iter().enumerate() { + self.visit_field(f, i == struct_def.fields.len() - 1, span.lo, &struct_snippet); } self.block_indent -= config!(tab_spaces); @@ -457,6 +457,7 @@ fn struct_header(&self, // Field of a struct fn visit_field(&mut self, field: &ast::StructField, + last_field: bool, // These two args are for missing spans hacks. struct_start: BytePos, struct_snippet: &str) @@ -480,21 +481,25 @@ fn visit_field(&mut self, }; let typ = pprust::ty_to_string(&field.node.ty); - let field_str = match name { + let mut field_str = match name { Some(name) => { let budget = config!(ideal_width) - self.block_indent; + // 3 is being conservative and assuming that there will be a trailing comma. if self.block_indent + vis.len() + name.len() + typ.len() + 3 > budget { - format!("{}{}:\n{}{},", + format!("{}{}:\n{}{}", vis, name, &make_indent(self.block_indent + config!(tab_spaces)), typ) } else { - format!("{}{}: {},", vis, name, typ) + format!("{}{}: {}", vis, name, typ) } } - None => format!("{}{},", vis, typ), + None => format!("{}{}", vis, typ), }; + if !last_field || config!(struct_trailing_comma) { + field_str.push(','); + } self.changes.push_str_span(field.span, &field_str); // This hack makes sure we only add comments etc. after the comma, and