Empty structs and struct lits (#920)

* Handle empty struct lits

Closes #835

* Don't crash on empty struct defs.

Not a great fix, but better than crashing.
This commit is contained in:
Nick Cameron 2016-04-12 07:05:54 +12:00 committed by Marcus Klaas de Vries
parent 7ac354fd09
commit 492b26cf04
6 changed files with 35 additions and 4 deletions

View File

@ -1390,7 +1390,6 @@ fn rewrite_struct_lit<'a>(context: &RewriteContext,
offset: Indent)
-> Option<String> {
debug!("rewrite_struct_lit: width {}, offset {:?}", width, offset);
assert!(!fields.is_empty() || base.is_some());
enum StructLitField<'a> {
Regular(&'a ast::Field),
@ -1502,6 +1501,10 @@ fn rewrite_struct_lit<'a>(context: &RewriteContext,
};
let fields_str = try_opt!(write_list(&item_vec, &fmt));
if fields_str.is_empty() {
return Some(format!("{} {{}}", path_str));
}
let format_on_newline = || {
let inner_indent = context.block_indent
.block_indent(context.config)

View File

@ -786,7 +786,7 @@ fn format_struct_struct(context: &RewriteContext,
};
result.push_str(&generics_str);
// FIXME: properly format empty structs and their comments.
// FIXME(#919): properly format empty structs and their comments.
if fields.is_empty() {
result.push_str(&context.snippet(mk_sp(body_lo, span.hi)));
return Some(result);
@ -838,13 +838,17 @@ fn format_tuple_struct(context: &RewriteContext,
span: Span,
offset: Indent)
-> Option<String> {
assert!(!fields.is_empty(), "Tuple struct with no fields?");
let mut result = String::with_capacity(1024);
let header_str = format_header(item_name, ident, vis);
result.push_str(&header_str);
let body_lo = fields[0].span.lo;
// FIXME(#919): don't lose comments on empty tuple structs.
let body_lo = if fields.is_empty() {
span.hi
} else {
fields[0].span.lo
};
let where_clause_str = match generics {
Some(ref generics) => {

View File

@ -123,3 +123,12 @@ fn issue698() {
ffffffffffffffffffffffffffields: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
}
}
fn issue835() {
MyStruct {};
MyStruct { /* a comment */ };
MyStruct {
// Another comment
};
MyStruct {}
}

View File

@ -151,3 +151,6 @@ struct Issue677 {
pub trace: fn( obj:
*const libc::c_void, tracer : *mut JSTracer ),
}
struct Foo {}
struct Foo();

View File

@ -159,3 +159,12 @@ fn issue698() {
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
}
}
fn issue835() {
MyStruct {};
MyStruct { /* a comment */ };
MyStruct {
// Another comment
};
MyStruct {}
}

View File

@ -158,3 +158,6 @@ struct Issue677 {
pub ptr: *const libc::c_void,
pub trace: fn(obj: *const libc::c_void, tracer: *mut JSTracer),
}
struct Foo {}
struct Foo();