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

View File

@ -591,7 +591,7 @@ impl<'a> CommentRewrite<'a> {
) { ) {
Some(s) => self.result.push_str(&Self::join_block( Some(s) => self.result.push_str(&Self::join_block(
&s, &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( None => self.result.push_str(&Self::join_block(
&ib.original_block_as_string(), &ib.original_block_as_string(),
@ -634,7 +634,7 @@ impl<'a> CommentRewrite<'a> {
) { ) {
Some(s) => self.result.push_str(&Self::join_block( Some(s) => self.result.push_str(&Self::join_block(
&s, &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( None => self.result.push_str(&Self::join_block(
&ib.original_block_as_string(), &ib.original_block_as_string(),

View File

@ -236,10 +236,7 @@ macro_rules! create_config {
use std::cmp; use std::cmp;
let max = 0; let max = 0;
$( let max = cmp::max(max, stringify!($i).len()+1); )+ $( let max = cmp::max(max, stringify!($i).len()+1); )+
let mut space_str = String::with_capacity(max); let space_str = " ".repeat(max);
for _ in 0..max {
space_str.push(' ');
}
writeln!(out, "Configuration Options:").unwrap(); writeln!(out, "Configuration Options:").unwrap();
$( $(
if $stb || include_unstable { 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() { for ranges in ranges.values_mut() {
ranges.sort(); ranges.sort();
let mut result = vec![]; let mut result = vec![];
{ let mut iter = ranges.iter_mut().peekable();
let mut iter = ranges.iter_mut().peekable(); while let Some(next) = iter.next() {
while let Some(next) = iter.next() { let mut next = *next;
let mut next = *next; while let Some(&&mut peek) = iter.peek() {
while let Some(&&mut peek) = iter.peek() { if let Some(merged) = next.merge(peek) {
if let Some(merged) = next.merge(peek) { iter.next().unwrap();
iter.next().unwrap(); next = merged;
next = merged; } else {
} else { break;
break;
}
} }
result.push(next)
} }
result.push(next)
} }
*ranges = result; *ranges = result;
} }

View File

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

View File

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

View File

@ -205,11 +205,10 @@ impl fmt::Display for UseSegment {
UseSegment::List(ref list) => { UseSegment::List(ref list) => {
write!(f, "{{")?; write!(f, "{{")?;
for (i, item) in list.iter().enumerate() { for (i, item) in list.iter().enumerate() {
let is_last = i == list.len() - 1; if i != 0 {
write!(f, "{}", item)?;
if !is_last {
write!(f, ", ")?; write!(f, ", ")?;
} }
write!(f, "{}", item)?;
} }
write!(f, "}}") write!(f, "}}")
} }
@ -219,13 +218,12 @@ impl fmt::Display for UseSegment {
impl fmt::Display for UseTree { impl fmt::Display for UseTree {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, segment) in self.path.iter().enumerate() { for (i, segment) in self.path.iter().enumerate() {
let is_last = i == self.path.len() - 1; if i != 0 {
write!(f, "{}", segment)?;
if !is_last {
write!(f, "::")?; 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 { if generics.where_clause.predicates.len() == 1 {
result.push_str(","); result.push_str(",");
} }
result.push_str(&format!("{}{{{}}}", &sep, &sep)); result.push_str(&format!("{}{{{}}}", sep, sep));
} else { } else {
result.push_str(" {}"); result.push_str(" {}");
} }
@ -912,7 +912,7 @@ fn rewrite_trait_ref(
let shape = Shape::indented(offset + used_space, context.config); let shape = Shape::indented(offset + used_space, context.config);
if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) { if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
if !trait_ref_str.contains('\n') { 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. // 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)?; let trait_ref_str = trait_ref.rewrite(context, shape)?;
Some(format!( Some(format!(
"{}{}{}", "{}{}{}",
&offset.to_string_with_newline(context.config), offset.to_string_with_newline(context.config),
polarity_str, 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_block_comment = trimmed_pre_snippet.ends_with("*/");
let has_single_line_comment = trimmed_pre_snippet.starts_with("//"); let has_single_line_comment = trimmed_pre_snippet.starts_with("//");
if has_block_comment { if has_block_comment {
let comment_end = pre_snippet.chars().rev().position(|c| c == '/').unwrap(); let comment_end = pre_snippet.rfind(|c| c == '/').unwrap();
if pre_snippet if pre_snippet[comment_end..].contains('\n') {
.chars()
.rev()
.take(comment_end + 1)
.any(|c| c == '\n')
{
( (
Some(trimmed_pre_snippet.to_owned()), Some(trimmed_pre_snippet.to_owned()),
ListItemCommentStyle::DifferentLine, ListItemCommentStyle::DifferentLine,

View File

@ -540,17 +540,12 @@ fn register_metavariable(
name: &str, name: &str,
dollar_count: usize, dollar_count: usize,
) { ) {
let mut new_name = String::new(); let mut new_name = "$".repeat(dollar_count - 1);
let mut old_name = String::new(); 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('z');
new_name.push_str(&name); new_name.push_str(name);
old_name.push_str(&name); old_name.push_str(name);
result.push_str(&new_name); result.push_str(&new_name);
map.insert(old_name, new_name); map.insert(old_name, new_name);

View File

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

View File

@ -609,11 +609,11 @@ fn handle_result(
for (file_name, fmt_text) in result { for (file_name, fmt_text) in result {
// If file is in tests/source, compare to file with same name in tests/target. // If file is in tests/source, compare to file with same name in tests/target.
let target = get_target(&file_name, 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 f = fs::File::open(&target).expect(&open_error);
let mut text = String::new(); 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); f.read_to_string(&mut text).expect(&read_error);
// Ignore LF and CRLF difference for Windows. // Ignore LF and CRLF difference for Windows.

View File

@ -2,6 +2,7 @@
use std::cmp; use std::cmp;
use itertools::Itertools;
use syntax::ast; use syntax::ast;
use syntax::source_map::{BytePos, Span}; 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) { .fold_options((0, ::std::usize::MAX), |(max_len, min_len), len| {
(Some((max_len, min_len)), Some(len)) => { (cmp::max(max_len, len), cmp::min(min_len, len))
Some((cmp::max(max_len, len), cmp::min(min_len, len)))
}
_ => None,
}) })
.unwrap_or((0, 0)) .unwrap_or((0, 0))
} }
@ -274,7 +272,11 @@ fn group_aligned_items<T: AlignedItem>(
.skip(1) .skip(1)
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join("\n"); .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" "\n"
} else { } else {
"" ""