1
Fork 0

Formatting

This commit is contained in:
Nick Cameron 2015-08-16 15:58:17 +12:00
parent d10629d8a5
commit a43e2b5ae8
12 changed files with 86 additions and 87 deletions

View file

@ -127,8 +127,8 @@ impl FindUncommented for str {
if b != c { if b != c {
needle_iter = pat.chars(); needle_iter = pat.chars();
} }
}, }
None => return Some(i - pat.len()) None => return Some(i - pat.len()),
} }
if possible_comment && (b == '/' || b == '*') { if possible_comment && (b == '/' || b == '*') {
@ -145,7 +145,7 @@ impl FindUncommented for str {
// Handle case where the pattern is a suffix of the search string // Handle case where the pattern is a suffix of the search string
match needle_iter.next() { match needle_iter.next() {
Some(_) => None, Some(_) => None,
None => Some(self.len() - pat.len()) None => Some(self.len() - pat.len()),
} }
} }
} }

View file

@ -30,7 +30,7 @@ impl Rewrite for ast::Expr {
ast::Lit_::LitStr(ref is, _) => { ast::Lit_::LitStr(ref is, _) => {
rewrite_string_lit(context, &is, l.span, width, offset) rewrite_string_lit(context, &is, l.span, width, offset)
} }
_ => context.codemap.span_to_snippet(self.span).ok() _ => context.codemap.span_to_snippet(self.span).ok(),
} }
} }
ast::Expr_::ExprCall(ref callee, ref args) => { ast::Expr_::ExprCall(ref callee, ref args) => {
@ -105,7 +105,7 @@ impl Rewrite for ast::Expr {
ast::Expr_::ExprPath(ref qself, ref path) => { ast::Expr_::ExprPath(ref qself, ref path) => {
rewrite_path(context, qself.as_ref(), path, width, offset) rewrite_path(context, qself.as_ref(), path, width, offset)
} }
_ => context.codemap.span_to_snippet(self.span).ok() _ => context.codemap.span_to_snippet(self.span).ok(),
} }
} }
} }
@ -199,7 +199,7 @@ impl<'a> Loop<'a> {
keyword: "while ", keyword: "while ",
matcher: match pat { matcher: match pat {
Some(..) => "let ", Some(..) => "let ",
None => "" None => "",
}, },
connector: " =", connector: " =",
} }
@ -237,7 +237,7 @@ impl<'a> Rewrite for Loop<'a> {
self.connector, self.connector,
inner_width, inner_width,
inner_offset)), inner_offset)),
None => String::new() None => String::new(),
}; };
// FIXME: this drops any comment between "loop" and the block. // FIXME: this drops any comment between "loop" and the block.
@ -250,7 +250,7 @@ impl<'a> Rewrite for Loop<'a> {
fn rewrite_label(label: Option<ast::Ident>) -> String { fn rewrite_label(label: Option<ast::Ident>) -> String {
match label { match label {
Some(ident) => format!("{}: ", ident), Some(ident) => format!("{}: ", ident),
None => "".to_owned() None => "".to_owned(),
} }
} }
@ -262,9 +262,8 @@ fn rewrite_range(context: &RewriteContext,
offset: usize) offset: usize)
-> Option<String> { -> Option<String> {
let left_string = match left { let left_string = match left {
// 2 = ..
Some(expr) => try_opt!(expr.rewrite(context, width - 2, offset)), Some(expr) => try_opt!(expr.rewrite(context, width - 2, offset)),
None => String::new() None => String::new(),
}; };
let right_string = match right { let right_string = match right {
@ -273,7 +272,7 @@ fn rewrite_range(context: &RewriteContext,
let max_width = (width - 2).checked_sub(left_string.len()).unwrap_or(0); let max_width = (width - 2).checked_sub(left_string.len()).unwrap_or(0);
try_opt!(expr.rewrite(context, max_width, offset + 2 + left_string.len())) try_opt!(expr.rewrite(context, max_width, offset + 2 + left_string.len()))
} }
None => String::new() None => String::new(),
}; };
Some(format!("{}..{}", left_string, right_string)) Some(format!("{}..{}", left_string, right_string))
@ -354,12 +353,13 @@ impl Rewrite for ast::Arm {
let pat_strs = pats.iter().map(|p| p.rewrite(context, let pat_strs = pats.iter().map(|p| p.rewrite(context,
// 5 = ` => {` // 5 = ` => {`
width - 5, width - 5,
offset + context.config.tab_spaces)).collect::<Vec<_>>(); offset + context.config.tab_spaces))
.collect::<Vec<_>>();
if pat_strs.iter().any(|p| p.is_none()) { if pat_strs.iter().any(|p| p.is_none()) {
return None; return None;
} }
let pat_strs = pat_strs.into_iter().map(|p| p.unwrap()).collect::<Vec<_>>(); let pat_strs = pat_strs.into_iter().map(|p| p.unwrap()).collect::<Vec<_>>();
let mut total_width = pat_strs.iter().fold(0, |a, p| a + p.len()); let mut total_width = pat_strs.iter().fold(0, |a, p| a + p.len());
// Add ` | `.len(). // Add ` | `.len().
total_width += (pat_strs.len() - 1) * 3; total_width += (pat_strs.len() - 1) * 3;
@ -496,7 +496,7 @@ fn rewrite_pat_expr(context: &RewriteContext,
pat_offset)); pat_offset));
format!("{}{}{}", matcher, pat_string, connector) format!("{}{}{}", matcher, pat_string, connector)
} }
None => String::new() None => String::new(),
}; };
// Consider only the last line of the pat string. // Consider only the last line of the pat string.
@ -804,7 +804,7 @@ fn rewrite_binary_op(context: &RewriteContext,
let used_width = result.len() + 1; let used_width = result.len() + 1;
let remaining_width = match result.rfind('\n') { let remaining_width = match result.rfind('\n') {
Some(idx) => (offset + width + idx).checked_sub(used_width).unwrap_or(0), Some(idx) => (offset + width + idx).checked_sub(used_width).unwrap_or(0),
None => width.checked_sub(used_width).unwrap_or(0) None => width.checked_sub(used_width).unwrap_or(0),
}; };
// Get "full width" rhs and see if it fits on the current line. This // Get "full width" rhs and see if it fits on the current line. This
@ -836,7 +836,7 @@ fn rewrite_unary_op(context: &RewriteContext,
ast::UnOp::UnUniq => "box ", ast::UnOp::UnUniq => "box ",
ast::UnOp::UnDeref => "*", ast::UnOp::UnDeref => "*",
ast::UnOp::UnNot => "!", ast::UnOp::UnNot => "!",
ast::UnOp::UnNeg => "-" ast::UnOp::UnNeg => "-",
}; };
let subexpr = try_opt!(expr.rewrite(context, width - operator_str.len(), offset)); let subexpr = try_opt!(expr.rewrite(context, width - operator_str.len(), offset));

View file

@ -58,18 +58,18 @@ fn write_file(text: &StringBuffer,
where T: Write where T: Write
{ {
match config.newline_style { match config.newline_style {
NewlineStyle::Unix => write!(writer, "{}", text), NewlineStyle::Unix => write!(writer, "{}", text),
NewlineStyle::Windows => { NewlineStyle::Windows => {
for (c, _) in text.chars() { for (c, _) in text.chars() {
match c { match c {
'\n' => try!(write!(writer, "\r\n")), '\n' => try!(write!(writer, "\r\n")),
'\r' => continue, '\r' => continue,
c => try!(write!(writer, "{}", c)), c => try!(write!(writer, "{}", c)),
}
} }
Ok(()) }
}, Ok(())
} }
}
} }
match mode { match mode {

View file

@ -15,7 +15,8 @@ use rewrite::{Rewrite, RewriteContext};
use syntax::ast; use syntax::ast;
use syntax::codemap::Span; use syntax::codemap::Span;
// TODO (some day) remove unused imports, expand globs, compress many single imports into a list import // TODO (some day) remove unused imports, expand globs, compress many single
// imports into a list import.
impl Rewrite for ast::ViewPath { impl Rewrite for ast::ViewPath {
// Returns an empty string when the ViewPath is empty (like foo::bar::{}) // Returns an empty string when the ViewPath is empty (like foo::bar::{})
@ -39,10 +40,10 @@ impl Rewrite for ast::ViewPath {
let path_str = try_opt!(path.rewrite(context, width - ident_str.len() - 4, offset)); let path_str = try_opt!(path.rewrite(context, width - ident_str.len() - 4, offset));
Some(if path.segments.last().unwrap().identifier == ident { Some(if path.segments.last().unwrap().identifier == ident {
path_str path_str
} else { } else {
format!("{} as {}", path_str, ident_str) format!("{} as {}", path_str, ident_str)
}) })
} }
} }
} }
@ -81,7 +82,7 @@ pub fn rewrite_use_list(width: usize,
match path_list.len() { match path_list.len() {
0 => return None, 0 => return None,
1 => return Some(rewrite_single_use_list(path_str, path_list[0])), 1 => return Some(rewrite_single_use_list(path_str, path_list[0])),
_ => () _ => (),
} }
// 2 = :: // 2 = ::
@ -161,7 +162,7 @@ fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
Some(pos) => { Some(pos) => {
items[0] = items.remove(pos); items[0] = items.remove(pos);
true true
}, }
None => false None => false,
} }
} }

View file

@ -29,7 +29,7 @@ impl ReportTactic {
match *self { match *self {
ReportTactic::Always => true, ReportTactic::Always => true,
ReportTactic::Unnumbered => true, ReportTactic::Unnumbered => true,
ReportTactic::Never => false ReportTactic::Never => false,
} }
} }
} }
@ -113,7 +113,7 @@ impl BadIssueSeeker {
match self.state { match self.state {
Seeking::Issue { todo_idx, fixme_idx } => { Seeking::Issue { todo_idx, fixme_idx } => {
self.state = self.inspect_issue(c, todo_idx, fixme_idx); self.state = self.inspect_issue(c, todo_idx, fixme_idx);
}, }
Seeking::Number { issue, part } => { Seeking::Number { issue, part } => {
let result = self.inspect_number(c, issue, part); let result = self.inspect_number(c, issue, part);
@ -198,19 +198,19 @@ impl BadIssueSeeker {
} else { } else {
part = NumberPart::Pound; part = NumberPart::Pound;
} }
}, }
NumberPart::Pound => { NumberPart::Pound => {
if c == '#' { if c == '#' {
part = NumberPart::Number; part = NumberPart::Number;
} }
}, }
NumberPart::Number => { NumberPart::Number => {
if c >= '0' && c <= '9' { if c >= '0' && c <= '9' {
part = NumberPart::CloseParen; part = NumberPart::CloseParen;
} else { } else {
return IssueClassification::Bad(issue); return IssueClassification::Bad(issue);
} }
}, }
NumberPart::CloseParen => {} NumberPart::CloseParen => {}
} }

View file

@ -411,10 +411,8 @@ impl<'a> FmtVisitor<'a> {
result.push('('); result.push('(');
let indent = self.block_indent let indent = self.block_indent + vis.len() + field.node.name.to_string().len() +
+ vis.len() 1; // Open paren
+ field.node.name.to_string().len()
+ 1; // Open paren
let comma_cost = if self.config.enum_trailing_comma { let comma_cost = if self.config.enum_trailing_comma {
1 1
@ -449,7 +447,7 @@ impl<'a> FmtVisitor<'a> {
} }
result result
}, }
ast::VariantKind::StructVariantKind(ref struct_def) => { ast::VariantKind::StructVariantKind(ref struct_def) => {
// TODO Should limit the width, as we have a trailing comma // TODO Should limit the width, as we have a trailing comma
self.format_struct("", self.format_struct("",
@ -491,7 +489,7 @@ impl<'a> FmtVisitor<'a> {
let is_tuple = match struct_def.fields[0].node.kind { let is_tuple = match struct_def.fields[0].node.kind {
ast::StructFieldKind::NamedField(..) => false, ast::StructFieldKind::NamedField(..) => false,
ast::StructFieldKind::UnnamedField(..) => true ast::StructFieldKind::UnnamedField(..) => true,
}; };
let (opener, terminator) = if is_tuple { let (opener, terminator) = if is_tuple {
@ -506,7 +504,7 @@ impl<'a> FmtVisitor<'a> {
offset + header_str.len(), offset + header_str.len(),
codemap::mk_sp(span.lo, codemap::mk_sp(span.lo,
struct_def.fields[0].span.lo)), struct_def.fields[0].span.lo)),
None => opener.to_owned() None => opener.to_owned(),
}; };
result.push_str(&generics_str); result.push_str(&generics_str);
@ -632,7 +630,7 @@ impl<'a> FmtVisitor<'a> {
}; };
let vis = match field.node.kind { let vis = match field.node.kind {
ast::StructFieldKind::NamedField(_, vis) | ast::StructFieldKind::NamedField(_, vis) |
ast::StructFieldKind::UnnamedField(vis) => format_visibility(vis) ast::StructFieldKind::UnnamedField(vis) => format_visibility(vis),
}; };
let typ = pprust::ty_to_string(&field.node.ty); let typ = pprust::ty_to_string(&field.node.ty);
@ -645,7 +643,7 @@ impl<'a> FmtVisitor<'a> {
match name { match name {
Some(name) => format!("{}{}{}: {}", attr_str, vis, name, typ), Some(name) => format!("{}{}{}: {}", attr_str, vis, name, typ),
None => format!("{}{}{}", attr_str, vis, typ) None => format!("{}{}{}", attr_str, vis, typ),
} }
} }
@ -799,8 +797,7 @@ fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf, args: &[ast::Arg]) -
// this hacky solution caused by absence of `Mutability` in `SelfValue`. // this hacky solution caused by absence of `Mutability` in `SelfValue`.
let mut_str = { let mut_str = {
if let ast::Pat_::PatIdent(ast::BindingMode::BindByValue(mutability), _, _) if let ast::Pat_::PatIdent(ast::BindingMode::BindByValue(mutability), _, _) = args[0].pat.node {
= args[0].pat.node {
format_mutability(mutability) format_mutability(mutability)
} else { } else {
panic!("there is a bug or change in structure of AST, aborting."); panic!("there is a bug or change in structure of AST, aborting.");
@ -809,7 +806,7 @@ fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf, args: &[ast::Arg]) -
Some(format!("{}self", mut_str)) Some(format!("{}self", mut_str))
} }
_ => None _ => None,
} }
} }

View file

@ -92,7 +92,7 @@ impl FromStr for WriteMode {
"replace" => Ok(WriteMode::Replace), "replace" => Ok(WriteMode::Replace),
"display" => Ok(WriteMode::Display), "display" => Ok(WriteMode::Display),
"overwrite" => Ok(WriteMode::Overwrite), "overwrite" => Ok(WriteMode::Overwrite),
_ => Err(()) _ => Err(()),
} }
} }
} }
@ -243,7 +243,7 @@ fn fmt_lines(file_map: &mut FileMap, config: &Config) -> FormatReport {
for (c, b) in text.chars() { for (c, b) in text.chars() {
if c == '\r' { if c == '\r' {
continue; continuecontinue
} }
// Add warnings for bad todos/ fixmes // Add warnings for bad todos/ fixmes

View file

@ -213,7 +213,8 @@ pub fn write_list<'b>(items: &[ListItem], formatting: &ListFormatting<'b>) -> St
let comment = item.post_comment.as_ref().unwrap(); let comment = item.post_comment.as_ref().unwrap();
// Use block-style only for the last item or multiline comments. // Use block-style only for the last item or multiline comments.
let block_style = !formatting.ends_with_newline && last || let block_style = !formatting.ends_with_newline && last ||
comment.trim().contains('\n') || comment.trim().len() > width; comment.trim().contains('\n') ||
comment.trim().len() > width;
let formatted_comment = rewrite_comment(comment, block_style, width, offset); let formatted_comment = rewrite_comment(comment, block_style, width, offset);
@ -381,7 +382,7 @@ fn comment_len(comment: &Option<String>) -> usize {
} else { } else {
text_len text_len
} }
}, }
&None => 0 &None => 0,
} }
} }

View file

@ -67,6 +67,6 @@ fn module_file(id: ast::Ident,
match parser::Parser::default_submod_path(id, &dir_path, codemap).result { match parser::Parser::default_submod_path(id, &dir_path, codemap).result {
Ok(parser::ModulePathSuccess { path, .. }) => path, Ok(parser::ModulePathSuccess { path, .. }) => path,
Err(_) => panic!("Couldn't find module {}", id) Err(_) => panic!("Couldn't find module {}", id),
} }
} }

View file

@ -157,7 +157,7 @@ fn get_path_separator(codemap: &CodeMap,
if c == ':' { if c == ':' {
return "::" return "::"
} else if c.is_whitespace() || c == '<' { } else if c.is_whitespace() || c == '<' {
continue; continuecontinue
} else { } else {
return ""; return "";
} }
@ -235,7 +235,7 @@ fn rewrite_segment(segment: &ast::PathSegment,
ast::PathParameters::ParenthesizedParameters(ref data) => { ast::PathParameters::ParenthesizedParameters(ref data) => {
let output = match data.output { let output = match data.output {
Some(ref ty) => format!(" -> {}", pprust::ty_to_string(&*ty)), Some(ref ty) => format!(" -> {}", pprust::ty_to_string(&*ty)),
None => String::new() None => String::new(),
}; };
let list_lo = span_after(codemap::mk_sp(*span_lo, span_hi), "(", context.codemap); let list_lo = span_after(codemap::mk_sp(*span_lo, span_hi), "(", context.codemap);
@ -267,7 +267,7 @@ fn rewrite_segment(segment: &ast::PathSegment,
format!("({}){}", write_list(&items.collect::<Vec<_>>(), &fmt), output) format!("({}){}", write_list(&items.collect::<Vec<_>>(), &fmt), output)
} }
_ => String::new() _ => String::new(),
}; };
Some(format!("{}{}", segment.identifier, params)) Some(format!("{}{}", segment.identifier, params))
@ -278,57 +278,57 @@ impl Rewrite for ast::WherePredicate {
// TODO dead spans? // TODO dead spans?
// TODO assumes we'll always fit on one line... // TODO assumes we'll always fit on one line...
Some(match self { Some(match self {
&ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes, &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
ref bounded_ty, ref bounded_ty,
ref bounds, ref bounds,
..}) => { ..}) => {
if bound_lifetimes.len() > 0 { if bound_lifetimes.len() > 0 {
let lifetime_str = bound_lifetimes.iter().map(|lt| { let lifetime_str = bound_lifetimes.iter().map(|lt| {
lt.rewrite(context, width, offset).unwrap() lt.rewrite(context, width, offset).unwrap()
}).collect::<Vec<_>>().join(", "); }).collect::<Vec<_>>().join(", ");
let type_str = pprust::ty_to_string(bounded_ty); let type_str = pprust::ty_to_string(bounded_ty);
// 8 = "for<> : ".len() // 8 = "for<> : ".len()
let used_width = lifetime_str.len() + type_str.len() + 8; let used_width = lifetime_str.len() + type_str.len() + 8;
let bounds_str = bounds.iter().map(|ty_bound| { let bounds_str = bounds.iter().map(|ty_bound| {
ty_bound.rewrite(context, ty_bound.rewrite(context,
width - used_width, width - used_width,
offset + used_width) offset + used_width)
.unwrap() .unwrap()
}).collect::<Vec<_>>().join(" + "); }).collect::<Vec<_>>().join(" + ");
format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str) format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
} else { } else {
let type_str = pprust::ty_to_string(bounded_ty); let type_str = pprust::ty_to_string(bounded_ty);
// 2 = ": ".len() // 2 = ": ".len()
let used_width = type_str.len() + 2; let used_width = type_str.len() + 2;
let bounds_str = bounds.iter().map(|ty_bound| { let bounds_str = bounds.iter().map(|ty_bound| {
ty_bound.rewrite(context, ty_bound.rewrite(context,
width - used_width, width - used_width,
offset + used_width) offset + used_width)
.unwrap() .unwrap()
}).collect::<Vec<_>>().join(" + "); }).collect::<Vec<_>>().join(" + ");
format!("{}: {}", type_str, bounds_str) format!("{}: {}", type_str, bounds_str)
}
} }
} &ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
&ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
ref bounds, ref bounds,
..}) => { ..}) => {
format!("{}: {}", format!("{}: {}",
pprust::lifetime_to_string(lifetime), pprust::lifetime_to_string(lifetime),
bounds.iter().map(pprust::lifetime_to_string) bounds.iter().map(pprust::lifetime_to_string)
.collect::<Vec<_>>().join(" + ")) .collect::<Vec<_>>().join(" + "))
} }
&ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => { &ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
let ty_str = pprust::ty_to_string(ty); let ty_str = pprust::ty_to_string(ty);
// 3 = " = ".len() // 3 = " = ".len()
let used_width = 3 + ty_str.len(); let used_width = 3 + ty_str.len();
let path_str = try_opt!(path.rewrite(context, let path_str = try_opt!(path.rewrite(context,
width - used_width, width - used_width,
offset + used_width)); offset + used_width));
format!("{} = {}", path_str, ty_str) format!("{} = {}", path_str, ty_str)
} }
}) })
} }
} }

View file

@ -21,7 +21,7 @@ pub fn extra_offset(text: &str, offset: usize) -> usize {
match text.rfind('\n') { match text.rfind('\n') {
// 1 for newline character // 1 for newline character
Some(idx) => text.len() - idx - 1 - offset, Some(idx) => text.len() - idx - 1 - offset,
None => text.len() None => text.len(),
} }
} }
@ -70,7 +70,7 @@ pub fn make_indent(width: usize) -> String {
pub fn format_visibility(vis: Visibility) -> &'static str { pub fn format_visibility(vis: Visibility) -> &'static str {
match vis { match vis {
Visibility::Public => "pub ", Visibility::Public => "pub ",
Visibility::Inherited => "" Visibility::Inherited => "",
} }
} }
@ -78,7 +78,7 @@ pub fn format_visibility(vis: Visibility) -> &'static str {
pub fn format_mutability(mutability: ast::Mutability) -> &'static str { pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
match mutability { match mutability {
ast::Mutability::MutMutable => "mut ", ast::Mutability::MutMutable => "mut ",
ast::Mutability::MutImmutable => "" ast::Mutability::MutImmutable => "",
} }
} }

View file

@ -351,7 +351,7 @@ impl<'a> FmtVisitor<'a> {
let prev_span = codemap::mk_sp(self.last_pos, span.lo); let prev_span = codemap::mk_sp(self.last_pos, span.lo);
let span_end = match self.snippet(prev_span).rfind('\n') { let span_end = match self.snippet(prev_span).rfind('\n') {
Some(offset) => self.last_pos + BytePos(offset as u32), Some(offset) => self.last_pos + BytePos(offset as u32),
None => span.lo None => span.lo,
}; };
self.format_missing(span_end); self.format_missing(span_end);
self.last_pos = span.hi; self.last_pos = span.hi;