Skip to content

Remove blank lines at start or end of block #1872

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 14, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion src/bin/cargo-fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,6 @@ fn get_targets(workspace_hitlist: WorkspaceHitlist) -> Result<Vec<Target>, std::
std::io::ErrorKind::NotFound,
str::from_utf8(&output.stderr).unwrap(),
))

}

fn target_from_json(jtarget: &Value) -> Target {
Expand Down
1 change: 0 additions & 1 deletion src/bin/rustfmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ fn match_cli_path_or_file(
config_path: Option<PathBuf>,
input_file: &Path,
) -> FmtResult<(Config, Option<PathBuf>)> {

if let Some(config_file) = config_path {
let toml = Config::from_toml_path(config_file.as_ref())?;
return Ok((toml, Some(config_file)));
Expand Down
4 changes: 3 additions & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -606,7 +606,9 @@ create_config! {
tuple patterns";
combine_control_expr: bool, true, "Combine control expressions with funciton calls.";
struct_field_align_threshold: usize, 0, "Align struct fields if their diffs fits within \
threshold."
threshold.";
remove_blank_lines_at_start_or_end_of_block: bool, true,
"Remove blank lines at start or end of a block";
}

#[cfg(test)]
Expand Down
1 change: 0 additions & 1 deletion src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2985,7 +2985,6 @@ fn choose_rhs(
}

fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {

fn count_line_breaks(src: &str) -> usize {
src.chars().filter(|&x| x == '\n').count()
}
Expand Down
1 change: 0 additions & 1 deletion src/filemap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,6 @@ pub fn write_file<T>(
where
T: Write,
{

fn source_and_formatted_text(
text: &StringBuffer,
filename: &str,
Expand Down
2 changes: 0 additions & 2 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,6 @@ where
} else {
Some(format!("{}{}", args, output))
}

}

fn type_bound_colon(context: &RewriteContext) -> &'static str {
Expand Down Expand Up @@ -601,7 +600,6 @@ impl Rewrite for ast::TyParam {
result.push_str(&join_bounds(context, shape, &strs));
}
if let Some(ref def) = self.default {

let eq_str = match context.config.type_punctuation_density() {
TypeDensity::Compressed => "=",
TypeDensity::Wide => " = ",
Expand Down
73 changes: 69 additions & 4 deletions src/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@ use std::cmp;

use strings::string_buffer::StringBuffer;
use syntax::{ast, ptr, visit};
use syntax::codemap::{self, BytePos, CodeMap, Span};
use syntax::attr::HasAttrs;
use syntax::codemap::{self, BytePos, CodeMap, Pos, Span};
use syntax::parse::ParseSess;

use {Indent, Shape, Spanned};
use codemap::{LineRangeUtils, SpanUtils};
use comment::{contains_comment, FindUncommented};
use comment::{contains_comment, CodeCharKind, CommentCodeSlices, FindUncommented};
use comment::rewrite_comment;
use config::{BraceStyle, Config};
use expr::{format_expr, ExprType};
Expand Down Expand Up @@ -131,6 +132,48 @@ impl<'a> FmtVisitor<'a> {
self.block_indent = self.block_indent.block_indent(self.config);
self.buffer.push_str("{");

if self.config.remove_blank_lines_at_start_or_end_of_block() {
if let Some(first_stmt) = b.stmts.first() {
let attr_lo = inner_attrs
.and_then(|attrs| {
utils::inner_attributes(attrs)
.first()
.map(|attr| attr.span.lo)
})
.or_else(|| {
// Attributes for an item in a statement position
// do not belong to the statement. (rust-lang/rust#34459)
if let ast::StmtKind::Item(ref item) = first_stmt.node {
item.attrs.first()
} else {
first_stmt.attrs().first()
}.and_then(|attr| {
// Some stmts can have embedded attributes.
// e.g. `match { #![attr] ... }`
let attr_lo = attr.span.lo;
if attr_lo < first_stmt.span.lo {
Some(attr_lo)
} else {
None
}
})
});

let snippet =
self.snippet(mk_sp(self.last_pos, attr_lo.unwrap_or(first_stmt.span.lo)));
let len = CommentCodeSlices::new(&snippet).nth(0).and_then(
|(kind, _, s)| if kind == CodeCharKind::Normal {
s.rfind('\n')
} else {
None
},
);
if let Some(len) = len {
self.last_pos = self.last_pos + BytePos::from_usize(len);
}
}
}

// Format inner attributes if available.
if let Some(attrs) = inner_attrs {
self.visit_attrs(attrs, ast::AttrStyle::Inner);
Expand All @@ -148,17 +191,39 @@ impl<'a> FmtVisitor<'a> {
}
}

let mut remove_len = BytePos(0);
if self.config.remove_blank_lines_at_start_or_end_of_block() {
if let Some(stmt) = b.stmts.last() {
let snippet = self.snippet(mk_sp(
stmt.span.hi,
source!(self, b.span).hi - brace_compensation,
));
let len = CommentCodeSlices::new(&snippet)
.last()
.and_then(|(kind, _, s)| {
if kind == CodeCharKind::Normal && s.trim().is_empty() {
Some(s.len())
} else {
None
}
});
if let Some(len) = len {
remove_len = BytePos::from_usize(len);
}
}
}

let mut unindent_comment = self.is_if_else_block && !b.stmts.is_empty();
if unindent_comment {
let end_pos = source!(self, b.span).hi - brace_compensation;
let end_pos = source!(self, b.span).hi - brace_compensation - remove_len;
let snippet = self.get_context().snippet(mk_sp(self.last_pos, end_pos));
unindent_comment = snippet.contains("//") || snippet.contains("/*");
}
// FIXME: we should compress any newlines here to just one
if unindent_comment {
self.block_indent = self.block_indent.block_unindent(self.config);
}
self.format_missing_with_indent(source!(self, b.span).hi - brace_compensation);
self.format_missing_with_indent(source!(self, b.span).hi - brace_compensation - remove_len);
if unindent_comment {
self.block_indent = self.block_indent.block_indent(self.config);
}
Expand Down
1 change: 0 additions & 1 deletion tests/source/fn-simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,5 +51,4 @@ pub fn waltz(cwd: &Path) -> CliAssert {
formatted_comment = rewrite_comment(comment, block_style, width, offset, formatting_fig);
}
}

}
1 change: 0 additions & 1 deletion tests/source/indent_match_arms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,4 @@ fn main() {
},
_ => "something else",
}

}
1 change: 0 additions & 1 deletion tests/source/issue-510.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ fn solve_inline_size_constraints(&self,
block: &mut BlockFlow,
input: &ISizeConstraintInput)
-> ISizeConstraintSolution {

let (inline_start,inline_size,margin_inline_start,margin_inline_end) =
match (inline_startssssssxxxxxxsssssxxxxxxxxxssssssxxx,inline_startssssssxxxxxxsssssxxxxxxxxxssssssxxx) {
(MaybeAuto::Auto, MaybeAuto::Auto, MaybeAuto::Auto) => {
Expand Down
22 changes: 22 additions & 0 deletions tests/source/remove_blank_lines.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
fn main() {




let x = 1;




}

fn foo() {

#![attribute]

let x = 1;

// comment


}
1 change: 0 additions & 1 deletion tests/source/spaces-within-angle-brackets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ fn foo<T, E>(a: T, b: E) {
}

fn foo<T: Send, E: Send>(a: T, b: E) {

foo::<u32, str>(10, "bar");

let opt: Option<u32>;
Expand Down
1 change: 0 additions & 1 deletion tests/source/spaces-within-parens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ struct TupleStruct2(u32, u32);
fn fooEmpty() {}

fn foo(e: E, _: u32) -> (u32, u32) {

// Tuples
let t1 = ();
let t2 = (1,);
Expand Down
1 change: 0 additions & 1 deletion tests/source/spaces-within-square-brackets.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// rustfmt-spaces_within_square_brackets: true

fn main() {

let arr: [i32; 5] = [1, 2, 3, 4, 5];
let arr: [i32; 500] = [0; 500];

Expand Down
2 changes: 0 additions & 2 deletions tests/source/struct_tuple_visual.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
// rustfmt-error_on_line_overflow: false
// rustfmt-struct_lit_style: Visual
fn foo() {

Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(f(), b());

Foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(// Comment
Expand Down Expand Up @@ -35,5 +34,4 @@ fn foo() {
// /|\ \
// o o o o
G)

}
1 change: 0 additions & 1 deletion tests/target/fn-simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,5 +96,4 @@ pub fn waltz(cwd: &Path) -> CliAssert {
rewrite_comment(comment, block_style, width, offset, formatting_fig);
}
}

}
1 change: 0 additions & 1 deletion tests/target/indent_match_arms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,4 @@ fn main() {
},
_ => "something else",
}

}
1 change: 0 additions & 1 deletion tests/target/issue-510.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ impl ISizeAndMarginsComputer for AbsoluteNonReplaced {
block: &mut BlockFlow,
input: &ISizeConstraintInput,
) -> ISizeConstraintSolution {

let (inline_start, inline_size, margin_inline_start, margin_inline_end) = match (
inline_startssssssxxxxxxsssssxxxxxxxxxssssssxxx,
inline_startssssssxxxxxxsssssxxxxxxxxxssssssxxx,
Expand Down
11 changes: 11 additions & 0 deletions tests/target/remove_blank_lines.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
fn main() {
let x = 1;
}

fn foo() {
#![attribute]

let x = 1;

// comment
}
1 change: 0 additions & 1 deletion tests/target/spaces-within-angle-brackets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ fn foo< T, E >(a: T, b: E) {
}

fn foo< T: Send, E: Send >(a: T, b: E) {

foo::< u32, str >(10, "bar");

let opt: Option< u32 >;
Expand Down
1 change: 0 additions & 1 deletion tests/target/spaces-within-parens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ struct TupleStruct2( u32, u32 );
fn fooEmpty() {}

fn foo( e: E, _: u32 ) -> ( u32, u32 ) {

// Tuples
let t1 = ();
let t2 = ( 1, );
Expand Down
1 change: 0 additions & 1 deletion tests/target/spaces-within-square-brackets.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// rustfmt-spaces_within_square_brackets: true

fn main() {

let arr: [ i32; 5 ] = [ 1, 2, 3, 4, 5 ];
let arr: [ i32; 500 ] = [ 0; 500 ];

Expand Down
2 changes: 0 additions & 2 deletions tests/target/struct_tuple_visual.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
// rustfmt-error_on_line_overflow: false
// rustfmt-struct_lit_style: Visual
fn foo() {

Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(f(), b());

Foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(
Expand Down Expand Up @@ -45,5 +44,4 @@ fn foo() {
// o o o o
G,
)

}