Source formatting fallout

This commit is contained in:
Nick Cameron 2017-03-28 10:58:41 +13:00
parent 038436919d
commit e4efa22983
13 changed files with 101 additions and 73 deletions

View file

@ -96,7 +96,8 @@ fn format_crate(verbosity: Verbosity) -> Result<ExitStatus, std::io::Error> {
let targets = try!(get_targets());
// Currently only bin and lib files get formatted
let files: Vec<_> = targets.into_iter()
let files: Vec<_> = targets
.into_iter()
.filter(|t| t.kind.should_format())
.inspect(|t| if verbosity == Verbosity::Verbose {
println!("[{:?}] {:?}", t.kind, t.path)
@ -165,11 +166,13 @@ fn get_targets() -> Result<Vec<Target>, std::io::Error> {
fn target_from_json(jtarget: &Json) -> Target {
let jtarget = jtarget.as_object().unwrap();
let path = PathBuf::from(jtarget.get("src_path")
let path = PathBuf::from(jtarget
.get("src_path")
.unwrap()
.as_string()
.unwrap());
let kinds = jtarget.get("kind")
let kinds = jtarget
.get("kind")
.unwrap()
.as_array()
.unwrap();

View file

@ -226,7 +226,8 @@ fn execute(opts: &Options) -> FmtResult<Summary> {
let options = try!(CliOptions::from_matches(&matches));
// Add any additional files that were specified via `--file-lines`.
files.extend(options.file_lines
files.extend(options
.file_lines
.files()
.cloned()
.map(PathBuf::from));
@ -338,7 +339,8 @@ fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
}
// Read the config_path and convert to parent dir if a file is provided.
let config_path: Option<PathBuf> = matches.opt_str("config-path")
let config_path: Option<PathBuf> = matches
.opt_str("config-path")
.map(PathBuf::from)
.and_then(|dir| {
if dir.is_file() {
@ -360,7 +362,8 @@ fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
}
// We append files from `--file-lines` later in `execute()`.
let files: Vec<_> = matches.free
let files: Vec<_> = matches
.free
.iter()
.map(PathBuf::from)
.collect();

View file

@ -113,8 +113,9 @@ pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -
} else {
chain_indent(context, shape.add_offset(parent_rewrite.len()))
};
(nested_shape, context.config.chain_indent == IndentStyle::Visual ||
parent_rewrite.len() <= context.config.tab_spaces)
(nested_shape,
context.config.chain_indent == IndentStyle::Visual ||
parent_rewrite.len() <= context.config.tab_spaces)
} else if is_block_expr(&parent, &parent_rewrite) {
// The parent is a block, so align the rest of the chain with the closing
// brace.
@ -425,7 +426,8 @@ fn rewrite_method_call(method_name: ast::Ident,
format!("::<{}>", type_list.join(", "))
};
(types.last()
(types
.last()
.unwrap()
.span
.hi,

View file

@ -360,7 +360,8 @@ pub fn rewrite_array<'a, I>(expr_iter: I,
}
}
let has_long_item = try_opt!(items.iter()
let has_long_item = try_opt!(items
.iter()
.map(|li| li.item.as_ref().map(|s| s.len() > 10))
.fold(Some(false),
|acc, x| acc.and_then(|y| x.map(|x| x || y))));
@ -1308,7 +1309,8 @@ impl Rewrite for ast::Arm {
// Let's try and get the arm body on the same line as the condition.
// 4 = ` => `.len()
if shape.width > pat_width + comma.len() + 4 {
let arm_shape = shape.shrink_left(pat_width + 4)
let arm_shape = shape
.shrink_left(pat_width + 4)
.unwrap()
.sub_width(comma.len())
.unwrap()
@ -1404,7 +1406,8 @@ fn rewrite_guard(context: &RewriteContext,
// 4 = ` if `, 5 = ` => {`
let overhead = pattern_width + 4 + 5;
if overhead < shape.width {
let cond_shape = shape.shrink_left(pattern_width + 4)
let cond_shape = shape
.shrink_left(pattern_width + 4)
.unwrap()
.sub_width(5)
.unwrap();
@ -1424,7 +1427,8 @@ fn rewrite_guard(context: &RewriteContext,
3));
if let Some(cond_str) = cond_str {
return Some(format!("\n{}if {}",
shape.indent
shape
.indent
.block_indent(context.config)
.to_string(context.config),
cond_str));
@ -1538,7 +1542,8 @@ fn string_requires_rewrite(context: &RewriteContext,
string: &str,
shape: Shape)
-> bool {
if context.codemap
if context
.codemap
.lookup_char_pos(span.lo)
.col
.0 != shape.indent.width() {
@ -1610,7 +1615,8 @@ fn rewrite_call_inner<R>(context: &RewriteContext,
let nested_shape = match context.config.fn_call_style {
IndentStyle::Block => {
shape.block()
shape
.block()
.block_indent(context.config.tab_spaces)
.sub_width(context.config.tab_spaces)
}
@ -1781,9 +1787,9 @@ fn rewrite_struct_lit<'a>(context: &RewriteContext,
return Some(format!("{} {{}}", path_str));
}
let field_iter = fields.into_iter()
.map(StructLitField::Regular)
.chain(base.into_iter().map(StructLitField::Base));
let field_iter =
fields.into_iter().map(StructLitField::Regular).chain(base.into_iter()
.map(StructLitField::Base));
// Foo { a: Foo } - indent is +3, width is -5.
let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
@ -1895,7 +1901,8 @@ pub fn rewrite_tuple<'a, I>(context: &RewriteContext,
if items.len() == 1 {
// 3 = "(" + ",)"
let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
return items.next()
return items
.next()
.unwrap()
.rewrite(context, nested_shape)
.map(|s| if context.config.spaces_within_parens {

View file

@ -191,7 +191,8 @@ impl<'a> FmtVisitor<'a> {
pub fn format_imports(&mut self, use_items: &[ptr::P<ast::Item>]) {
// Find the location immediately before the first use item in the run. This must not lie
// before the current `self.last_pos`
let pos_before_first_use_item = use_items.first()
let pos_before_first_use_item = use_items
.first()
.map(|p_i| {
cmp::max(self.last_pos,
p_i.attrs
@ -204,7 +205,8 @@ impl<'a> FmtVisitor<'a> {
// Construct a list of pairs, each containing a `use` item and the start of span before
// that `use` item.
let mut last_pos_of_prev_use_item = pos_before_first_use_item;
let mut ordered_use_items = use_items.iter()
let mut ordered_use_items = use_items
.iter()
.map(|p_i| {
let new_item = (&*p_i, last_pos_of_prev_use_item);
last_pos_of_prev_use_item = p_i.span.hi;

View file

@ -1129,7 +1129,8 @@ pub fn rewrite_type_alias(context: &RewriteContext,
let line_width = last_line_width(&result);
// This checked_sub may fail as the extra space after '=' is not taken into account
// In that case the budget is set to 0 which will make ty.rewrite retry on a new line
let budget = context.config
let budget = context
.config
.max_width
.checked_sub(indent.width() + line_width + ";".len())
.unwrap_or(0);
@ -1720,12 +1721,12 @@ fn rewrite_args(context: &RewriteContext,
// Account for sugary self.
// FIXME: the comment for the self argument is dropped. This is blocked
// on rust issue #27522.
let min_args =
explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
.map_or(1, |self_str| {
arg_item_strs[0] = self_str;
2
});
let min_args = explicit_self
.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
.map_or(1, |self_str| {
arg_item_strs[0] = self_str;
2
});
// Comments between args.
let mut arg_items = Vec::new();
@ -1852,7 +1853,8 @@ fn compute_budgets_for_args(context: &RewriteContext,
if !newline_brace {
used_space += 2;
}
let one_line_budget = context.config
let one_line_budget = context
.config
.max_width
.checked_sub(used_space)
.unwrap_or(0);
@ -1962,7 +1964,8 @@ fn rewrite_trait_bounds(context: &RewriteContext,
return Some(String::new());
}
let bound_str = try_opt!(bounds.iter()
let bound_str = try_opt!(bounds
.iter()
.map(|ty_bound| ty_bound.rewrite(&context, shape))
.intersperse(Some(" + ".to_string()))
.collect::<Option<String>>());

View file

@ -275,7 +275,8 @@ pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
// 1 = space between item and comment.
let width = formatting.shape
let width = formatting
.shape
.width
.checked_sub(item_last_line_width + 1)
.unwrap_or(1);
@ -397,8 +398,8 @@ impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
let first_newline = test_snippet.find('\n').unwrap_or(test_snippet.len());
// From the end of the first line of comments.
let test_snippet = &test_snippet[first_newline..];
let first = test_snippet.find(|c: char| !c.is_whitespace())
.unwrap_or(test_snippet.len());
let first =
test_snippet.find(|c: char| !c.is_whitespace()).unwrap_or(test_snippet.len());
// From the end of the first line of comments to the next non-whitespace char.
let test_snippet = &test_snippet[..first];

View file

@ -156,13 +156,13 @@ pub fn rewrite_macro(mac: &ast::Mac,
// Format macro invocation as array literal.
let extra_offset = macro_name.len();
let shape = try_opt!(shape.shrink_left(extra_offset));
let rewrite = try_opt!(rewrite_array(expr_vec.iter().map(|x| &**x),
mk_sp(context.codemap
.span_after(mac.span,
original_style.opener()),
mac.span.hi - BytePos(1)),
context,
shape));
let rewrite =
try_opt!(rewrite_array(expr_vec.iter().map(|x| &**x),
mk_sp(context.codemap.span_after(mac.span,
original_style.opener()),
mac.span.hi - BytePos(1)),
context,
shape));
Some(format!("{}{}", macro_name, rewrite))
}

View file

@ -83,7 +83,8 @@ impl<'a> FmtVisitor<'a> {
let local_end = self.codemap.lookup_byte_offset(span.hi);
let start_index = local_begin.pos.to_usize();
let end_index = local_end.pos.to_usize();
let big_snippet = &local_begin.fm
let big_snippet = &local_begin
.fm
.src
.as_ref()
.unwrap()

View file

@ -42,7 +42,8 @@ pub fn rewrite_string<'a>(orig: &str, fmt: &StringFormat<'a>) -> Option<String>
// `cur_start` is the position in `orig` of the start of the current line.
let mut cur_start = 0;
let mut result = String::with_capacity(stripped_str.len()
let mut result = String::with_capacity(stripped_str
.len()
.checked_next_power_of_two()
.unwrap_or(usize::max_value()));
result.push_str(fmt.opener);

View file

@ -206,7 +206,8 @@ fn rewrite_segment(path_context: PathContext,
.chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
.collect::<Vec<_>>();
let next_span_lo = param_list.last()
let next_span_lo = param_list
.last()
.unwrap()
.get_span()
.hi + BytePos(1);
@ -297,28 +298,28 @@ fn format_function_type<'a, I>(inputs: I,
// 1 for (
let offset = shape.indent + 1;
let list_lo = context.codemap.span_after(span, "(");
let items = itemize_list(context.codemap,
// FIXME Would be nice to avoid this allocation,
// but I couldn't get the types to work out.
inputs.map(|i| ArgumentKind::Regular(Box::new(i)))
.chain(variadic_arg),
")",
|arg| match *arg {
ArgumentKind::Regular(ref ty) => ty.span().lo,
ArgumentKind::Variadic(start) => start,
},
|arg| match *arg {
ArgumentKind::Regular(ref ty) => ty.span().hi,
ArgumentKind::Variadic(start) => start + BytePos(3),
},
|arg| match *arg {
ArgumentKind::Regular(ref ty) => {
ty.rewrite(context, Shape::legacy(budget, offset))
}
ArgumentKind::Variadic(_) => Some("...".to_owned()),
},
list_lo,
span.hi);
let items =
itemize_list(context.codemap,
// FIXME Would be nice to avoid this allocation,
// but I couldn't get the types to work out.
inputs.map(|i| ArgumentKind::Regular(Box::new(i))).chain(variadic_arg),
")",
|arg| match *arg {
ArgumentKind::Regular(ref ty) => ty.span().lo,
ArgumentKind::Variadic(start) => start,
},
|arg| match *arg {
ArgumentKind::Regular(ref ty) => ty.span().hi,
ArgumentKind::Variadic(start) => start + BytePos(3),
},
|arg| match *arg {
ArgumentKind::Regular(ref ty) => {
ty.rewrite(context, Shape::legacy(budget, offset))
}
ArgumentKind::Variadic(_) => Some("...".to_owned()),
},
list_lo,
span.hi);
let list_str = try_opt!(format_fn_args(items, Shape::legacy(budget, offset), context.config));
@ -680,7 +681,8 @@ fn rewrite_bare_fn(bare_fn: &ast::BareFnTy,
// 6 = "for<> ".len(), 4 = "for<".
// This doesn't work out so nicely for mutliline situation with lots of
// rightward drift. If that is a problem, we could use the list stuff.
result.push_str(&try_opt!(bare_fn.lifetimes
result.push_str(&try_opt!(bare_fn
.lifetimes
.iter()
.map(|l| {
l.rewrite(context,

View file

@ -127,7 +127,8 @@ pub fn contains_skip(attrs: &[Attribute]) -> bool {
// Find the end of a TyParam
#[inline]
pub fn end_typaram(typaram: &ast::TyParam) -> BytePos {
typaram.bounds
typaram
.bounds
.last()
.map_or(typaram.span, |bound| match *bound {
ast::RegionTyParamBound(ref lt) => lt.span,
@ -278,7 +279,8 @@ pub fn wrap_str<S: AsRef<str>>(s: S, max_width: usize, shape: Shape) -> Option<S
// indentation.
// A special check for the last line, since the caller may
// place trailing characters on this line.
if snippet.lines()
if snippet
.lines()
.rev()
.next()
.unwrap()

View file

@ -476,7 +476,8 @@ impl<'a> FmtVisitor<'a> {
return true;
}
let outers: Vec<_> = attrs.iter()
let outers: Vec<_> = attrs
.iter()
.filter(|a| a.style == ast::AttrStyle::Outer)
.cloned()
.collect();
@ -487,10 +488,10 @@ impl<'a> FmtVisitor<'a> {
let first = &outers[0];
self.format_missing_with_indent(source!(self, first.span).lo);
let rewrite = outers.rewrite(&self.get_context(),
Shape::legacy(self.config.max_width -
self.block_indent.width(),
self.block_indent))
let rewrite = outers
.rewrite(&self.get_context(),
Shape::legacy(self.config.max_width - self.block_indent.width(),
self.block_indent))
.unwrap();
self.buffer.push_str(&rewrite);
let last = outers.last().unwrap();