Cargo fmt

This commit is contained in:
topecongiro 2018-05-08 06:25:48 +09:00
parent 0ec311ee07
commit bd25c7d0f7
17 changed files with 86 additions and 43 deletions

View File

@ -156,7 +156,8 @@ pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -
let last_subexpr = &subexpr_list[suffix_try_num];
let subexpr_list = &subexpr_list[suffix_try_num..subexpr_num - prefix_try_num];
let iter = subexpr_list.iter().skip(1).rev().zip(child_shape_iter);
let mut rewrites = iter.map(|(e, shape)| rewrite_chain_subexpr(e, total_span, context, shape))
let mut rewrites = iter
.map(|(e, shape)| rewrite_chain_subexpr(e, total_span, context, shape))
.collect::<Option<Vec<_>>>()?;
// Total of all items excluding the last.

View File

@ -50,7 +50,8 @@ pub fn rewrite_closure(
if let ast::ExprKind::Block(ref block) = body.node {
// The body of the closure is an empty block.
if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
return body.rewrite(context, shape)
return body
.rewrite(context, shape)
.map(|s| format!("{} {}", prefix, s));
}

View File

@ -249,7 +249,8 @@ fn _rewrite_comment(
// If there are lines without a starting sigil, we won't format them correctly
// so in that case we won't even re-align (if !config.normalize_comments()) and
// we should stop now.
let num_bare_lines = orig.lines()
let num_bare_lines = orig
.lines()
.map(|line| line.trim())
.filter(|l| !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*")))
.count();
@ -271,11 +272,13 @@ fn identify_comment(
is_doc_comment: bool,
) -> Option<String> {
let style = comment_style(orig, false);
let first_group = orig.lines()
let first_group = orig
.lines()
.take_while(|l| style.line_with_same_comment_style(l, false))
.collect::<Vec<_>>()
.join("\n");
let rest = orig.lines()
let rest = orig
.lines()
.skip(first_group.lines().count())
.collect::<Vec<_>>()
.join("\n");
@ -333,7 +336,8 @@ fn rewrite_comment_inner(
};
let line_breaks = count_newlines(orig.trim_right());
let lines = orig.lines()
let lines = orig
.lines()
.enumerate()
.map(|(i, mut line)| {
line = trim_right_unless_two_whitespaces(line.trim_left(), is_doc_comment);
@ -553,7 +557,8 @@ fn light_rewrite_comment(
config: &Config,
is_doc_comment: bool,
) -> Option<String> {
let lines: Vec<&str> = orig.lines()
let lines: Vec<&str> = orig
.lines()
.map(|l| {
// This is basically just l.trim(), but in the case that a line starts
// with `*` we want to leave one space before it, so it aligns with the

View File

@ -282,7 +282,8 @@ pub struct IgnoreList(HashSet<PathBuf>);
impl IgnoreList {
pub fn add_prefix(&mut self, dir: &Path) {
self.0 = self.0
self.0 = self
.0
.iter()
.map(|s| {
if s.has_root() {

View File

@ -455,7 +455,8 @@ where
width: context.budget(lhs_overhead),
..shape
};
let lhs_result = lhs.rewrite(context, lhs_shape)
let lhs_result = lhs
.rewrite(context, lhs_shape)
.map(|lhs_str| format!("{}{}", pp.prefix, lhs_str))?;
// Try to put both lhs and rhs on the same line.
@ -1036,7 +1037,8 @@ impl<'a> ControlFlow<'a> {
// `for event in event`
// Do not include label in the span.
let lo = self.label
let lo = self
.label
.map_or(self.span.lo(), |label| label.ident.span.hi());
let between_kwd_cond = mk_sp(
context
@ -1295,11 +1297,13 @@ pub fn rewrite_multiple_patterns(
pats: &[&ast::Pat],
shape: Shape,
) -> Option<String> {
let pat_strs = pats.iter()
let pat_strs = pats
.iter()
.map(|p| p.rewrite(context, shape))
.collect::<Option<Vec<_>>>()?;
let use_mixed_layout = pats.iter()
let use_mixed_layout = pats
.iter()
.zip(pat_strs.iter())
.all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();

View File

@ -170,7 +170,8 @@ fn main() {
env_logger::init();
let opts = make_opts();
let matches = opts.parse(env::args().skip(1))
let matches = opts
.parse(env::args().skip(1))
.expect("Couldn't parse command line");
let config = Config::from_args(&matches, &opts);

View File

@ -231,10 +231,12 @@ impl fmt::Display for UseTree {
impl UseTree {
// Rewrite use tree with `use ` and a trailing `;`.
pub fn rewrite_top_level(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
let vis = self.visibility
let vis = self
.visibility
.as_ref()
.map_or(Cow::from(""), |vis| ::utils::format_visibility(&vis));
let use_str = self.rewrite(context, shape.offset_left(vis.len())?)
let use_str = self
.rewrite(context, shape.offset_left(vis.len())?)
.map(|s| {
if s.is_empty() {
s.to_owned()
@ -448,7 +450,8 @@ impl UseTree {
// Recursively normalize elements of a list use (including sorting the list).
if let UseSegment::List(list) = last {
let mut list = list.into_iter()
let mut list = list
.into_iter()
.map(|ut| ut.normalize())
.collect::<Vec<_>>();
list.sort();
@ -530,7 +533,8 @@ impl UseTree {
fn merge(&mut self, other: UseTree) {
let mut new_path = vec![];
for (mut a, b) in self.path
for (mut a, b) in self
.path
.clone()
.iter_mut()
.zip(other.path.clone().into_iter())

View File

@ -142,7 +142,8 @@ impl<'a> Item<'a> {
keyword: "",
abi: format_abi(fm.abi, config.force_explicit_abi(), true),
vis: None,
body: fm.items
body: fm
.items
.iter()
.map(|i| BodyElement::ForeignItem(i))
.collect(),
@ -1725,7 +1726,8 @@ fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
impl Rewrite for ast::Arg {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
if is_named_arg(self) {
let mut result = self.pat
let mut result = self
.pat
.rewrite(context, Shape::legacy(shape.width, shape.indent))?;
if !is_empty_infer(context, &*self.ty) {
@ -1738,7 +1740,8 @@ impl Rewrite for ast::Arg {
}
let overhead = last_line_width(&result);
let max_width = shape.width.checked_sub(overhead)?;
let ty_str = self.ty
let ty_str = self
.ty
.rewrite(context, Shape::legacy(max_width, shape.indent))?;
result.push_str(&ty_str);
}
@ -1876,7 +1879,8 @@ fn rewrite_fn_base(
// Note that the width and indent don't really matter, we'll re-layout the
// return type later anyway.
let ret_str = fd.output
let ret_str = fd
.output
.rewrite(context, Shape::indented(indent, context.config))?;
let multi_line_ret_str = ret_str.contains('\n');
@ -2034,7 +2038,8 @@ fn rewrite_fn_base(
if multi_line_ret_str || ret_should_indent {
// Now that we know the proper indent and width, we need to
// re-layout the return type.
let ret_str = fd.output
let ret_str = fd
.output
.rewrite(context, Shape::indented(ret_indent, context.config))?;
result.push_str(&ret_str);
} else {
@ -2151,7 +2156,8 @@ fn rewrite_args(
variadic: bool,
generics_str_contains_newline: bool,
) -> Option<String> {
let mut arg_item_strs = args.iter()
let mut arg_item_strs = args
.iter()
.map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
.collect::<Option<Vec<_>>>()?;

View File

@ -165,7 +165,8 @@ impl FormattingError {
match self.kind {
ErrorKind::LineOverflow(found, max) => (max, found - max),
ErrorKind::TrailingWhitespace => {
let trailing_ws_start = self.line_buffer
let trailing_ws_start = self
.line_buffer
.rfind(|c: char| !c.is_whitespace())
.map(|pos| pos + 1)
.unwrap_or(0);

View File

@ -96,17 +96,20 @@ impl ListItem {
pub fn is_different_group(&self) -> bool {
self.inner_as_ref().contains('\n') || self.pre_comment.is_some()
|| self.post_comment
|| self
.post_comment
.as_ref()
.map_or(false, |s| s.contains('\n'))
}
pub fn is_multiline(&self) -> bool {
self.inner_as_ref().contains('\n')
|| self.pre_comment
|| self
.pre_comment
.as_ref()
.map_or(false, |s| s.contains('\n'))
|| self.post_comment
|| self
.post_comment
.as_ref()
.map_or(false, |s| s.contains('\n'))
}
@ -115,7 +118,8 @@ impl ListItem {
self.pre_comment
.as_ref()
.map_or(false, |comment| comment.trim_left().starts_with("//"))
|| self.post_comment
|| self
.post_comment
.as_ref()
.map_or(false, |comment| comment.trim_left().starts_with("//"))
}
@ -517,7 +521,8 @@ where
self.inner.next().map(|item| {
let mut new_lines = false;
// Pre-comment
let pre_snippet = self.snippet_provider
let pre_snippet = self
.snippet_provider
.span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
.unwrap();
let trimmed_pre_snippet = pre_snippet.trim();
@ -555,7 +560,8 @@ where
Some(next_item) => (self.get_lo)(next_item),
None => self.next_span_start,
};
let post_snippet = self.snippet_provider
let post_snippet = self
.snippet_provider
.span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
.unwrap();

View File

@ -291,7 +291,8 @@ impl<'a> FmtVisitor<'a> {
i += offset;
if c == '\n' {
let skip_this_line = !self.config
let skip_this_line = !self
.config
.file_lines()
.contains_line(file_name, status.cur_line);
if skip_this_line {

View File

@ -184,7 +184,8 @@ impl<'a, T: 'a + Rewrite + ToExpr + Spanned> Context<'a, T> {
}
fn items_span(&self) -> Span {
let span_lo = self.context
let span_lo = self
.context
.snippet_provider
.span_after(self.span, self.prefix);
mk_sp(span_lo, self.span.hi())
@ -288,7 +289,8 @@ impl<'a, T: 'a + Rewrite + ToExpr + Spanned> Context<'a, T> {
// formatted code, where a prefix or a suffix being left on its own
// line. Here we explicitlly check those cases.
if count_newlines(overflowed) == 1 {
let rw = self.items
let rw = self
.items
.last()
.and_then(|last_item| last_item.rewrite(self.context, self.nested_shape));
let no_newline = rw.as_ref().map_or(false, |s| !s.contains('\n'));
@ -305,7 +307,8 @@ impl<'a, T: 'a + Rewrite + ToExpr + Spanned> Context<'a, T> {
list_items[self.items.len() - 1].item = placeholder;
}
_ if self.items.len() >= 1 => {
list_items[self.items.len() - 1].item = self.items
list_items[self.items.len() - 1].item = self
.items
.last()
.and_then(|last_item| last_item.rewrite(self.context, self.nested_shape));
@ -427,7 +430,8 @@ impl<'a, T: 'a + Rewrite + ToExpr + Spanned> Context<'a, T> {
} else {
first_line_width(items_str) + (paren_overhead / 2)
};
let nested_indent_str = self.nested_shape
let nested_indent_str = self
.nested_shape
.indent
.to_string_with_newline(self.context.config);
let indent_str = shape

View File

@ -167,7 +167,8 @@ impl Rewrite for Pat {
rewrite_struct_pat(path, fields, ellipsis, self.span, context, shape)
}
PatKind::Mac(ref mac) => rewrite_macro(mac, None, context, shape, MacroPosition::Pat),
PatKind::Paren(ref pat) => pat.rewrite(context, shape.offset_left(1)?.sub_width(1)?)
PatKind::Paren(ref pat) => pat
.rewrite(context, shape.offset_left(1)?.sub_width(1)?)
.map(|inner_pat| format!("({})", inner_pat)),
}
}

View File

@ -628,7 +628,8 @@ impl ConfigurationSection {
Some((i, line)) => {
if line.starts_with("```rust") {
// Get the lines of the code block.
let lines: Vec<String> = file.map(|(_i, l)| l)
let lines: Vec<String> = file
.map(|(_i, l)| l)
.take_while(|l| !l.starts_with("```"))
.collect();
let block = format!("{}\n", lines.join("\n"));
@ -699,7 +700,8 @@ impl ConfigCodeBlock {
assert!(self.code_block.is_some() && self.code_block_start.is_some());
// See if code block begins with #![rustfmt_skip].
let fmt_skip = self.code_block
let fmt_skip = self
.code_block
.as_ref()
.unwrap()
.split('\n')

View File

@ -234,7 +234,8 @@ fn rewrite_segment(
|| !data.types.is_empty()
|| !data.bindings.is_empty() =>
{
let param_list = data.lifetimes
let param_list = data
.lifetimes
.iter()
.map(SegmentParam::LifeTime)
.chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
@ -574,7 +575,8 @@ impl Rewrite for ast::PolyTraitRef {
{
// 6 is "for<> ".len()
let extra_offset = lifetime_str.len() + 6;
let path_str = self.trait_ref
let path_str = self
.trait_ref
.rewrite(context, shape.offset_left(extra_offset)?)?;
Some(
@ -717,7 +719,8 @@ impl Rewrite for ast::Ty {
rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
}
ast::TyKind::ImplicitSelf => Some(String::from("")),
ast::TyKind::ImplTrait(ref it) => it.rewrite(context, shape)
ast::TyKind::ImplTrait(ref it) => it
.rewrite(context, shape)
.map(|it_str| format!("impl {}", it_str)),
ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
}

View File

@ -29,7 +29,8 @@ const SKIP_ANNOTATION: &str = "rustfmt_skip";
pub fn extra_offset(text: &str, shape: Shape) -> usize {
match text.rfind('\n') {
// 1 for newline character
Some(idx) => text.len()
Some(idx) => text
.len()
.checked_sub(idx + 1 + shape.used_width())
.unwrap_or(0),
None => text.len(),

View File

@ -687,7 +687,8 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
}
pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
while let Some(pos) = self.snippet_provider
while let Some(pos) = self
.snippet_provider
.opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
{
if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {