Merge pull request #3480 from sinkuu/cleanup

Cleanups
This commit is contained in:
Seiichi Uchida 2019-03-29 22:07:19 +09:00 committed by GitHub
commit dfa94d1505
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 60 additions and 76 deletions

View File

@ -550,7 +550,7 @@ impl<'a> ChainFormatterShared<'a> {
let almost_total = if extendable {
prev_last_line_width
} else {
self.rewrites.iter().fold(0, |a, b| a + b.len())
self.rewrites.iter().map(|a| a.len()).sum()
} + last.tries;
let one_line_budget = if self.child_count == 1 {
shape.width

View File

@ -591,7 +591,7 @@ impl<'a> CommentRewrite<'a> {
) {
Some(s) => self.result.push_str(&Self::join_block(
&s,
&format!("{}{}", &self.comment_line_separator, ib.line_start),
&format!("{}{}", self.comment_line_separator, ib.line_start),
)),
None => self.result.push_str(&Self::join_block(
&ib.original_block_as_string(),
@ -634,7 +634,7 @@ impl<'a> CommentRewrite<'a> {
) {
Some(s) => self.result.push_str(&Self::join_block(
&s,
&format!("{}{}", &self.comment_line_separator, ib.line_start),
&format!("{}{}", self.comment_line_separator, ib.line_start),
)),
None => self.result.push_str(&Self::join_block(
&ib.original_block_as_string(),

View File

@ -236,10 +236,7 @@ macro_rules! create_config {
use std::cmp;
let max = 0;
$( let max = cmp::max(max, stringify!($i).len()+1); )+
let mut space_str = String::with_capacity(max);
for _ in 0..max {
space_str.push(' ');
}
let space_str = " ".repeat(max);
writeln!(out, "Configuration Options:").unwrap();
$(
if $stb || include_unstable {

View File

@ -156,20 +156,18 @@ fn normalize_ranges(ranges: &mut HashMap<FileName, Vec<Range>>) {
for ranges in ranges.values_mut() {
ranges.sort();
let mut result = vec![];
{
let mut iter = ranges.iter_mut().peekable();
while let Some(next) = iter.next() {
let mut next = *next;
while let Some(&&mut peek) = iter.peek() {
if let Some(merged) = next.merge(peek) {
iter.next().unwrap();
next = merged;
} else {
break;
}
let mut iter = ranges.iter_mut().peekable();
while let Some(next) = iter.next() {
let mut next = *next;
while let Some(&&mut peek) = iter.peek() {
if let Some(merged) = next.merge(peek) {
iter.next().unwrap();
next = merged;
} else {
break;
}
result.push(next)
}
result.push(next)
}
*ranges = result;
}

View File

@ -257,16 +257,14 @@ impl Config {
let parsed: ::toml::Value = toml
.parse()
.map_err(|e| format!("Could not parse TOML: {}", e))?;
let mut err: String = String::new();
{
let table = parsed
.as_table()
.ok_or(String::from("Parsed config was not table"))?;
for key in table.keys() {
if !Config::is_valid_name(key) {
let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
err.push_str(msg)
}
let mut err = String::new();
let table = parsed
.as_table()
.ok_or(String::from("Parsed config was not table"))?;
for key in table.keys() {
if !Config::is_valid_name(key) {
let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
err.push_str(msg)
}
}
match parsed.try_into() {

View File

@ -1,6 +1,7 @@
use std::borrow::Cow;
use std::cmp::min;
use itertools::Itertools;
use syntax::parse::token::DelimToken;
use syntax::source_map::{BytePos, SourceMap, Span};
use syntax::{ast, ptr};
@ -1246,8 +1247,7 @@ fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) ->
if !context.config.format_strings() {
if string_lit
.lines()
.rev()
.skip(1)
.dropping_back(1)
.all(|line| line.ends_with('\\'))
{
let new_indent = shape.visual_indent(1).indent;
@ -1459,7 +1459,7 @@ fn rewrite_paren(
let subexpr_str = subexpr.rewrite(context, sub_shape)?;
let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
if fits_single_line {
Some(format!("({}{}{})", pre_comment, &subexpr_str, post_comment))
Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
} else {
rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
}

View File

@ -48,11 +48,7 @@ impl<'b, T: Write + 'b> Session<'b, T> {
let format_result = format_project(input, config, self);
format_result.map(|report| {
{
let new_errors = &report.internal.borrow().1;
self.errors.add(new_errors);
}
self.errors.add(&report.internal.borrow().1);
report
})
})

View File

@ -205,11 +205,10 @@ impl fmt::Display for UseSegment {
UseSegment::List(ref list) => {
write!(f, "{{")?;
for (i, item) in list.iter().enumerate() {
let is_last = i == list.len() - 1;
write!(f, "{}", item)?;
if !is_last {
if i != 0 {
write!(f, ", ")?;
}
write!(f, "{}", item)?;
}
write!(f, "}}")
}
@ -219,13 +218,12 @@ impl fmt::Display for UseSegment {
impl fmt::Display for UseTree {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, segment) in self.path.iter().enumerate() {
let is_last = i == self.path.len() - 1;
write!(f, "{}", segment)?;
if !is_last {
if i != 0 {
write!(f, "::")?;
}
write!(f, "{}", segment)?;
}
write!(f, "")
Ok(())
}
}

View File

@ -730,7 +730,7 @@ pub fn format_impl(
if generics.where_clause.predicates.len() == 1 {
result.push_str(",");
}
result.push_str(&format!("{}{{{}}}", &sep, &sep));
result.push_str(&format!("{}{{{}}}", sep, sep));
} else {
result.push_str(" {}");
}
@ -912,7 +912,7 @@ fn rewrite_trait_ref(
let shape = Shape::indented(offset + used_space, context.config);
if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
if !trait_ref_str.contains('\n') {
return Some(format!(" {}{}", polarity_str, &trait_ref_str));
return Some(format!(" {}{}", polarity_str, trait_ref_str));
}
}
// We could not make enough space for trait_ref, so put it on new line.
@ -921,9 +921,9 @@ fn rewrite_trait_ref(
let trait_ref_str = trait_ref.rewrite(context, shape)?;
Some(format!(
"{}{}{}",
&offset.to_string_with_newline(context.config),
offset.to_string_with_newline(context.config),
polarity_str,
&trait_ref_str
trait_ref_str
))
}

View File

@ -577,13 +577,8 @@ pub fn extract_pre_comment(pre_snippet: &str) -> (Option<String>, ListItemCommen
let has_block_comment = trimmed_pre_snippet.ends_with("*/");
let has_single_line_comment = trimmed_pre_snippet.starts_with("//");
if has_block_comment {
let comment_end = pre_snippet.chars().rev().position(|c| c == '/').unwrap();
if pre_snippet
.chars()
.rev()
.take(comment_end + 1)
.any(|c| c == '\n')
{
let comment_end = pre_snippet.rfind(|c| c == '/').unwrap();
if pre_snippet[comment_end..].contains('\n') {
(
Some(trimmed_pre_snippet.to_owned()),
ListItemCommentStyle::DifferentLine,

View File

@ -540,17 +540,12 @@ fn register_metavariable(
name: &str,
dollar_count: usize,
) {
let mut new_name = String::new();
let mut old_name = String::new();
let mut new_name = "$".repeat(dollar_count - 1);
let mut old_name = "$".repeat(dollar_count);
old_name.push('$');
for _ in 0..(dollar_count - 1) {
new_name.push('$');
old_name.push('$');
}
new_name.push('z');
new_name.push_str(&name);
old_name.push_str(&name);
new_name.push_str(name);
old_name.push_str(name);
result.push_str(&new_name);
map.insert(old_name, new_name);

View File

@ -2,6 +2,7 @@
use std::cmp::min;
use itertools::Itertools;
use syntax::parse::token::DelimToken;
use syntax::source_map::Span;
use syntax::{ast, ptr};
@ -711,10 +712,14 @@ fn last_item_shape(
if items.len() == 1 && !lists.get(0)?.is_nested_call() {
return Some(shape);
}
let offset = items.iter().rev().skip(1).fold(0, |acc, i| {
// 2 = ", "
acc + 2 + i.inner_as_ref().len()
});
let offset = items
.iter()
.dropping_back(1)
.map(|i| {
// 2 = ", "
2 + i.inner_as_ref().len()
})
.sum();
Shape {
width: min(args_max_width, shape.width),
..shape

View File

@ -609,11 +609,11 @@ fn handle_result(
for (file_name, fmt_text) in result {
// If file is in tests/source, compare to file with same name in tests/target.
let target = get_target(&file_name, target);
let open_error = format!("couldn't open target {:?}", &target);
let open_error = format!("couldn't open target {:?}", target);
let mut f = fs::File::open(&target).expect(&open_error);
let mut text = String::new();
let read_error = format!("failed reading target {:?}", &target);
let read_error = format!("failed reading target {:?}", target);
f.read_to_string(&mut text).expect(&read_error);
// Ignore LF and CRLF difference for Windows.

View File

@ -2,6 +2,7 @@
use std::cmp;
use itertools::Itertools;
use syntax::ast;
use syntax::source_map::{BytePos, Span};
@ -190,11 +191,8 @@ fn struct_field_prefix_max_min_width<T: AlignedItem>(
}
})
})
.fold(Some((0, ::std::usize::MAX)), |acc, len| match (acc, len) {
(Some((max_len, min_len)), Some(len)) => {
Some((cmp::max(max_len, len), cmp::min(min_len, len)))
}
_ => None,
.fold_options((0, ::std::usize::MAX), |(max_len, min_len), len| {
(cmp::max(max_len, len), cmp::min(min_len, len))
})
.unwrap_or((0, 0))
}
@ -274,7 +272,11 @@ fn group_aligned_items<T: AlignedItem>(
.skip(1)
.collect::<Vec<_>>()
.join("\n");
let spacings = if snippet.lines().rev().skip(1).any(|l| l.trim().is_empty()) {
let spacings = if snippet
.lines()
.dropping_back(1)
.any(|l| l.trim().is_empty())
{
"\n"
} else {
""