test fallout

This commit is contained in:
Nick Cameron 2017-03-28 11:25:59 +13:00
parent a8692797ae
commit 5305bc8436
24 changed files with 132 additions and 313 deletions

View File

@ -110,10 +110,7 @@ fn format_crate(verbosity: Verbosity) -> Result<ExitStatus, std::io::Error> {
fn get_fmt_args() -> Vec<String> {
// All arguments after -- are passed to rustfmt
env::args()
.skip_while(|a| a != "--")
.skip(1)
.collect()
env::args().skip_while(|a| a != "--").skip(1).collect()
}
#[derive(Debug)]
@ -146,17 +143,12 @@ pub struct Target {
// Returns a vector of all compile targets of a crate
fn get_targets() -> Result<Vec<Target>, std::io::Error> {
let mut targets: Vec<Target> = vec![];
let output = try!(Command::new("cargo")
.arg("read-manifest")
.output());
let output = try!(Command::new("cargo").arg("read-manifest").output());
if output.status.success() {
// None of the unwraps should fail if output of `cargo read-manifest` is correct
let data = &String::from_utf8(output.stdout).unwrap();
let json = Json::from_str(data).unwrap();
let jtargets = json.find("targets")
.unwrap()
.as_array()
.unwrap();
let jtargets = json.find("targets").unwrap().as_array().unwrap();
for jtarget in jtargets {
targets.push(target_from_json(jtarget));
}
@ -171,16 +163,8 @@ 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")
.unwrap()
.as_string()
.unwrap());
let kinds = jtarget
.get("kind")
.unwrap()
.as_array()
.unwrap();
let path = PathBuf::from(jtarget.get("src_path").unwrap().as_string().unwrap());
let kinds = jtarget.get("kind").unwrap().as_array().unwrap();
let kind = match kinds[0].as_string().unwrap() {
"bin" => TargetKind::Bin,
"lib" | "dylib" | "staticlib" | "cdylib" | "rlib" => TargetKind::Lib,

View File

@ -226,11 +226,7 @@ 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()
.cloned()
.map(PathBuf::from));
files.extend(options.file_lines.files().cloned().map(PathBuf::from));
let mut config = Config::default();
let mut path = None;
@ -311,10 +307,7 @@ fn main() {
fn print_usage(opts: &Options, reason: &str) {
let reason = format!("{}\nusage: {} [options] <file>...",
reason,
env::args_os()
.next()
.unwrap()
.to_string_lossy());
env::args_os().next().unwrap().to_string_lossy());
println!("{}", opts.usage(&reason));
}
@ -365,11 +358,7 @@ fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
}
// We append files from `--file-lines` later in `execute()`.
let files: Vec<_> = matches
.free
.iter()
.map(PathBuf::from)
.collect();
let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
Ok(Operation::Format {
files: files,

View File

@ -160,10 +160,7 @@ pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -
Some(first_child_shape)
.into_iter()
.chain(::std::iter::repeat(other_child_shape).take(subexpr_list.len() - 1));
let iter = subexpr_list
.iter()
.rev()
.zip(child_shape_iter);
let iter = subexpr_list.iter().rev().zip(child_shape_iter);
let mut rewrites =
try_opt!(iter.map(|(e, shape)| rewrite_chain_subexpr(e, total_span, context, shape))
.collect::<Option<Vec<_>>>());
@ -182,14 +179,9 @@ pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -
// line, we won't consider putting them on a single line either.
let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
let first_span = context.snippet(subexpr_list[1].span);
let last_iter = last_span
.chars()
.take_while(|c| c.is_whitespace());
let last_iter = last_span.chars().take_while(|c| c.is_whitespace());
first_span
.chars()
.chain(last_iter)
.any(|c| c == '\n')
first_span.chars().chain(last_iter).any(|c| c == '\n')
} else {
false
};
@ -258,9 +250,7 @@ pub fn rewrite_try(expr: &ast::Expr,
let sub_expr = try_opt!(expr.rewrite(context, try_opt!(shape.sub_width(try_count))));
Some(format!("{}{}",
sub_expr,
iter::repeat("?")
.take(try_count)
.collect::<String>()))
iter::repeat("?").take(try_count).collect::<String>()))
}
fn join_rewrites(rewrites: &[String], subexps: &[ast::Expr], connector: &str) -> String {

View File

@ -340,11 +340,7 @@ pub fn rewrite_array<'a, I>(expr_iter: I,
};
let nested_shape = match context.config.array_layout {
IndentStyle::Block => {
shape
.block()
.block_indent(context.config.tab_spaces)
}
IndentStyle::Block => shape.block().block_indent(context.config.tab_spaces),
IndentStyle::Visual => {
try_opt!(shape
.visual_indent(bracket_size)
@ -902,10 +898,7 @@ impl<'a> Rewrite for ControlFlow<'a> {
label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
};
let block_width = shape
.width
.checked_sub(used_width)
.unwrap_or(0);
let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
// This is used only for the empty block case: `{}`. So, we use 1 if we know
// we should avoid the single line case.
let block_width = if self.else_block.is_some() || self.nested_if {
@ -946,10 +939,7 @@ impl<'a> Rewrite for ControlFlow<'a> {
extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
let alt_block_sep = String::from("\n") +
&shape
.indent
.block_only()
.to_string(context.config);
&shape.indent.block_only().to_string(context.config);
let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
""
} else if context.config.control_brace_style ==
@ -972,9 +962,7 @@ impl<'a> Rewrite for ControlFlow<'a> {
},
|s| &**s),
pat_expr_string,
after_cond_comment
.as_ref()
.map_or(block_sep, |s| &**s),
after_cond_comment.as_ref().map_or(block_sep, |s| &**s),
block_str);
if let Some(else_block) = self.else_block {
@ -1048,9 +1036,7 @@ impl<'a> Rewrite for ControlFlow<'a> {
between_kwd_else_block_comment
.as_ref()
.map_or(between_sep, |s| &**s),
after_else_comment
.as_ref()
.map_or(after_sep, |s| &**s))
after_else_comment.as_ref().map_or(after_sep, |s| &**s))
.ok());
result.push_str(&try_opt!(rewrite));
}
@ -1132,9 +1118,7 @@ fn rewrite_match_arm_comment(context: &RewriteContext,
let mut result = String::new();
// any text not preceeded by a newline is pushed unmodified to the block
let first_brk = missed_str
.find(|c: char| c == '\n')
.unwrap_or(0);
let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
result.push_str(&missed_str[..first_brk]);
let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
@ -1174,11 +1158,7 @@ fn rewrite_match(context: &RewriteContext,
let cond_shape = try_opt!(shape.shrink_left(6));
let cond_shape = try_opt!(cond_shape.sub_width(2));
let cond_str = try_opt!(cond.rewrite(context, cond_shape));
let alt_block_sep = String::from("\n") +
&shape
.indent
.block_only()
.to_string(context.config);
let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
let block_sep = match context.config.control_brace_style {
ControlBraceStyle::AlwaysSameLine => " ",
_ => alt_block_sep.as_str(),
@ -1305,10 +1285,7 @@ impl Rewrite for ast::Arm {
.collect::<Option<Vec<_>>>());
let all_simple = pat_strs.iter().all(|p| pat_is_simple(p));
let items: Vec<_> = pat_strs
.into_iter()
.map(ListItem::from_str)
.collect();
let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
let fmt = ListFormatting {
tactic: if all_simple {
DefinitiveListTactic::Mixed
@ -1354,10 +1331,7 @@ impl Rewrite for ast::Arm {
let comma = arm_comma(&context.config, body);
let alt_block_sep = String::from("\n") +
&shape
.indent
.block_only()
.to_string(context.config);
&shape.indent.block_only().to_string(context.config);
let pat_width = extra_offset(&pats_str, shape);
// Let's try and get the arm body on the same line as the condition.
@ -1447,10 +1421,7 @@ impl Rewrite for ast::Arm {
// E.g. `Foo::Bar` is simple, but `Foo(..)` is not.
fn pat_is_simple(pat_str: &str) -> bool {
pat_str.len() <= 16 ||
(pat_str.len() <= 24 &&
pat_str
.chars()
.all(|c| c.is_alphabetic() || c == ':'))
(pat_str.len() <= 24 && pat_str.chars().all(|c| c.is_alphabetic() || c == ':'))
}
// The `if ...` guard on a match arm.
@ -1478,10 +1449,7 @@ fn rewrite_guard(context: &RewriteContext,
}
// Not enough space to put the guard after the pattern, try a newline.
let overhead = shape
.indent
.block_indent(context.config)
.width() + 4 + 5;
let overhead = shape.indent.block_indent(context.config).width() + 4 + 5;
if overhead < shape.width {
let cond_str = guard.rewrite(context,
Shape::legacy(shape.width - overhead,
@ -1556,10 +1524,7 @@ fn rewrite_pat_expr(context: &RewriteContext,
}
}
let nested_indent = shape
.indent
.block_only()
.block_indent(context.config);
let nested_indent = shape.indent.block_only().block_indent(context.config);
// The expression won't fit on the current line, jump to next.
result.push('\n');
@ -1608,11 +1573,7 @@ fn string_requires_rewrite(context: &RewriteContext,
string: &str,
shape: Shape)
-> bool {
if context
.codemap
.lookup_char_pos(span.lo)
.col
.0 != shape.indent.width() {
if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
return true;
}
@ -1728,9 +1689,7 @@ fn rewrite_call_inner<R>(context: &RewriteContext,
indent: nested_shape.indent.block_only(),
..nested_shape
};
let rewrite = args.last()
.unwrap()
.rewrite(context, nested_shape);
let rewrite = args.last().unwrap().rewrite(context, nested_shape);
if let Some(rewrite) = rewrite {
let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
@ -1875,9 +1834,7 @@ fn rewrite_struct_lit<'a>(context: &RewriteContext,
let span_lo = |item: &StructLitField| match *item {
StructLitField::Regular(field) => field.span.lo,
StructLitField::Base(expr) => {
let last_field_hi = fields
.last()
.map_or(span.lo, |field| field.span.hi);
let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
let pos = snippet.find_uncommented("..").unwrap();
last_field_hi + BytePos(pos as u32)

View File

@ -127,11 +127,7 @@ impl FileLines {
map.get_vec(&canonical)
.ok_or(())
}) {
Ok(ranges) => {
ranges
.iter()
.any(|r| r.contains(Range::from(range)))
}
Ok(ranges) => ranges.iter().any(|r| r.contains(Range::from(range))),
Err(_) => false,
}
}
@ -146,11 +142,7 @@ impl FileLines {
match map.get_vec(range.file_name()) {
None => false,
Some(ranges) => {
ranges
.iter()
.any(|r| r.intersects(Range::from(range)))
}
Some(ranges) => ranges.iter().any(|r| r.intersects(Range::from(range))),
}
}
}
@ -168,12 +160,7 @@ impl<'a> iter::Iterator for Files<'a> {
fn canonicalize_path_string(s: &str) -> Result<String, ()> {
match path::PathBuf::from(s).canonicalize() {
Ok(canonicalized) => {
canonicalized
.to_str()
.map(|s| s.to_string())
.ok_or(())
}
Ok(canonicalized) => canonicalized.to_str().map(|s| s.to_string()).ok_or(()),
_ => Err(()),
}
}
@ -184,9 +171,7 @@ impl str::FromStr for FileLines {
fn from_str(s: &str) -> Result<FileLines, String> {
let v: Vec<JsonSpan> = try!(json::decode(s).map_err(|e| e.to_string()));
let m = try!(v.into_iter()
.map(JsonSpan::into_tuple)
.collect());
let m = try!(v.into_iter().map(JsonSpan::into_tuple).collect());
Ok(FileLines::from_multimap(m))
}
}

View File

@ -65,12 +65,7 @@ fn compare_path_list_items(a: &ast::PathListItem, b: &ast::PathListItem) -> Orde
match a.node.rename {
Some(a_rename) => {
match b.node.rename {
Some(b_rename) => {
a_rename
.name
.as_str()
.cmp(&b_rename.name.as_str())
}
Some(b_rename) => a_rename.name.as_str().cmp(&b_rename.name.as_str()),
None => Ordering::Greater,
}
}
@ -135,11 +130,8 @@ fn rewrite_view_path_prefix(path: &ast::Path,
context: &RewriteContext,
shape: Shape)
-> Option<String> {
let path_str = if path.segments
.last()
.unwrap()
.identifier
.to_string() == "self" && path.segments.len() > 1 {
let path_str = if path.segments.last().unwrap().identifier.to_string() == "self" &&
path.segments.len() > 1 {
let path = &ast::Path {
span: path.span.clone(),
segments: path.segments[..path.segments.len() - 1].to_owned(),

View File

@ -225,15 +225,12 @@ fn find_unnumbered_issue() {
fn check_fail(text: &str, failing_pos: usize) {
let mut seeker = BadIssueSeeker::new(ReportTactic::Unnumbered, ReportTactic::Unnumbered);
assert_eq!(Some(failing_pos),
text.chars()
.position(|c| seeker.inspect(c).is_some()));
text.chars().position(|c| seeker.inspect(c).is_some()));
}
fn check_pass(text: &str) {
let mut seeker = BadIssueSeeker::new(ReportTactic::Unnumbered, ReportTactic::Unnumbered);
assert_eq!(None,
text.chars()
.position(|c| seeker.inspect(c).is_some()));
assert_eq!(None, text.chars().position(|c| seeker.inspect(c).is_some()));
}
check_fail("TODO\n", 4);
@ -253,8 +250,7 @@ fn find_unnumbered_issue() {
fn find_issue() {
fn is_bad_issue(text: &str, report_todo: ReportTactic, report_fixme: ReportTactic) -> bool {
let mut seeker = BadIssueSeeker::new(report_todo, report_fixme);
text.chars()
.any(|c| seeker.inspect(c).is_some())
text.chars().any(|c| seeker.inspect(c).is_some())
}
assert!(is_bad_issue("TODO(@maintainer, #1222, hello)\n",

View File

@ -370,8 +370,7 @@ impl<'a> FmtVisitor<'a> {
enum_def: &ast::EnumDef,
generics: &ast::Generics,
span: Span) {
self.buffer
.push_str(&format_header("enum ", ident, vis));
self.buffer.push_str(&format_header("enum ", ident, vis));
let enum_snippet = self.snippet(span);
let brace_pos = enum_snippet.find_uncommented("{").unwrap();
@ -584,9 +583,7 @@ pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -
if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
visitor.block_indent = offset
.block_only()
.block_indent(context.config);
visitor.block_indent = offset.block_only().block_indent(context.config);
visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
for item in items {
@ -665,10 +662,7 @@ fn format_impl_ref_and_type(context: &RewriteContext,
result.push_str(" ");
}
let used_space = last_line_width(&result);
let budget = try_opt!(context
.config
.max_width
.checked_sub(used_space));
let budget = try_opt!(context.config.max_width.checked_sub(used_space));
let indent = offset + used_space;
result.push_str(&*try_opt!(trait_ref.rewrite(context, Shape::legacy(budget, indent))));
@ -698,10 +692,7 @@ fn format_impl_ref_and_type(context: &RewriteContext,
}
// 1 = space before the type.
let budget = try_opt!(context
.config
.max_width
.checked_sub(used_space + 1));
let budget = try_opt!(context.config.max_width.checked_sub(used_space + 1));
let indent = offset + result.len() + 1;
let self_ty_str = self_ty.rewrite(context, Shape::legacy(budget, indent));
if let Some(self_ty_str) = self_ty_str {
@ -713,10 +704,7 @@ fn format_impl_ref_and_type(context: &RewriteContext,
// Can't fit the self type on what's left of the line, so start a new one.
let indent = offset.block_indent(context.config);
result.push_str(&format!("\n{}", indent.to_string(context.config)));
let budget = try_opt!(context
.config
.max_width
.checked_sub(indent.width()));
let budget = try_opt!(context.config.max_width.checked_sub(indent.width()));
result.push_str(&*try_opt!(self_ty.rewrite(context, Shape::legacy(budget, indent))));
Some(result)
} else {
@ -790,9 +778,7 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent)
if offset.width() + last_line_width(&result) + trait_bound_str.len() >
context.config.comment_width {
result.push('\n');
let trait_indent = offset
.block_only()
.block_indent(context.config);
let trait_indent = offset.block_only().block_indent(context.config);
result.push_str(&trait_indent.to_string(context.config));
}
result.push_str(&trait_bound_str);
@ -860,9 +846,7 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent)
if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
visitor.block_indent = offset
.block_only()
.block_indent(context.config);
visitor.block_indent = offset.block_only().block_indent(context.config);
visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
for item in trait_items {
@ -1060,10 +1044,7 @@ fn format_tuple_struct(context: &RewriteContext,
(ListTactic::HorizontalVertical, offset.block_only() + result.len() + 1)
}
IndentStyle::Block => {
(ListTactic::HorizontalVertical,
offset
.block_only()
.block_indent(&context.config))
(ListTactic::HorizontalVertical, offset.block_only().block_indent(&context.config))
}
};
// 3 = `();`
@ -1379,9 +1360,7 @@ impl Rewrite for ast::Arg {
result.push_str(" ");
}
result.push_str(":");
if context
.config
.space_after_type_annotation_colon {
if context.config.space_after_type_annotation_colon {
result.push_str(" ");
}
let max_width = try_opt!(shape.width.checked_sub(result.len()));
@ -1695,10 +1674,7 @@ fn rewrite_fn_base(context: &RewriteContext,
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 budget = try_opt!(context
.config
.max_width
.checked_sub(ret_indent.width()));
let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
let ret_str = try_opt!(fd.output
.rewrite(context, Shape::legacy(budget, ret_indent)));
result.push_str(&ret_str);
@ -1821,9 +1797,7 @@ fn rewrite_args(context: &RewriteContext,
};
let reduced_span = mk_sp(span.lo, second_arg_start);
context
.codemap
.span_after_last(reduced_span, ",")
context.codemap.span_after_last(reduced_span, ",")
} else {
span.lo
};
@ -1835,9 +1809,7 @@ fn rewrite_args(context: &RewriteContext,
let variadic_arg = if variadic {
let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
let variadic_start = context
.codemap
.span_after(variadic_span, "...") - BytePos(3);
let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
Some(ArgumentKind::Variadic(variadic_start))
} else {
None
@ -1879,10 +1851,7 @@ fn rewrite_args(context: &RewriteContext,
};
let tactic = definitive_tactic(&arg_items,
context
.config
.fn_args_density
.to_list_tactic(),
context.config.fn_args_density.to_list_tactic(),
one_line_budget);
let budget = match tactic {
DefinitiveListTactic::Horizontal => one_line_budget,
@ -1988,9 +1957,7 @@ fn rewrite_generics(context: &RewriteContext,
IndentStyle::Visual => generics_offset + 1,
};
let h_budget = try_opt!(shape
.width
.checked_sub(generics_offset.width() + 2));
let h_budget = try_opt!(shape.width.checked_sub(generics_offset.width() + 2));
// FIXME: might need to insert a newline if the generics are really long.
// Strings for the generics.
@ -2014,9 +1981,7 @@ fn rewrite_generics(context: &RewriteContext,
let ty_spans = tys.iter().map(span_for_ty_param);
let items = itemize_list(context.codemap,
lt_spans
.chain(ty_spans)
.zip(lt_strs.chain(ty_strs)),
lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
">",
|&(sp, _)| sp.lo,
|&(sp, _)| sp.hi,

View File

@ -536,9 +536,7 @@ fn format_lines(text: &mut StringBuffer, name: &str, config: &Config, report: &m
});
}
report
.file_error_map
.insert(name.to_owned(), errors);
report.file_error_map.insert(name.to_owned(), errors);
}
fn parse_input(input: Input,

View File

@ -118,9 +118,7 @@ pub struct ListItem {
impl ListItem {
pub fn is_multiline(&self) -> bool {
self.item
.as_ref()
.map_or(false, |s| s.contains('\n')) || self.pre_comment.is_some() ||
self.item.as_ref().map_or(false, |s| s.contains('\n')) || self.pre_comment.is_some() ||
self.post_comment
.as_ref()
.map_or(false, |s| s.contains('\n'))
@ -199,10 +197,7 @@ pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
let mut iter = items.into_iter().enumerate().peekable();
let mut line_len = 0;
let indent_str = &formatting
.shape
.indent
.to_string(formatting.config);
let indent_str = &formatting.shape.indent.to_string(formatting.config);
while let Some((i, item)) = iter.next() {
let item = item.as_ref();
let inner_item = try_opt!(item.item.as_ref());
@ -412,9 +407,7 @@ impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
// Everything from the separator to the next item.
let test_snippet = &post_snippet[comment_end - 1..];
let first_newline = test_snippet
.find('\n')
.unwrap_or(test_snippet.len());
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
@ -423,10 +416,7 @@ impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
// From the end of the first line of comments to the next non-whitespace char.
let test_snippet = &test_snippet[..first];
if test_snippet
.chars()
.filter(|c| c == &'\n')
.count() > 1 {
if test_snippet.chars().filter(|c| c == &'\n').count() > 1 {
// There were multiple line breaks which got trimmed to nothing.
new_lines = true;
}

View File

@ -109,10 +109,7 @@ pub fn rewrite_macro(mac: &ast::Mac,
let expr = match parser.parse_expr() {
Ok(expr) => {
// Recovered errors.
if context
.parse_session
.span_diagnostic
.has_errors() {
if context.parse_session.span_diagnostic.has_errors() {
return None;
}

View File

@ -75,10 +75,7 @@ impl<'a> FmtVisitor<'a> {
// Get a snippet from the file start to the span's hi without allocating.
// We need it to determine what precedes the current comment. If the comment
// follows code on the same line, we won't touch it.
let big_span_lo = self.codemap
.lookup_char_pos(span.lo)
.file
.start_pos;
let big_span_lo = self.codemap.lookup_char_pos(span.lo).file.start_pos;
let local_begin = self.codemap.lookup_byte_offset(big_span_lo);
let local_end = self.codemap.lookup_byte_offset(span.hi);
let start_index = local_begin.pos.to_usize();
@ -189,8 +186,7 @@ impl<'a> FmtVisitor<'a> {
self.buffer.push_str(&snippet[line_start..lw]);
self.buffer.push_str("\n");
} else {
self.buffer
.push_str(&snippet[line_start..i + 1]);
self.buffer.push_str(&snippet[line_start..i + 1]);
}
line_start = i + 1;

View File

@ -92,16 +92,12 @@ impl Rewrite for Pat {
PatKind::Lit(ref expr) => expr.rewrite(context, shape),
PatKind::Slice(ref prefix, ref slice_pat, ref suffix) => {
// Rewrite all the sub-patterns.
let prefix = prefix
.iter()
.map(|p| p.rewrite(context, shape));
let prefix = prefix.iter().map(|p| p.rewrite(context, shape));
let slice_pat =
slice_pat
.as_ref()
.map(|p| Some(format!("{}..", try_opt!(p.rewrite(context, shape)))));
let suffix = suffix
.iter()
.map(|p| p.rewrite(context, shape));
let suffix = suffix.iter().map(|p| p.rewrite(context, shape));
// Munge them together.
let pats: Option<Vec<String>> = prefix
@ -280,10 +276,7 @@ fn rewrite_tuple_pat(pats: &[ptr::P<ast::Pat>],
// add comma if `(x,)`
let add_comma = path_str.is_none() && pat_vec.len() == 1 && dotdot_pos.is_none();
let path_len = path_str
.as_ref()
.map(|p| p.len())
.unwrap_or(0);
let path_len = path_str.as_ref().map(|p| p.len()).unwrap_or(0);
// 2 = "()".len(), 3 = "(,)".len()
let nested_shape = try_opt!(shape.sub_width(path_len + if add_comma { 3 } else { 2 }));
// 1 = "(".len()

View File

@ -42,14 +42,10 @@ pub fn make_diff(expected: &str, actual: &str, context_size: usize) -> Vec<Misma
}
while let Some(line) = context_queue.pop_front() {
mismatch
.lines
.push(DiffLine::Context(line.to_owned()));
mismatch.lines.push(DiffLine::Context(line.to_owned()));
}
mismatch
.lines
.push(DiffLine::Resulting(str.to_owned()));
mismatch.lines.push(DiffLine::Resulting(str.to_owned()));
lines_since_mismatch = 0;
}
diff::Result::Right(str) => {
@ -59,14 +55,10 @@ pub fn make_diff(expected: &str, actual: &str, context_size: usize) -> Vec<Misma
}
while let Some(line) = context_queue.pop_front() {
mismatch
.lines
.push(DiffLine::Context(line.to_owned()));
mismatch.lines.push(DiffLine::Context(line.to_owned()));
}
mismatch
.lines
.push(DiffLine::Expected(str.to_owned()));
mismatch.lines.push(DiffLine::Expected(str.to_owned()));
line_number += 1;
lines_since_mismatch = 0;
}
@ -76,9 +68,7 @@ pub fn make_diff(expected: &str, actual: &str, context_size: usize) -> Vec<Misma
}
if lines_since_mismatch < context_size {
mismatch
.lines
.push(DiffLine::Context(str.to_owned()));
mismatch.lines.push(DiffLine::Context(str.to_owned()));
} else {
context_queue.push_back(str);
}

View File

@ -203,12 +203,8 @@ fn rewrite_segment(path_context: PathContext,
let param_list = data.lifetimes
.iter()
.map(SegmentParam::LifeTime)
.chain(data.types
.iter()
.map(|x| SegmentParam::Type(&*x)))
.chain(data.bindings
.iter()
.map(|x| SegmentParam::Binding(&*x)))
.chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
.chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
.collect::<Vec<_>>();
let next_span_lo = param_list.last().unwrap().get_span().hi + BytePos(1);
@ -500,9 +496,7 @@ impl Rewrite for ast::TyParamBounds {
TypeDensity::Compressed => "+",
TypeDensity::Wide => " + ",
};
let strs: Vec<_> = try_opt!(self.iter()
.map(|b| b.rewrite(context, shape))
.collect());
let strs: Vec<_> = try_opt!(self.iter().map(|b| b.rewrite(context, shape)).collect());
wrap_str(strs.join(joiner), context.config.max_width, shape)
}
}

View File

@ -44,9 +44,7 @@ pub fn format_visibility(vis: &Visibility) -> Cow<'static, str> {
Visibility::Crate(_) => Cow::from("pub(crate) "),
Visibility::Restricted { ref path, .. } => {
let Path { ref segments, .. } = **path;
let mut segments_iter = segments
.iter()
.map(|seg| seg.identifier.name.as_str());
let mut segments_iter = segments.iter().map(|seg| seg.identifier.name.as_str());
if path.is_global() {
segments_iter
.next()
@ -184,9 +182,7 @@ pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
pub fn trim_newlines(input: &str) -> &str {
match input.find(|c| c != '\n' && c != '\r') {
Some(start) => {
let end = input
.rfind(|c| c != '\n' && c != '\r')
.unwrap_or(0) + 1;
let end = input.rfind(|c| c != '\n' && c != '\r').unwrap_or(0) + 1;
&input[start..end]
}
None => "",

View File

@ -118,8 +118,7 @@ impl<'a> FmtVisitor<'a> {
} else {
self.config.tab_spaces
};
self.buffer
.truncate(total_len - chars_too_many);
self.buffer.truncate(total_len - chars_too_many);
self.buffer.push_str("}");
self.block_indent = self.block_indent.block_unindent(self.config);
}
@ -190,9 +189,7 @@ impl<'a> FmtVisitor<'a> {
// the AST lumps them all together.
match item.node {
ast::ItemKind::Mod(ref m) => {
let outer_file = self.codemap
.lookup_char_pos(item.span.lo)
.file;
let outer_file = self.codemap.lookup_char_pos(item.span.lo).file;
let inner_file = self.codemap.lookup_char_pos(m.inner.lo).file;
if outer_file.name == inner_file.name {
// Module is inline, in this case we treat modules like any
@ -535,8 +532,7 @@ impl<'a> FmtVisitor<'a> {
let is_internal = !(inner_span.lo.0 == 0 && inner_span.hi.0 == 0) &&
local_file_name == self.codemap.span_to_filename(inner_span);
self.buffer
.push_str(&*utils::format_visibility(vis));
self.buffer.push_str(&*utils::format_visibility(vis));
self.buffer.push_str("mod ");
self.buffer.push_str(&ident.to_string());

View File

@ -4,7 +4,6 @@
// Test chain formatting.
fn main() {
// Don't put chains on a single line if it wasn't so in source.
let a = b .c
.d.1
.foo(|x| x + 1);

View File

@ -28,7 +28,9 @@ const DIFF_CONTEXT_SIZE: usize = 3;
fn get_path_string(dir_entry: io::Result<fs::DirEntry>) -> String {
let path = dir_entry.expect("Couldn't get DirEntry").path();
path.to_str().expect("Couldn't stringify path").to_owned()
path.to_str()
.expect("Couldn't stringify path")
.to_owned()
}
// Integration tests. The files in the tests/source are formatted and compared
@ -84,7 +86,9 @@ fn assert_output(source: &str, expected_filename: &str) {
let mut expected_file = fs::File::open(&expected_filename).expect("Couldn't open target");
let mut expected_text = String::new();
expected_file.read_to_string(&mut expected_text).expect("Failed reading target");
expected_file
.read_to_string(&mut expected_text)
.expect("Failed reading target");
let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
if compare.len() > 0 {
@ -100,8 +104,9 @@ fn assert_output(source: &str, expected_filename: &str) {
#[test]
fn idempotence_tests() {
// Get all files in the tests/target directory.
let files =
fs::read_dir("tests/target").expect("Couldn't read target dir").map(get_path_string);
let files = fs::read_dir("tests/target")
.expect("Couldn't read target dir")
.map(get_path_string);
let (_reports, count, fails) = check_files(files);
// Display results.
@ -276,7 +281,9 @@ fn get_config(config_file: Option<&str>) -> Config {
let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
let mut def_config = String::new();
def_config_file.read_to_string(&mut def_config).expect("Couldn't read config");
def_config_file
.read_to_string(&mut def_config)
.expect("Couldn't read config");
Config::from_toml(&def_config)
}
@ -298,11 +305,22 @@ fn read_significant_comments(file_name: &str) -> HashMap<String, String> {
.map(|line| line.expect("Failed getting line"))
.take_while(|line| line_regex.is_match(&line))
.filter_map(|line| {
regex.captures_iter(&line).next().map(|capture| {
(capture.get(1).expect("Couldn't unwrap capture").as_str().to_owned(),
capture.get(2).expect("Couldn't unwrap capture").as_str().to_owned())
})
})
regex
.captures_iter(&line)
.next()
.map(|capture| {
(capture
.get(1)
.expect("Couldn't unwrap capture")
.as_str()
.to_owned(),
capture
.get(2)
.expect("Couldn't unwrap capture")
.as_str()
.to_owned())
})
})
.collect()
}
@ -319,7 +337,8 @@ fn handle_result(result: HashMap<String, String>,
let mut f = fs::File::open(&target).expect("Couldn't open target");
let mut text = String::new();
f.read_to_string(&mut text).expect("Failed reading target");
f.read_to_string(&mut text)
.expect("Failed reading target");
if fmt_text != text {
let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);

View File

@ -5,12 +5,10 @@
fn main() {
// Don't put chains on a single line if it wasn't so in source.
let a = b.c
.d
.1
.foo(|x| x + 1);
let a = b.c.d.1.foo(|x| x + 1);
bbbbbbbbbbbbbbbbbbb.ccccccccccccccccccccccccccccccccccccc.ddddddddddddddddddddddddddd();
bbbbbbbbbbbbbbbbbbb.ccccccccccccccccccccccccccccccccccccc
.ddddddddddddddddddddddddddd();
bbbbbbbbbbbbbbbbbbb.ccccccccccccccccccccccccccccccccccccc
.ddddddddddddddddddddddddddd
@ -49,7 +47,9 @@ fn main() {
});
let suuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuum =
xxxxxxx.map(|x| x + 5).map(|x| x / 2).fold(0, |acc, x| acc + x);
xxxxxxx.map(|x| x + 5)
.map(|x| x / 2)
.fold(0, |acc, x| acc + x);
aaaaaaaaaaaaaaaa.map(|x| {
x += 1;
@ -125,7 +125,8 @@ fn floaters() {
}
fn is_replaced_content() -> bool {
constellat.send(ConstellationMsg::ViewportConstrained(self.id, constraints)).unwrap();
constellat.send(ConstellationMsg::ViewportConstrained(self.id, constraints))
.unwrap();
}
fn issue587() {

View File

@ -4,11 +4,7 @@
// Test chain formatting.
fn main() {
// Don't put chains on a single line if it wasn't so in source.
let a = b.c
.d
.1
.foo(|x| x + 1);
let a = b.c.d.1.foo(|x| x + 1);
bbbbbbbbbbbbbbbbbbb.ccccccccccccccccccccccccccccccccccccc.ddddddddddddddddddddddddddd();
@ -139,11 +135,8 @@ fn issue587() {
fn try_shorthand() {
let x = expr?;
let y = expr.kaas()?.test();
let loooooooooooooooooooooooooooooooooooooooooong = does_this?
.look?
.good?
.should_we_break?
.after_the_first_question_mark?;
let loooooooooooooooooooooooooooooooooooooooooong =
does_this?.look?.good?.should_we_break?.after_the_first_question_mark?;
let yyyy = expr?
.another?
.another?
@ -154,11 +147,7 @@ fn try_shorthand() {
.another?
.another?
.test();
let zzzz = expr?
.another?
.another?
.another?
.another?;
let zzzz = expr?.another?.another?.another?.another?;
let aaa = x??????????????????????????????????????????????????????????????????????????;
let y = a.very

View File

@ -291,7 +291,7 @@ fn issue1106() {
self.ast_map.expect_item(enum_node_id).node {}
}
for entry in WalkDir::new(path).into_iter().filter_entry(|entry| {
exclusions.filter_entry(entry)
}) {}
for entry in WalkDir::new(path)
.into_iter()
.filter_entry(|entry| exclusions.filter_entry(entry)) {}
}

View File

@ -1,4 +1,6 @@
fn f() {
block_flow.base.stacking_relative_position_of_display_port =
block_flow
.base
.stacking_relative_position_of_display_port =
self.base.stacking_relative_position_of_display_port;
}

View File

@ -29,13 +29,14 @@ fn b() {
}
fn issue550() {
self.visitor.visit_volume(self.level.sector_id(sector),
(floor_y,
if is_sky_flat(ceil_tex) {
from_wad_height(self.height_range.1)
} else {
ceil_y
}));
self.visitor
.visit_volume(self.level.sector_id(sector),
(floor_y,
if is_sky_flat(ceil_tex) {
from_wad_height(self.height_range.1)
} else {
ceil_y
}));
}
fn issue775() {