Skip to content

Commit

Permalink
Keep comments between if and else blocks. Fixes #447
Browse files Browse the repository at this point in the history
  • Loading branch information
DarkDrek committed Jan 12, 2016
1 parent bdcc815 commit b0eb0f5
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/expr.rs
Expand Up @@ -664,7 +664,30 @@ fn rewrite_if_else(context: &RewriteContext,
_ => else_block.rewrite(context, width, offset),
};

result.push_str(" else ");
let snippet = context.codemap
.span_to_snippet(mk_sp(if_block.span.hi, else_block.span.lo))
.unwrap();
// Preserve comments that are between the if and else block
if contains_comment(&snippet) {
let close_pos = try_opt!(snippet.find_uncommented("else"));
let trimmed = &snippet[..close_pos].trim();
let comment_str = format!("{}{}",
offset.to_string(context.config),
try_opt!(rewrite_comment(trimmed,
false,
width,
offset,
context.config)),
);
let else_str = format!("{}else ", offset.to_string(context.config));

result.push('\n');
result.push_str(&comment_str);
result.push('\n');
result.push_str(&else_str);
} else {
result.push_str(" else ");
}
result.push_str(&&try_opt!(rewrite));
}

Expand Down
7 changes: 7 additions & 0 deletions tests/target/issue-447.rs
@@ -0,0 +1,7 @@
fn main() {
if cond {
}
// This shouldn't be dropped
else {
}
}

0 comments on commit b0eb0f5

Please sign in to comment.