Merge pull request #2221 from topecongiro/rfc/blank-lines

Keep vertical spaces between items or statements within range
This commit is contained in:
Nick Cameron 2017-12-06 15:52:19 +13:00 committed by GitHub
commit b07e4339f0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 269 additions and 165 deletions

View File

@ -14,7 +14,6 @@
use std::path::PathBuf;
use std::process::Command;
fn main() {
let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());

View File

@ -14,7 +14,6 @@
use rustfmt::{run, Input};
use rustfmt::config;
fn prune_files(files: Vec<&str>) -> Vec<&str> {
let prefixes: Vec<_> = files
.iter()

View File

@ -10,7 +10,6 @@
#![cfg(not(test))]
extern crate env_logger;
extern crate getopts;
extern crate rustfmt_nightly as rustfmt;

View File

@ -31,7 +31,6 @@
// statement without needing a semi-colon), then adding or removing braces
// can change whether it is treated as an expression or statement.
pub fn rewrite_closure(
capture: ast::CaptureBy,
fn_decl: &ast::FnDecl,

View File

@ -18,7 +18,7 @@
use rewrite::RewriteContext;
use shape::{Indent, Shape};
use string::{rewrite_string, StringFormat};
use utils::{first_line_width, last_line_width};
use utils::{count_newlines, first_line_width, last_line_width};
fn is_custom_comment(comment: &str) -> bool {
if !comment.starts_with("//") {
@ -292,7 +292,7 @@ fn rewrite_comment_inner(
config: config,
};
let line_breaks = orig.trim_right().chars().filter(|&c| c == '\n').count();
let line_breaks = count_newlines(orig.trim_right());
let lines = orig.lines()
.enumerate()
.map(|(i, mut line)| {
@ -829,9 +829,6 @@ fn next(&mut self) -> Option<Self::Item> {
}
}
/// Iterator over an alternating sequence of functional and commented parts of
/// a string. The first item is always a, possibly zero length, subslice of
/// functional text. Line style comments contain their ending newlines.
@ -953,7 +950,6 @@ fn changed_comment_content(orig: &str, new: &str) -> bool {
res
}
/// Iterator over the 'payload' characters of a comment.
/// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
/// The comment must be one comment, ie not more than one start mark (no multiple line comments,
@ -999,7 +995,6 @@ fn next(&mut self) -> Option<Self::Item> {
}
}
fn remove_comment_header(comment: &str) -> &str {
if comment.starts_with("///") || comment.starts_with("//!") {
&comment[3..]

View File

@ -21,7 +21,6 @@
use lists::{ListTactic, SeparatorPlace, SeparatorTactic};
use Summary;
macro_rules! is_nightly_channel {
() => {
option_env!("CFG_RELEASE_CHANNEL")
@ -88,7 +87,6 @@ pub enum $e {
Wide,
}
impl Density {
pub fn to_list_tactic(self) -> ListTactic {
match self {
@ -579,8 +577,6 @@ pub fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
Ok(None)
}
create_config! {
// Fundamental stuff
max_width: usize, 100, true, "Maximum width of each line";
@ -651,6 +647,10 @@ pub fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
"Add trailing semicolon after break, continue and return";
match_block_trailing_comma: bool, false, false,
"Put a trailing comma after a block based match arm (non-block arms are not affected)";
blank_lines_upper_bound: usize, 1, false,
"Maximum number of blank lines which can be put between items.";
blank_lines_lower_bound: usize, 0, false,
"Minimum number of blank lines which must be put between items.";
// Options that can change the source code beyond whitespace/blocks (somewhat linty things)
merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one";

View File

@ -2807,12 +2807,8 @@ pub fn choose_rhs<R: Rewrite>(
}
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()
}
!next_line_rhs.contains('\n')
|| count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
use utils::count_newlines;
!next_line_rhs.contains('\n') || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
}
fn rewrite_expr_addrof(

View File

@ -8,7 +8,6 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// TODO: add tests
use std::fs::{self, File};

View File

@ -13,7 +13,6 @@
use syntax::ast;
use syntax::codemap::{BytePos, Span};
use spanned::Spanned;
use codemap::SpanUtils;
use comment::combine_strs_with_missing_comments;

View File

@ -283,7 +283,6 @@ pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
self.format_item(item);
}
fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
let rewrite = item.rewrite(&self.get_context(), self.shape());
self.push_rewrite(item.span(), rewrite);

View File

@ -17,7 +17,7 @@
use config::{Config, IndentStyle};
use rewrite::RewriteContext;
use shape::{Indent, Shape};
use utils::{first_line_width, last_line_width, mk_sp, starts_with_newline};
use utils::{count_newlines, first_line_width, last_line_width, mk_sp, starts_with_newline};
/// Formatting tactic for lists. This will be cast down to a
/// `DefinitiveListTactic` depending on the number and length of the items and
@ -677,7 +677,7 @@ fn next(&mut self) -> Option<Self::Item> {
// From the end of the first line of comments to the next non-whitespace char.
let test_snippet = &test_snippet[..first];
if test_snippet.chars().filter(|c| c == &'\n').count() > 1 {
if count_newlines(test_snippet) > 1 {
// There were multiple line breaks which got trimmed to nothing.
new_lines = true;
}

View File

@ -9,13 +9,15 @@
// except according to those terms.
use std::borrow::Cow;
use std::iter::repeat;
use syntax::codemap::{BytePos, Pos, Span};
use codemap::LineRangeUtils;
use comment::{rewrite_comment, CodeCharKind, CommentCodeSlices};
use config::WriteMode;
use shape::{Indent, Shape};
use utils::mk_sp;
use utils::{count_newlines, mk_sp};
use visitor::FmtVisitor;
impl<'a> FmtVisitor<'a> {
@ -74,8 +76,28 @@ fn format_missing_inner<F: Fn(&mut FmtVisitor, &str, &str)>(
self.last_pos = end;
let span = mk_sp(start, end);
let snippet = self.snippet(span);
if snippet.trim().is_empty() && !out_of_file_lines_range!(self, span) {
// Keep vertical spaces within range.
self.push_vertical_spaces(count_newlines(&snippet));
process_last_snippet(self, "", &snippet);
} else {
self.write_snippet(span, &process_last_snippet);
}
}
self.write_snippet(span, &process_last_snippet);
fn push_vertical_spaces(&mut self, mut newline_count: usize) {
// The buffer already has a trailing newline.
let offset = if self.buffer.cur_offset() == 0 { 0 } else { 1 };
let newline_upper_bound = self.config.blank_lines_upper_bound() + offset;
let newline_lower_bound = self.config.blank_lines_lower_bound() + offset;
if newline_count > newline_upper_bound {
newline_count = newline_upper_bound;
} else if newline_count < newline_lower_bound {
newline_count = newline_lower_bound;
}
let blank_lines: String = repeat('\n').take(newline_count).collect();
self.buffer.push_str(&blank_lines);
}
fn write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
@ -100,6 +122,85 @@ fn write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
self.write_snippet_inner(big_snippet, big_diff, &snippet, span, process_last_snippet);
}
fn process_comment(
&mut self,
status: &mut SnippetStatus,
snippet: &str,
big_snippet: &str,
offset: usize,
big_diff: usize,
subslice: &str,
file_name: &str,
) -> bool {
let last_char = big_snippet[..(offset + big_diff)]
.chars()
.rev()
.skip_while(|rev_c| [' ', '\t'].contains(rev_c))
.next();
let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
let subslice_num_lines = count_newlines(subslice);
let skip_this_range = !self.config.file_lines().intersects_range(
file_name,
status.cur_line,
status.cur_line + subslice_num_lines,
);
if status.rewrite_next_comment && skip_this_range {
status.rewrite_next_comment = false;
}
if status.rewrite_next_comment {
if fix_indent {
if let Some('{') = last_char {
self.buffer.push_str("\n");
}
self.buffer
.push_str(&self.block_indent.to_string(self.config));
} else {
self.buffer.push_str(" ");
}
let comment_width = ::std::cmp::min(
self.config.comment_width(),
self.config.max_width() - self.block_indent.width(),
);
let comment_indent = Indent::from_width(self.config, self.buffer.cur_offset());
let comment_shape = Shape::legacy(comment_width, comment_indent);
let comment_str = rewrite_comment(subslice, false, comment_shape, self.config)
.unwrap_or_else(|| String::from(subslice));
self.buffer.push_str(&comment_str);
status.last_wspace = None;
status.line_start = offset + subslice.len();
if let Some('/') = subslice.chars().nth(1) {
// check that there are no contained block comments
if !subslice
.split('\n')
.map(|s| s.trim_left())
.any(|s| s.len() >= 2 && &s[0..2] == "/*")
{
// Add a newline after line comments
self.buffer.push_str("\n");
}
} else if status.line_start <= snippet.len() {
// For other comments add a newline if there isn't one at the end already
match snippet[status.line_start..].chars().next() {
Some('\n') | Some('\r') => (),
_ => self.buffer.push_str("\n"),
}
}
status.cur_line += subslice_num_lines;
true
} else {
status.rewrite_next_comment = false;
false
}
}
fn write_snippet_inner<F>(
&mut self,
big_snippet: &str,
@ -113,13 +214,9 @@ fn write_snippet_inner<F>(
// Trim whitespace from the right hand side of each line.
// Annoyingly, the library functions for splitting by lines etc. are not
// quite right, so we must do it ourselves.
let mut line_start = 0;
let mut last_wspace = None;
let mut rewrite_next_comment = true;
let char_pos = self.codemap.lookup_char_pos(span.lo());
let file_name = &char_pos.file.name;
let mut cur_line = char_pos.line;
let mut status = SnippetStatus::new(char_pos.line);
fn replace_chars<'a>(string: &'a str) -> Cow<'a, str> {
if string.contains(char::is_whitespace) {
@ -143,121 +240,97 @@ fn replace_chars<'a>(string: &'a str) -> Cow<'a, str> {
debug!("{:?}: {:?}", kind, subslice);
if let CodeCharKind::Comment = kind {
let last_char = big_snippet[..(offset + big_diff)]
.chars()
.rev()
.skip_while(|rev_c| [' ', '\t'].contains(rev_c))
.next();
let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
let subslice_num_lines = subslice.chars().filter(|c| *c == '\n').count();
if rewrite_next_comment
&& !self.config.file_lines().intersects_range(
file_name,
cur_line,
cur_line + subslice_num_lines,
) {
rewrite_next_comment = false;
}
if rewrite_next_comment {
if fix_indent {
if let Some('{') = last_char {
self.buffer.push_str("\n");
}
self.buffer
.push_str(&self.block_indent.to_string(self.config));
} else {
self.buffer.push_str(" ");
}
let comment_width = ::std::cmp::min(
self.config.comment_width(),
self.config.max_width() - self.block_indent.width(),
);
let comment_indent = Indent::from_width(self.config, self.buffer.cur_offset());
self.buffer.push_str(&rewrite_comment(
subslice,
false,
Shape::legacy(comment_width, comment_indent),
self.config,
).unwrap());
last_wspace = None;
line_start = offset + subslice.len();
if let Some('/') = subslice.chars().nth(1) {
// check that there are no contained block comments
if !subslice
.split('\n')
.map(|s| s.trim_left())
.any(|s| s.len() >= 2 && &s[0..2] == "/*")
{
// Add a newline after line comments
self.buffer.push_str("\n");
}
} else if line_start <= snippet.len() {
// For other comments add a newline if there isn't one at the end already
match snippet[line_start..].chars().next() {
Some('\n') | Some('\r') => (),
_ => self.buffer.push_str("\n"),
}
}
cur_line += subslice_num_lines;
if self.process_comment(
&mut status,
snippet,
big_snippet,
offset,
big_diff,
subslice,
file_name,
) {
continue;
} else {
rewrite_next_comment = false;
}
}
for (mut i, c) in subslice.char_indices() {
i += offset;
let newline_count = count_newlines(&subslice);
if subslice.trim().is_empty() && newline_count > 0
&& self.config.file_lines().intersects_range(
file_name,
status.cur_line,
status.cur_line + newline_count,
) {
self.push_vertical_spaces(newline_count);
status.cur_line += newline_count;
status.rewrite_next_comment = true;
status.line_start = offset + newline_count;
} else {
for (mut i, c) in subslice.char_indices() {
i += offset;
if c == '\n' {
if !self.config.file_lines().contains_line(file_name, cur_line) {
last_wspace = None;
}
if c == '\n' {
if !self.config
.file_lines()
.contains_line(file_name, status.cur_line)
{
status.last_wspace = None;
}
if let Some(lw) = last_wspace {
self.buffer.push_str(&snippet[line_start..lw]);
self.buffer.push_str("\n");
if let Some(lw) = status.last_wspace {
self.buffer.push_str(&snippet[status.line_start..lw]);
self.buffer.push_str("\n");
} else {
self.buffer.push_str(&snippet[status.line_start..i + 1]);
}
status.cur_line += 1;
status.line_start = i + 1;
status.last_wspace = None;
status.rewrite_next_comment = true;
} else if c.is_whitespace() {
if status.last_wspace.is_none() {
status.last_wspace = Some(i);
}
} else if c == ';' {
if status.last_wspace.is_some() {
status.line_start = i;
}
status.rewrite_next_comment = true;
status.last_wspace = None;
} else {
self.buffer.push_str(&snippet[line_start..i + 1]);
status.rewrite_next_comment = true;
status.last_wspace = None;
}
cur_line += 1;
line_start = i + 1;
last_wspace = None;
rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
} else if c.is_whitespace() {
if last_wspace.is_none() {
last_wspace = Some(i);
}
} else if c == ';' {
if last_wspace.is_some() {
line_start = i;
}
rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
last_wspace = None;
} else {
rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
last_wspace = None;
}
}
let remaining = snippet[line_start..subslice.len() + offset].trim();
if !remaining.is_empty() {
self.buffer.push_str(remaining);
line_start = subslice.len() + offset;
rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
let remaining = snippet[status.line_start..subslice.len() + offset].trim();
if !remaining.is_empty() {
self.buffer.push_str(remaining);
status.line_start = subslice.len() + offset;
status.rewrite_next_comment = true;
}
}
}
process_last_snippet(self, &snippet[line_start..], snippet);
process_last_snippet(self, &snippet[status.line_start..], snippet);
}
}
struct SnippetStatus {
line_start: usize,
last_wspace: Option<usize>,
rewrite_next_comment: bool,
cur_line: usize,
}
impl SnippetStatus {
fn new(cur_line: usize) -> Self {
SnippetStatus {
line_start: 0,
last_wspace: None,
rewrite_next_comment: true,
cur_line,
}
}
}

View File

@ -18,7 +18,6 @@
use utils::contains_skip;
/// List all the files containing modules of a crate.
/// If a file is used twice in a crate, it appears only once.
pub fn list_files<'a>(

View File

@ -262,6 +262,11 @@ pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
}
}
#[inline]
pub fn count_newlines(input: &str) -> usize {
input.chars().filter(|&c| c == '\n').count()
}
#[inline]
pub fn trim_newlines(input: &str) -> &str {
match input.find(|c| c != '\n' && c != '\r') {

View File

@ -31,7 +31,7 @@
use regex::Regex;
use rewrite::{Rewrite, RewriteContext};
use shape::{Indent, Shape};
use utils::{self, contains_skip, inner_attributes, mk_sp, ptr_vec_to_ref_vec};
use utils::{self, contains_skip, count_newlines, inner_attributes, mk_sp, ptr_vec_to_ref_vec};
fn is_use_item(item: &ast::Item) -> bool {
match item.node {
@ -833,7 +833,7 @@ fn take_while_with_pred<'a, P>(
// Extract comments between two attributes.
let span_between_attr = mk_sp(attr.span.hi(), next_attr.span.lo());
let snippet = context.snippet(span_between_attr);
if snippet.chars().filter(|c| *c == '\n').count() >= 2 || snippet.contains('/') {
if count_newlines(&snippet) >= 2 || snippet.contains('/') {
break;
}
}
@ -886,7 +886,7 @@ fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) {
// Look at before and after comment and see if there are any empty lines.
let comment_begin = comment.chars().position(|c| c == '/');
let len = comment_begin.unwrap_or_else(|| comment.len());
let mlb = comment.chars().take(len).filter(|c| *c == '\n').count() > 1;
let mlb = count_newlines(&comment[..len]) > 1;
let mla = if comment_begin.is_none() {
mlb
} else {

View File

@ -0,0 +1,13 @@
// rustfmt-blank_lines_lower_bound: 1
fn foo() {}
fn bar() {}
// comment
fn foobar() {}
fn foo1() {}
fn bar1() {}
// comment
fn foobar1() {}

View File

@ -6,10 +6,16 @@ fn main() {
let x = 1;
let y = 2;
println!("x + y = {}", x + y);
}
fn foo() {
#![attribute]
@ -20,3 +26,19 @@ fn foo() {
}
// comment after item
// comment before item
fn bar() {
let x = 1;
// comment after statement
// comment before statment
let y = 2;
let z = 3;
println!("x + y + z = {}", x + y + z);
}

View File

@ -71,7 +71,6 @@ fn checkstyle_test() {
assert_output(filename, expected_filename);
}
// Helper function for comparing the results of rustfmt
// to a known output file generated by one of the write modes.
fn assert_output(source: &str, expected_filename: &str) {

View File

@ -0,0 +1,16 @@
// rustfmt-blank_lines_lower_bound: 1
fn foo() {}
fn bar() {}
// comment
fn foobar() {}
fn foo1() {}
fn bar1() {}
// comment
fn foobar1() {}

View File

@ -1,7 +1,6 @@
// rustfmt-where_single_line: true
// Where style
fn lorem_two_items<Ipsum, Dolor, Sit, Amet>() -> T
where
Ipsum: Eq,

View File

@ -7,28 +7,24 @@ fn main() {
();
}
'label: loop
// loop comment
{
();
}
cond = true;
while cond
{
();
}
'while_label: while cond
{
// while comment
();
}
for obj in iter
{
for sub_obj in obj

View File

@ -6,26 +6,22 @@ fn main() {
();
}
'label: loop
// loop comment
{
();
}
cond = true;
while cond {
();
}
'while_label: while cond {
// while comment
();
}
for obj in iter {
for sub_obj in obj {
'nested_while_label: while cond {

View File

@ -14,10 +14,8 @@ fn main() {
();
}
let a = if 0 > 1 { unreachable!() } else { 0x0 };
if true
{
();

View File

@ -13,10 +13,8 @@ fn main() {
();
}
let a = if 0 > 1 { unreachable!() } else { 0x0 };
if true {
();
} else if false {

View File

@ -13,10 +13,8 @@ fn main() {
();
}
let a = if 0 > 1 { unreachable!() } else { 0x0 };
if true {
();
}

View File

@ -3,7 +3,6 @@ enum TestEnum {
Arm2,
}
fn foo() {
let test = TestEnum::Arm1;
match test {

View File

@ -95,7 +95,6 @@ pub enum GenericEnum<I, T>
Right { list: I, root: T }, // Post Comment
}
enum EmtpyWithComment {
// Some comment
}

View File

@ -18,7 +18,6 @@ fn op(
"cool"
}
fn weird_comment(
// /*/ double level */ comment
x: Hello, // /*/* triple, even */*/

View File

@ -24,7 +24,6 @@ fn foo(
}
fn foo<U, T>(
a: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA,
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,

View File

@ -78,7 +78,6 @@ fn foo() {}
}
}
mod b {
mod a {
impl Foo {

View File

@ -4,7 +4,6 @@
// Test of lots of random stuff.
// FIXME split this into multiple, self-contained tests.
#[attr1]
extern crate foo;
#[attr2]
@ -24,7 +23,6 @@
mod doc;
mod other;
// sfdgfffffffffffffffffffffffffffffffffffffffffffffffffffffff
// ffffffffffffffffffffffffffffffffffffffffff
@ -129,7 +127,6 @@ fn main() {
println!("{}", i);
}
while true {
hello();
}

View File

@ -1,5 +1,9 @@
fn main() {
let x = 1;
let y = 2;
println!("x + y = {}", x + y);
}
fn foo() {
@ -9,3 +13,16 @@ fn foo() {
// comment
}
// comment after item
// comment before item
fn bar() {
let x = 1;
// comment after statement
// comment before statment
let y = 2;
let z = 3;
println!("x + y + z = {}", x + y + z);
}

View File

@ -52,7 +52,6 @@
T,
> = ();
pub type WithWhereClause<LONGPARAMETERNAME, T>
where
T: Clone,