formatting

This commit is contained in:
Nick Cameron 2018-07-11 21:35:10 +12:00
parent f0fe9c3c4a
commit 481e85cc58
16 changed files with 154 additions and 125 deletions

View File

@ -422,8 +422,7 @@ fn determine_operation(matches: &Matches) -> Result<Operation, ErrorKind> {
// we will do comparison later, so here tries to canonicalize first
// to get the expected behavior.
p.canonicalize().unwrap_or(p)
})
.collect();
}).collect();
Ok(Operation::Format {
files,

View File

@ -163,8 +163,7 @@ fn format_crate(
if verbosity == Verbosity::Verbose {
println!("[{}] {:?}", t.kind, t.path)
}
})
.map(|t| t.path)
}).map(|t| t.path)
.collect();
run_rustfmt(&files, &rustfmt_args, verbosity)

View File

@ -113,11 +113,7 @@ impl Rewrite for ChainItem {
impl ChainItem {
// Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
// `.c` and any trailing `?`s.
fn rewrite_postfix(
&self,
context: &RewriteContext,
shape: Shape,
) -> Option<String> {
fn rewrite_postfix(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
let shape = shape.sub_width(self.tries)?;
let mut rewrite = match self.expr.node {
ast::ExprKind::MethodCall(ref segment, ref expressions) => {
@ -128,14 +124,22 @@ impl ChainItem {
},
_ => &[],
};
Self::rewrite_method_call(segment.ident, types, expressions, self.expr.span, context, shape)?
Self::rewrite_method_call(
segment.ident,
types,
expressions,
self.expr.span,
context,
shape,
)?
}
ast::ExprKind::Field(ref nested, ref field) => {
let space = if Self::is_tup_field_access(&self.expr) && Self::is_tup_field_access(nested) {
" "
} else {
""
};
let space =
if Self::is_tup_field_access(&self.expr) && Self::is_tup_field_access(nested) {
" "
} else {
""
};
let result = format!("{}.{}", space, field.name);
if result.len() <= shape.width {
result
@ -296,10 +300,20 @@ trait ChainFormatter {
// .baz()
// ```
// If `bar` were not part of the root, then baz would be orphaned and 'float'.
fn format_root(&mut self, parent: &ChainItem, context: &RewriteContext, shape: Shape) -> Option<()>;
fn format_root(
&mut self,
parent: &ChainItem,
context: &RewriteContext,
shape: Shape,
) -> Option<()>;
fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Shape;
fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()>;
fn format_last_child(&mut self, context: &RewriteContext, shape: Shape, child_shape: Shape) -> Option<()>;
fn format_last_child(
&mut self,
context: &RewriteContext,
shape: Shape,
child_shape: Shape,
) -> Option<()>;
fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String>;
// Returns `Some` if the chain is only a root, None otherwise.
fn pure_root(&mut self) -> Option<String>;
@ -309,7 +323,7 @@ trait ChainFormatter {
// formatters can delegate much behaviour to `ChainFormatterShared`.
struct ChainFormatterShared<'a> {
// The current working set of child items.
children: &'a[ChainItem],
children: &'a [ChainItem],
// The current rewrites of items (includes trailing `?`s, but not any way to
// connect the rewrites together).
rewrites: Vec<String>,
@ -320,7 +334,7 @@ struct ChainFormatterShared<'a> {
child_count: usize,
}
impl <'a> ChainFormatterShared<'a> {
impl<'a> ChainFormatterShared<'a> {
fn new(chain: &'a Chain) -> ChainFormatterShared<'a> {
ChainFormatterShared {
children: &chain.children,
@ -371,9 +385,16 @@ impl <'a> ChainFormatterShared<'a> {
// result
// })
// ```
fn format_last_child(&mut self, may_extend: bool, context: &RewriteContext, shape: Shape, child_shape: Shape) -> Option<()> {
fn format_last_child(
&mut self,
may_extend: bool,
context: &RewriteContext,
shape: Shape,
child_shape: Shape,
) -> Option<()> {
let last = &self.children[0];
let extendable = may_extend && last_line_extendable(&self.rewrites[self.rewrites.len() - 1]);
let extendable =
may_extend && last_line_extendable(&self.rewrites[self.rewrites.len() - 1]);
// Total of all items excluding the last.
let almost_total = if extendable {
@ -387,7 +408,8 @@ impl <'a> ChainFormatterShared<'a> {
min(shape.width, context.config.width_heuristics().chain_width)
}.saturating_sub(almost_total);
let all_in_one_line = self.rewrites.iter().all(|s| !s.contains('\n')) && one_line_budget > 0;
let all_in_one_line =
self.rewrites.iter().all(|s| !s.contains('\n')) && one_line_budget > 0;
let last_shape = if all_in_one_line {
shape.sub_width(last.tries)?
} else {
@ -413,7 +435,8 @@ impl <'a> ChainFormatterShared<'a> {
// layout, just by looking at the overflowed rewrite. Now we rewrite the
// last child on its own line, and compare two rewrites to choose which is
// better.
let last_shape = child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?;
let last_shape = child_shape
.sub_width(shape.rhs_overhead(context.config) + last.tries)?;
match last.rewrite_postfix(context, last_shape) {
Some(ref new_rw) if !could_fit_single_line => {
last_subexpr_str = Some(new_rw.clone());
@ -440,7 +463,12 @@ impl <'a> ChainFormatterShared<'a> {
Some(())
}
fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape, block_like_iter: impl Iterator<Item=bool>) -> Option<String> {
fn join_rewrites(
&self,
context: &RewriteContext,
child_shape: Shape,
block_like_iter: impl Iterator<Item = bool>,
) -> Option<String> {
let connector = if self.fits_single_line {
// Yay, we can put everything on one line.
Cow::from("")
@ -473,7 +501,7 @@ struct ChainFormatterBlock<'a> {
is_block_like: Vec<bool>,
}
impl <'a> ChainFormatterBlock<'a> {
impl<'a> ChainFormatterBlock<'a> {
fn new(chain: &'a Chain) -> ChainFormatterBlock<'a> {
ChainFormatterBlock {
shared: ChainFormatterShared::new(chain),
@ -482,8 +510,13 @@ impl <'a> ChainFormatterBlock<'a> {
}
}
impl <'a> ChainFormatter for ChainFormatterBlock<'a> {
fn format_root(&mut self, parent: &ChainItem, context: &RewriteContext, shape: Shape) -> Option<()> {
impl<'a> ChainFormatter for ChainFormatterBlock<'a> {
fn format_root(
&mut self,
parent: &ChainItem,
context: &RewriteContext,
shape: Shape,
) -> Option<()> {
let mut root_rewrite: String = parent.rewrite(context, shape)?;
let mut root_ends_with_block = is_block_expr(context, &parent.expr, &root_rewrite);
@ -520,18 +553,26 @@ impl <'a> ChainFormatter for ChainFormatterBlock<'a> {
fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
for item in self.shared.children[1..].iter().rev() {
let rewrite = item.rewrite_postfix(context, child_shape)?;
self.is_block_like.push(is_block_expr(context, &item.expr, &rewrite));
self.is_block_like
.push(is_block_expr(context, &item.expr, &rewrite));
self.shared.rewrites.push(rewrite);
}
Some(())
}
fn format_last_child(&mut self, context: &RewriteContext, shape: Shape, child_shape: Shape) -> Option<()> {
self.shared.format_last_child(true, context, shape, child_shape)
fn format_last_child(
&mut self,
context: &RewriteContext,
shape: Shape,
child_shape: Shape,
) -> Option<()> {
self.shared
.format_last_child(true, context, shape, child_shape)
}
fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
self.shared.join_rewrites(context, child_shape, self.is_block_like.iter().cloned())
self.shared
.join_rewrites(context, child_shape, self.is_block_like.iter().cloned())
}
fn pure_root(&mut self) -> Option<String> {
@ -552,8 +593,13 @@ impl<'a> ChainFormatterVisual<'a> {
}
}
impl <'a> ChainFormatter for ChainFormatterVisual<'a> {
fn format_root(&mut self, parent: &ChainItem, context: &RewriteContext, shape: Shape) -> Option<()> {
impl<'a> ChainFormatter for ChainFormatterVisual<'a> {
fn format_root(
&mut self,
parent: &ChainItem,
context: &RewriteContext,
shape: Shape,
) -> Option<()> {
// Determines if we can continue formatting a given expression on the same line.
fn is_continuable(expr: &ast::Expr) -> bool {
match expr.node {
@ -596,12 +642,19 @@ impl <'a> ChainFormatter for ChainFormatterVisual<'a> {
Some(())
}
fn format_last_child(&mut self, context: &RewriteContext, shape: Shape, child_shape: Shape) -> Option<()> {
self.shared.format_last_child(false, context, shape, child_shape)
fn format_last_child(
&mut self,
context: &RewriteContext,
shape: Shape,
child_shape: Shape,
) -> Option<()> {
self.shared
.format_last_child(false, context, shape, child_shape)
}
fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
self.shared.join_rewrites(context, child_shape, iter::repeat(false))
self.shared
.join_rewrites(context, child_shape, iter::repeat(false))
}
fn pure_root(&mut self) -> Option<String> {
@ -613,9 +666,7 @@ impl <'a> ChainFormatter for ChainFormatterVisual<'a> {
// parens, braces, and brackets in its idiomatic formatting.
fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
match expr.node {
ast::ExprKind::Mac(..)
| ast::ExprKind::Call(..)
| ast::ExprKind::MethodCall(..) => {
ast::ExprKind::Mac(..) | ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) => {
context.use_block_indent() && repr.contains('\n')
}
ast::ExprKind::Struct(..)
@ -631,7 +682,7 @@ fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool
| ast::ExprKind::Binary(_, _, ref expr)
| ast::ExprKind::Index(_, ref expr)
| ast::ExprKind::Unary(_, ref expr)
| ast::ExprKind::Closure(_, _, _, _, ref expr, _)
| ast::ExprKind::Closure(_, _, _, _, ref expr, _)
| ast::ExprKind::Try(ref expr)
| ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
_ => false,

View File

@ -198,8 +198,7 @@ fn rewrite_closure_expr(
} else {
Some(rw)
}
})
.map(|rw| format!("{} {}", prefix, rw))
}).map(|rw| format!("{} {}", prefix, rw))
}
// Rewrite closure whose body is block.
@ -376,11 +375,8 @@ where
.map(|e| match e.node {
ast::ExprKind::Closure(..) => true,
_ => false,
})
.unwrap_or(false)
})
.count()
> 1
}).unwrap_or(false)
}).count() > 1
}
fn is_block_closure_forced(context: &RewriteContext, expr: &ast::Expr) -> bool {

View File

@ -348,8 +348,7 @@ fn rewrite_comment_inner(
}
line
})
.map(|s| left_trim_comment_line(s, &style))
}).map(|s| left_trim_comment_line(s, &style))
.map(|(line, has_leading_whitespace)| {
if orig.starts_with("/*") && line_breaks == 0 {
(
@ -517,8 +516,7 @@ fn trim_custom_comment_prefix(s: &str) -> String {
} else {
line
}
})
.collect::<Vec<_>>()
}).collect::<Vec<_>>()
.join("\n")
}
@ -606,8 +604,7 @@ fn light_rewrite_comment(
};
// Preserve markdown's double-space line break syntax in doc comment.
trim_right_unless_two_whitespaces(left_trimmed, is_doc_comment)
})
.collect();
}).collect();
Some(lines.join(&format!("\n{}", offset.to_string(config))))
}
@ -1341,8 +1338,7 @@ mod test {
.filter_map(|(s, c)| match s {
FullCodeCharKind::Normal | FullCodeCharKind::InString => Some(c),
_ => None,
})
.collect()
}).collect()
}
#[test]

View File

@ -322,8 +322,7 @@ impl IgnoreList {
path.push(s);
path
}
})
.collect();
}).collect();
}
fn skip_file_inner(&self, file: &Path) -> bool {

View File

@ -1212,8 +1212,7 @@ fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Opt
new_indent.to_string(context.config),
line.trim_left()
)
})
.collect::<Vec<_>>()
}).collect::<Vec<_>>()
.join("\n")
.trim_left(),
);

View File

@ -46,8 +46,7 @@ fn prune_files(files: Vec<&str>) -> Vec<&str> {
return true;
}
pruned_prefixes.iter().all(|pp| !f.starts_with(pp))
})
.collect()
}).collect()
}
fn git_diff(commits: &str) -> String {

View File

@ -344,8 +344,7 @@ impl UseTree {
.zip(items.into_iter())
.map(|(t, list_item)| {
Self::from_ast(context, &t.0, Some(list_item), None, None, None)
})
.collect(),
}).collect(),
));
}
UseTreeKind::Simple(ref rename, ..) => {

View File

@ -1669,7 +1669,7 @@ fn rewrite_static(
&**expr,
Shape::legacy(remaining_width, offset.block_only()),
).and_then(|res| recover_comment_removed(res, static_parts.span, context))
.map(|s| if s.ends_with(';') { s } else { s + ";" })
.map(|s| if s.ends_with(';') { s } else { s + ";" })
} else {
Some(format!("{}{};", prefix, ty_str))
}
@ -2783,17 +2783,15 @@ impl Rewrite for ast::ForeignItem {
let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
let item_str = match self.node {
ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
rewrite_fn_base(
context,
shape.indent,
self.ident,
&FnSig::new(fn_decl, generics, self.vis.clone()),
span,
false,
false,
).map(|(s, _)| format!("{};", s))
}
ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => rewrite_fn_base(
context,
shape.indent,
self.ident,
&FnSig::new(fn_decl, generics, self.vis.clone()),
span,
false,
false,
).map(|(s, _)| format!("{};", s)),
ast::ForeignItemKind::Static(ref ty, is_mutable) => {
// FIXME(#21): we're dropping potential comments in between the
// function keywords here.

View File

@ -1115,26 +1115,25 @@ fn indent_macro_snippet(
};
trimmed_lines.push((trimmed, line, prefix_space_width));
prefix_space_width
})
.min()?;
}).min()?;
Some(
first_line + "\n" + &trimmed_lines
.iter()
.map(
|&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
_ if !trimmed => line.to_owned(),
Some(original_indent_width) => {
let new_indent_width = indent.width() + original_indent_width
.saturating_sub(min_prefix_space_width);
let new_indent = Indent::from_width(context.config, new_indent_width);
format!("{}{}", new_indent.to_string(context.config), line.trim())
}
None => String::new(),
},
)
.collect::<Vec<_>>()
.join("\n"),
first_line + "\n"
+ &trimmed_lines
.iter()
.map(
|&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
_ if !trimmed => line.to_owned(),
Some(original_indent_width) => {
let new_indent_width = indent.width()
+ original_indent_width.saturating_sub(min_prefix_space_width);
let new_indent = Indent::from_width(context.config, new_indent_width);
format!("{}{}", new_indent.to_string(context.config), line.trim())
}
None => String::new(),
},
).collect::<Vec<_>>()
.join("\n"),
)
}
@ -1296,8 +1295,7 @@ impl MacroBranch {
}
(s + l + "\n", !kind.is_string() || l.ends_with('\\'))
},
)
.0;
).0;
// Undo our replacement of macro variables.
// FIXME: this could be *much* more efficient.

View File

@ -151,8 +151,7 @@ fn rewrite_reorderable_items(
.map(|use_tree| ListItem {
item: use_tree.rewrite_top_level(context, nested_shape),
..use_tree.list_item.unwrap_or_else(ListItem::empty)
})
.collect();
}).collect();
wrap_reorderable_items(context, &item_vec, nested_shape)
}
@ -242,15 +241,13 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
let item_length = items
.iter()
.take_while(|ppi| {
item_kind.is_same_item_kind(&***ppi)
&& (!in_group || {
let current = self.codemap.lookup_line_range(ppi.span());
let in_same_group = current.lo < last.hi + 2;
last = current;
in_same_group
})
})
.count();
item_kind.is_same_item_kind(&***ppi) && (!in_group || {
let current = self.codemap.lookup_line_range(ppi.span());
let in_same_group = current.lo < last.hi + 2;
last = current;
in_same_group
})
}).count();
let items = &items[..item_length];
let at_least_one_in_file_lines = items

View File

@ -193,13 +193,15 @@ where
W: Write,
{
for mismatch in diff {
let (num_removed, num_added) = mismatch.lines.iter().fold((0, 0), |(rem, add), line| {
match *line {
DiffLine::Context(_) => panic!("No Context expected"),
DiffLine::Expected(_) => (rem, add + 1),
DiffLine::Resulting(_) => (rem + 1, add),
}
});
let (num_removed, num_added) =
mismatch
.lines
.iter()
.fold((0, 0), |(rem, add), line| match *line {
DiffLine::Context(_) => panic!("No Context expected"),
DiffLine::Expected(_) => (rem, add + 1),
DiffLine::Resulting(_) => (rem + 1, add),
});
// Write a header with enough information to separate the modified lines.
writeln!(
out,

View File

@ -514,8 +514,7 @@ fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
.to_owned(),
)
})
})
.collect()
}).collect()
}
// Compare output to input.
@ -884,8 +883,8 @@ fn configuration_snippet_tests() {
fs::File::open(Path::new(CONFIGURATIONS_FILE_NAME))
.expect(&format!("Couldn't read file {}", CONFIGURATIONS_FILE_NAME)),
).lines()
.map(|l| l.unwrap())
.enumerate();
.map(|l| l.unwrap())
.enumerate();
let mut code_blocks: Vec<ConfigCodeBlock> = Vec::new();
let mut hash_set = Config::hash_set();
@ -961,5 +960,5 @@ fn verify_check_works() {
"--check",
temp_file.path.to_str().unwrap(),
]).succeeds()
.unwrap();
.unwrap();
}

View File

@ -548,7 +548,8 @@ impl Rewrite for ast::GenericParam {
};
result.push_str(eq_str);
let budget = shape.width.checked_sub(result.len())?;
let rewrite = def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
let rewrite =
def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
result.push_str(&rewrite);
}
@ -793,8 +794,7 @@ fn rewrite_lifetime_param(
.filter(|p| match p.kind {
ast::GenericParamKind::Lifetime => true,
_ => false,
})
.map(|lt| lt.rewrite(context, shape))
}).map(|lt| lt.rewrite(context, shape))
.collect::<Option<Vec<_>>>()?
.join(", ");
if result.is_empty() {

View File

@ -200,14 +200,12 @@ fn struct_field_prefix_max_min_width<T: AlignedItem>(
Some(field_str.len())
}
})
})
.fold(Some((0, ::std::usize::MAX)), |acc, len| match (acc, len) {
}).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,
})
.unwrap_or((0, 0))
}).unwrap_or((0, 0))
}
fn rewrite_aligned_items_inner<T: AlignedItem>(