Format source codes

This commit is contained in:
topecongiro 2017-05-16 23:24:38 +09:00
parent feff6248c4
commit d7b6f1199f
10 changed files with 189 additions and 215 deletions

View File

@ -249,13 +249,11 @@ pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -
// True if the chain is only `?`s. // True if the chain is only `?`s.
fn chain_only_try(exprs: &[ast::Expr]) -> bool { fn chain_only_try(exprs: &[ast::Expr]) -> bool {
exprs exprs.iter().all(|e| if let ast::ExprKind::Try(_) = e.node {
.iter() true
.all(|e| if let ast::ExprKind::Try(_) = e.node { } else {
true false
} else { })
false
})
} }
pub fn rewrite_try(expr: &ast::Expr, pub fn rewrite_try(expr: &ast::Expr,

View File

@ -1028,11 +1028,10 @@ impl<'a> Rewrite for ControlFlow<'a> {
let between_kwd_else_block_comment = let between_kwd_else_block_comment =
extract_comment(between_kwd_else_block, context, shape); extract_comment(between_kwd_else_block, context, shape);
let after_else = let after_else = mk_sp(context.codemap.span_after(mk_sp(self.block.span.hi,
mk_sp(context else_block.span.lo),
.codemap "else"),
.span_after(mk_sp(self.block.span.hi, else_block.span.lo), "else"), else_block.span.lo);
else_block.span.lo);
let after_else_comment = extract_comment(after_else, context, shape); let after_else_comment = extract_comment(after_else, context, shape);
let between_sep = match context.config.control_brace_style { let between_sep = match context.config.control_brace_style {

View File

@ -457,11 +457,8 @@ impl<'a> FmtVisitor<'a> {
} }
let indent = self.block_indent; let indent = self.block_indent;
let mut result = try_opt!(field let mut result = try_opt!(field.node.attrs.rewrite(&self.get_context(),
.node Shape::indented(indent, self.config)));
.attrs
.rewrite(&self.get_context(),
Shape::indented(indent, self.config)));
if !result.is_empty() { if !result.is_empty() {
result.push('\n'); result.push('\n');
result.push_str(&indent.to_string(self.config)); result.push_str(&indent.to_string(self.config));
@ -1201,9 +1198,9 @@ impl Rewrite for ast::StructField {
let name = self.ident; let name = self.ident;
let vis = format_visibility(&self.vis); let vis = format_visibility(&self.vis);
let mut attr_str = let mut attr_str = try_opt!(self.attrs.rewrite(context,
try_opt!(self.attrs Shape::indented(shape.indent,
.rewrite(context, Shape::indented(shape.indent, context.config))); context.config)));
if !attr_str.is_empty() { if !attr_str.is_empty() {
attr_str.push('\n'); attr_str.push('\n');
attr_str.push_str(&shape.indent.to_string(context.config)); attr_str.push_str(&shape.indent.to_string(context.config));
@ -1223,9 +1220,9 @@ impl Rewrite for ast::StructField {
let last_line_width = last_line_width(&result) + type_annotation_spacing.1.len(); let last_line_width = last_line_width(&result) + type_annotation_spacing.1.len();
let budget = try_opt!(shape.width.checked_sub(last_line_width)); let budget = try_opt!(shape.width.checked_sub(last_line_width));
let ty_rewritten = self.ty let ty_rewritten =
.rewrite(context, self.ty.rewrite(context,
Shape::legacy(budget, shape.indent + last_line_width)); Shape::legacy(budget, shape.indent + last_line_width));
match ty_rewritten { match ty_rewritten {
Some(ref ty) if ty.contains('\n') => { Some(ref ty) if ty.contains('\n') => {
let new_ty = rewrite_type_in_next_line(); let new_ty = rewrite_type_in_next_line();
@ -1377,9 +1374,8 @@ impl Rewrite for ast::FunctionRetTy {
impl Rewrite for ast::Arg { impl Rewrite for ast::Arg {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> { fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
if is_named_arg(self) { if is_named_arg(self) {
let mut result = try_opt!(self.pat let mut result = try_opt!(self.pat.rewrite(context,
.rewrite(context, Shape::legacy(shape.width, shape.indent)));
Shape::legacy(shape.width, shape.indent)));
if self.ty.node != ast::TyKind::Infer { if self.ty.node != ast::TyKind::Infer {
if context.config.space_before_type_annotation { if context.config.space_before_type_annotation {
@ -1390,10 +1386,9 @@ impl Rewrite for ast::Arg {
result.push_str(" "); result.push_str(" ");
} }
let max_width = try_opt!(shape.width.checked_sub(result.len())); let max_width = try_opt!(shape.width.checked_sub(result.len()));
let ty_str = try_opt!(self.ty let ty_str = try_opt!(self.ty.rewrite(context,
.rewrite(context, Shape::legacy(max_width,
Shape::legacy(max_width, shape.indent + result.len())));
shape.indent + result.len())));
result.push_str(&ty_str); result.push_str(&ty_str);
} }
@ -1693,9 +1688,8 @@ fn rewrite_fn_base(context: &RewriteContext,
if multi_line_ret_str || ret_should_indent { if multi_line_ret_str || ret_should_indent {
// Now that we know the proper indent and width, we need to // Now that we know the proper indent and width, we need to
// re-layout the return type. // re-layout the return type.
let ret_str = try_opt!(fd.output let ret_str = try_opt!(fd.output.rewrite(context,
.rewrite(context, Shape::indented(ret_indent, context.config)));
Shape::indented(ret_indent, context.config)));
result.push_str(&ret_str); result.push_str(&ret_str);
} else { } else {
result.push_str(&ret_str); result.push_str(&ret_str);
@ -1985,16 +1979,14 @@ fn rewrite_generics(context: &RewriteContext,
.map(|ty_param| ty_param.rewrite(context, Shape::legacy(h_budget, offset))); .map(|ty_param| ty_param.rewrite(context, Shape::legacy(h_budget, offset)));
// Extract comments between generics. // Extract comments between generics.
let lt_spans = lifetimes let lt_spans = lifetimes.iter().map(|l| {
.iter() let hi = if l.bounds.is_empty() {
.map(|l| { l.lifetime.span.hi
let hi = if l.bounds.is_empty() { } else {
l.lifetime.span.hi l.bounds[l.bounds.len() - 1].span.hi
} else { };
l.bounds[l.bounds.len() - 1].span.hi mk_sp(l.lifetime.span.lo, hi)
}; });
mk_sp(l.lifetime.span.lo, hi)
});
let ty_spans = tys.iter().map(span_for_ty_param); let ty_spans = tys.iter().map(span_for_ty_param);
let items = itemize_list(context.codemap, let items = itemize_list(context.codemap,

View File

@ -339,116 +339,114 @@ impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
let white_space: &[_] = &[' ', '\t']; let white_space: &[_] = &[' ', '\t'];
self.inner self.inner.next().map(|item| {
.next() let mut new_lines = false;
.map(|item| { // Pre-comment
let mut new_lines = false; let pre_snippet = self.codemap
// Pre-comment .span_to_snippet(codemap::mk_sp(self.prev_span_end, (self.get_lo)(&item)))
let pre_snippet = self.codemap .unwrap();
.span_to_snippet(codemap::mk_sp(self.prev_span_end, (self.get_lo)(&item))) let trimmed_pre_snippet = pre_snippet.trim();
.unwrap(); let has_pre_comment = trimmed_pre_snippet.contains("//") ||
let trimmed_pre_snippet = pre_snippet.trim(); trimmed_pre_snippet.contains("/*");
let has_pre_comment = trimmed_pre_snippet.contains("//") || let pre_comment = if has_pre_comment {
trimmed_pre_snippet.contains("/*"); Some(trimmed_pre_snippet.to_owned())
let pre_comment = if has_pre_comment { } else {
Some(trimmed_pre_snippet.to_owned()) None
} else { };
None
};
// Post-comment // Post-comment
let next_start = match self.inner.peek() { let next_start = match self.inner.peek() {
Some(next_item) => (self.get_lo)(next_item), Some(next_item) => (self.get_lo)(next_item),
None => self.next_span_start, None => self.next_span_start,
}; };
let post_snippet = self.codemap let post_snippet = self.codemap
.span_to_snippet(codemap::mk_sp((self.get_hi)(&item), next_start)) .span_to_snippet(codemap::mk_sp((self.get_hi)(&item), next_start))
.unwrap(); .unwrap();
let comment_end = match self.inner.peek() { let comment_end = match self.inner.peek() {
Some(..) => { Some(..) => {
let mut block_open_index = post_snippet.find("/*"); let mut block_open_index = post_snippet.find("/*");
// check if it realy is a block comment (and not //*) // check if it realy is a block comment (and not //*)
if let Some(i) = block_open_index { if let Some(i) = block_open_index {
if i > 0 && &post_snippet[i - 1..i] == "/" { if i > 0 && &post_snippet[i - 1..i] == "/" {
block_open_index = None; block_open_index = None;
}
}
let newline_index = post_snippet.find('\n');
let separator_index = post_snippet.find_uncommented(",").unwrap();
match (block_open_index, newline_index) {
// Separator before comment, with the next item on same line.
// Comment belongs to next item.
(Some(i), None) if i > separator_index => separator_index + 1,
// Block-style post-comment before the separator.
(Some(i), None) => {
cmp::max(find_comment_end(&post_snippet[i..]).unwrap() + i,
separator_index + 1)
}
// Block-style post-comment. Either before or after the separator.
(Some(i), Some(j)) if i < j => {
cmp::max(find_comment_end(&post_snippet[i..]).unwrap() + i,
separator_index + 1)
}
// Potential *single* line comment.
(_, Some(j)) if j > separator_index => j + 1,
_ => post_snippet.len(),
} }
} }
None => { let newline_index = post_snippet.find('\n');
post_snippet let separator_index = post_snippet.find_uncommented(",").unwrap();
.find_uncommented(self.terminator)
.unwrap_or(post_snippet.len())
}
};
if !post_snippet.is_empty() && comment_end > 0 { match (block_open_index, newline_index) {
// Account for extra whitespace between items. This is fiddly // Separator before comment, with the next item on same line.
// because of the way we divide pre- and post- comments. // Comment belongs to next item.
(Some(i), None) if i > separator_index => separator_index + 1,
// Everything from the separator to the next item. // Block-style post-comment before the separator.
let test_snippet = &post_snippet[comment_end - 1..]; (Some(i), None) => {
let first_newline = test_snippet.find('\n').unwrap_or(test_snippet.len()); cmp::max(find_comment_end(&post_snippet[i..]).unwrap() + i,
// From the end of the first line of comments. separator_index + 1)
let test_snippet = &test_snippet[first_newline..]; }
let first = test_snippet // Block-style post-comment. Either before or after the separator.
.find(|c: char| !c.is_whitespace()) (Some(i), Some(j)) if i < j => {
.unwrap_or(test_snippet.len()); cmp::max(find_comment_end(&post_snippet[i..]).unwrap() + i,
// From the end of the first line of comments to the next non-whitespace char. separator_index + 1)
let test_snippet = &test_snippet[..first]; }
// Potential *single* line comment.
if test_snippet.chars().filter(|c| c == &'\n').count() > 1 { (_, Some(j)) if j > separator_index => j + 1,
// There were multiple line breaks which got trimmed to nothing. _ => post_snippet.len(),
new_lines = true;
} }
} }
None => {
// Cleanup post-comment: strip separators and whitespace.
self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
let post_snippet = post_snippet[..comment_end].trim();
let post_snippet_trimmed = if post_snippet.starts_with(',') {
post_snippet[1..].trim_matches(white_space)
} else if post_snippet.ends_with(',') {
post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
} else {
post_snippet post_snippet
}; .find_uncommented(self.terminator)
.unwrap_or(post_snippet.len())
let post_comment = if !post_snippet_trimmed.is_empty() {
Some(post_snippet_trimmed.to_owned())
} else {
None
};
ListItem {
pre_comment: pre_comment,
item: (self.get_item_string)(&item),
post_comment: post_comment,
new_lines: new_lines,
} }
}) };
if !post_snippet.is_empty() && comment_end > 0 {
// Account for extra whitespace between items. This is fiddly
// because of the way we divide pre- and post- comments.
// 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());
// 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());
// 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 {
// There were multiple line breaks which got trimmed to nothing.
new_lines = true;
}
}
// Cleanup post-comment: strip separators and whitespace.
self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
let post_snippet = post_snippet[..comment_end].trim();
let post_snippet_trimmed = if post_snippet.starts_with(',') {
post_snippet[1..].trim_matches(white_space)
} else if post_snippet.ends_with(',') {
post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
} else {
post_snippet
};
let post_comment = if !post_snippet_trimmed.is_empty() {
Some(post_snippet_trimmed.to_owned())
} else {
None
};
ListItem {
pre_comment: pre_comment,
item: (self.get_item_string)(&item),
post_comment: post_comment,
new_lines: new_lines,
}
})
} }
} }

View File

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

View File

@ -158,13 +158,12 @@ impl<'a> FmtVisitor<'a> {
self.config.max_width - self.config.max_width -
self.block_indent.width()); self.block_indent.width());
self.buffer self.buffer.push_str(&rewrite_comment(subslice,
.push_str(&rewrite_comment(subslice, false,
false, Shape::legacy(comment_width,
Shape::legacy(comment_width, self.block_indent),
self.block_indent), self.config)
self.config) .unwrap());
.unwrap());
last_wspace = None; last_wspace = None;
line_start = offset + subslice.len(); line_start = offset + subslice.len();

View File

@ -39,11 +39,10 @@ impl Rewrite for Pat {
let sub_pat = match *sub_pat { let sub_pat = match *sub_pat {
Some(ref p) => { Some(ref p) => {
// 3 - ` @ `. // 3 - ` @ `.
let width = try_opt!(shape let width = try_opt!(shape.width.checked_sub(prefix.len() +
.width mut_infix.len() +
.checked_sub(prefix.len() + mut_infix.len() + id_str.len() +
id_str.len() + 3));
3));
format!(" @ {}", format!(" @ {}",
try_opt!(p.rewrite(context, Shape::legacy(width, shape.indent)))) try_opt!(p.rewrite(context, Shape::legacy(width, shape.indent))))
} }
@ -328,13 +327,11 @@ fn rewrite_tuple_pat(pats: &[ptr::P<ast::Pat>],
fn count_wildcard_suffix_len(items: &[ListItem]) -> usize { fn count_wildcard_suffix_len(items: &[ListItem]) -> usize {
let mut suffix_len = 0; let mut suffix_len = 0;
for item in items for item in items.iter().rev().take_while(|i| match i.item {
.iter() Some(ref internal_string) if internal_string ==
.rev() "_" => true,
.take_while(|i| match i.item { _ => false,
Some(ref internal_string) if internal_string == "_" => true, }) {
_ => false,
}) {
suffix_len += 1; suffix_len += 1;
if item.pre_comment.is_some() || item.post_comment.is_some() { if item.pre_comment.is_some() || item.post_comment.is_some() {

View File

@ -163,11 +163,10 @@ impl<'a> Rewrite for SegmentParam<'a> {
TypeDensity::Compressed => format!("{}=", binding.ident), TypeDensity::Compressed => format!("{}=", binding.ident),
}; };
let budget = try_opt!(shape.width.checked_sub(result.len())); let budget = try_opt!(shape.width.checked_sub(result.len()));
let rewrite = let rewrite = try_opt!(binding.ty.rewrite(context,
try_opt!(binding Shape::legacy(budget,
.ty shape.indent +
.rewrite(context, result.len())));
Shape::legacy(budget, shape.indent + result.len())));
result.push_str(&rewrite); result.push_str(&rewrite);
Some(result) Some(result)
} }
@ -563,10 +562,10 @@ impl Rewrite for ast::PolyTraitRef {
// 6 is "for<> ".len() // 6 is "for<> ".len()
let extra_offset = lifetime_str.len() + 6; let extra_offset = lifetime_str.len() + 6;
let max_path_width = try_opt!(shape.width.checked_sub(extra_offset)); let max_path_width = try_opt!(shape.width.checked_sub(extra_offset));
let path_str = try_opt!(self.trait_ref let path_str = try_opt!(self.trait_ref.rewrite(context,
.rewrite(context, Shape::legacy(max_path_width,
Shape::legacy(max_path_width, shape.indent +
shape.indent + extra_offset))); extra_offset)));
Some(if context.config.spaces_within_angle_brackets && lifetime_str.len() > 0 { Some(if context.config.spaces_within_angle_brackets && lifetime_str.len() > 0 {
format!("for< {} > {}", lifetime_str, path_str) format!("for< {} > {}", lifetime_str, path_str)
@ -613,22 +612,20 @@ impl Rewrite for ast::Ty {
format!("&{} {}{}", format!("&{} {}{}",
lt_str, lt_str,
mut_str, mut_str,
try_opt!(mt.ty try_opt!(mt.ty.rewrite(context,
.rewrite(context, Shape::legacy(budget,
Shape::legacy(budget, shape.indent + 2 +
shape.indent + 2 + mut_len +
mut_len + lt_len))))
lt_len))))
} }
None => { None => {
let budget = try_opt!(shape.width.checked_sub(1 + mut_len)); let budget = try_opt!(shape.width.checked_sub(1 + mut_len));
format!("&{}{}", format!("&{}{}",
mut_str, mut_str,
try_opt!(mt.ty try_opt!(mt.ty.rewrite(context,
.rewrite(context, Shape::legacy(budget,
Shape::legacy(budget, shape.indent + 1 +
shape.indent + 1 + mut_len))))
mut_len))))
} }
}) })
} }

View File

@ -303,21 +303,18 @@ fn read_significant_comments(file_name: &str) -> HashMap<String, String> {
.map(|line| line.expect("Failed getting line")) .map(|line| line.expect("Failed getting line"))
.take_while(|line| line_regex.is_match(&line)) .take_while(|line| line_regex.is_match(&line))
.filter_map(|line| { .filter_map(|line| {
regex regex.captures_iter(&line).next().map(|capture| {
.captures_iter(&line) (capture
.next() .get(1)
.map(|capture| { .expect("Couldn't unwrap capture")
(capture .as_str()
.get(1) .to_owned(),
.expect("Couldn't unwrap capture") capture
.as_str() .get(2)
.to_owned(), .expect("Couldn't unwrap capture")
capture .as_str()
.get(2) .to_owned())
.expect("Couldn't unwrap capture") })
.as_str()
.to_owned())
})
}) })
.collect() .collect()
} }

View File

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