Merge pull request #2136 from topecongiro/issue-2025

Remove empty lines at the beginning of the file
This commit is contained in:
Nick Cameron 2017-11-11 10:14:49 +13:00 committed by GitHub
commit 5496d87525
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 40 additions and 3 deletions

View file

@ -34,6 +34,7 @@ pub trait SpanUtils {
fn span_after(&self, original: Span, needle: &str) -> BytePos;
fn span_after_last(&self, original: Span, needle: &str) -> BytePos;
fn span_before(&self, original: Span, needle: &str) -> BytePos;
fn opt_span_after(&self, original: Span, needle: &str) -> Option<BytePos>;
}
pub trait LineRangeUtils {
@ -70,6 +71,13 @@ impl SpanUtils for CodeMap {
original.lo() + BytePos(offset as u32)
}
fn opt_span_after(&self, original: Span, needle: &str) -> Option<BytePos> {
let snippet = self.span_to_snippet(original).ok()?;
let offset = snippet.find_uncommented(needle)? + needle.len();
Some(original.lo() + BytePos(offset as u32))
}
}
impl LineRangeUtils for CodeMap {

View file

@ -321,6 +321,7 @@ where
let filemap = visitor.codemap.lookup_char_pos(module.inner.lo()).file;
// Format inner attributes if available.
if !krate.attrs.is_empty() && path == main_file {
visitor.skip_empty_lines(filemap.end_pos);
if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
visitor.push_rewrite(module.inner, None);
} else {
@ -328,6 +329,7 @@ where
}
} else {
visitor.last_pos = filemap.start_pos;
visitor.skip_empty_lines(filemap.end_pos);
visitor.format_separate_mod(module, &*filemap);
};

View file

@ -510,6 +510,10 @@ impl<'a> FmtVisitor<'a> {
}
}
pub fn opt_snippet(&self, span: Span) -> Option<String> {
self.codemap.span_to_snippet(span).ok()
}
pub fn snippet(&self, span: Span) -> String {
match self.codemap.span_to_snippet(span) {
Ok(s) => s,
@ -695,6 +699,20 @@ impl<'a> FmtVisitor<'a> {
self.format_missing_with_indent(filemap.end_pos);
}
pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
while let Some(pos) = self.codemap
.opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
{
if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
if snippet.trim().is_empty() {
self.last_pos = pos;
} else {
return;
}
}
}
}
pub fn get_context(&self) -> RewriteContext {
RewriteContext {
parse_session: self.parse_session,

View file

@ -0,0 +1,8 @@
// See if rustfmt removes empty lines on top of the file.
pub fn foo() {
println!("hello, world");
}

View file

@ -0,0 +1,4 @@
// See if rustfmt removes empty lines on top of the file.
pub fn foo() {
println!("hello, world");
}

View file

@ -1,4 +1,3 @@
fn main() {
loop {
return some_val;

View file

@ -1,4 +1,3 @@
mod mod2a;
mod mod2b;

View file

@ -1,3 +1,2 @@
#[path = "mod2a.rs"]
mod c;