Merge pull request #2121 from topecongiro/clippy-lints

Refactor code via clippy
This commit is contained in:
Nick Cameron 2017-11-07 14:01:42 +13:00 committed by GitHub
commit 036917b691
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 289 additions and 302 deletions

11
Cargo.lock generated
View File

@ -6,6 +6,15 @@ dependencies = [
"memchr 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "derive-new"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)",
"syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "diff"
version = "0.1.10"
@ -98,6 +107,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
name = "rustfmt-nightly"
version = "0.2.14"
dependencies = [
"derive-new 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
"diff 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)",
"env_logger 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)",
"getopts 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)",
@ -242,6 +252,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[metadata]
"checksum aho-corasick 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)" = "500909c4f87a9e52355b26626d890833e9e1d53ac566db76c36faa984b889699"
"checksum derive-new 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "415f627ab054041c3eb748c2e1da0ef751989f5f0c386b63a098e545854a98ba"
"checksum diff 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "0a515461b6c8c08419850ced27bc29e86166dcdcde8fbe76f8b1f0589bb49472"
"checksum dtoa 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "09c3753c3db574d215cba4ea76018483895d7bff25a31b49ba45db21c48e50ab"
"checksum env_logger 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3ddf21e73e016298f5cb37d6ef8e8da8e39f91f9ec8b0df44b7deb16a9f8cd5b"

View File

@ -40,6 +40,7 @@ diff = "0.1"
log = "0.3"
env_logger = "0.4"
getopts = "0.2"
derive-new = "0.5"
[target.'cfg(unix)'.dependencies]
libc = "0.2.11"

View File

@ -254,15 +254,15 @@ fn extract_target_from_package(package: &Value) -> Option<Vec<Target>> {
let jtargets = get_json_array_with(package, "targets")?;
let mut targets: Vec<Target> = vec![];
for jtarget in jtargets {
targets.push(Target::from_json(&jtarget)?);
targets.push(Target::from_json(jtarget)?);
}
Some(targets)
}
fn filter_packages_with_hitlist<'a>(
fn filter_packages_with_hitlist(
packages: Vec<Value>,
workspace_hitlist: &'a WorkspaceHitlist,
) -> Result<Vec<Value>, &'a String> {
workspace_hitlist: &WorkspaceHitlist,
) -> Result<Vec<Value>, &String> {
let some_hitlist: Option<HashSet<&String>> =
workspace_hitlist.get_some().map(HashSet::from_iter);
if some_hitlist.is_none() {
@ -387,7 +387,7 @@ fn format_files(
for f in files {
print!(" {}", f.display());
}
println!("");
println!();
}
let mut command = Command::new("rustfmt")
.stdout(stdout)

View File

@ -33,7 +33,7 @@ use regex::Regex;
/// The default pattern of files to format.
///
/// We only want to format rust files by default.
const DEFAULT_PATTERN: &'static str = r".*\.rs";
const DEFAULT_PATTERN: &str = r".*\.rs";
#[derive(Debug)]
enum FormatDiffError {

View File

@ -73,9 +73,9 @@ impl CliOptions {
.map(|c| c == "nightly")
.unwrap_or(false);
if unstable_features && !rust_nightly {
return Err(FmtError::from(format!(
"Unstable features are only available on Nightly channel"
)));
return Err(FmtError::from(
"Unstable features are only available on Nightly channel",
));
} else {
options.unstable_features = unstable_features;
}

View File

@ -327,12 +327,10 @@ fn rewrite_comment_inner(
if line.is_empty() {
continue;
}
} else if is_prev_line_multi_line && !line.is_empty() {
result.push(' ')
} else {
if is_prev_line_multi_line && !line.is_empty() {
result.push(' ')
} else {
result.push_str(&comment_line_separator);
}
result.push_str(&comment_line_separator);
}
if config.wrap_comments() && line.len() > fmt.shape.width && !has_url(line) {

View File

@ -478,7 +478,7 @@ macro_rules! create_config {
$(
println!("{}{}", space_str, $dstring);
)+
println!("");
println!();
)+
}
}
@ -500,7 +500,7 @@ macro_rules! create_config {
///
/// Return the path if a config file exists, empty if no file exists, and Error for IO errors
pub fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
const CONFIG_FILE_NAMES: [&'static str; 2] = [".rustfmt.toml", "rustfmt.toml"];
const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
for config_file_name in &CONFIG_FILE_NAMES {
let config_file = dir.join(config_file_name);
match fs::metadata(&config_file) {

View File

@ -75,7 +75,7 @@ pub fn format_expr(
ast::ExprKind::Call(ref callee, ref args) => {
let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
let callee_str = callee.rewrite(context, shape)?;
rewrite_call(context, &callee_str, &args, inner_span, shape)
rewrite_call(context, &callee_str, args, inner_span, shape)
}
ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
@ -83,9 +83,7 @@ pub fn format_expr(
rewrite_pair(
&**lhs,
&**rhs,
"",
&format!(" {} ", context.snippet(op.span)),
"",
PairParts::new("", &format!(" {} ", context.snippet(op.span)), ""),
context,
shape,
context.config.binop_separator(),
@ -101,7 +99,7 @@ pub fn format_expr(
shape,
),
ast::ExprKind::Tup(ref items) => {
rewrite_tuple(context, &ptr_vec_to_ref_vec(&items), expr.span, shape)
rewrite_tuple(context, &ptr_vec_to_ref_vec(items), expr.span, shape)
}
ast::ExprKind::If(..) |
ast::ExprKind::IfLet(..) |
@ -186,9 +184,7 @@ pub fn format_expr(
ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
&**expr,
&**ty,
"",
" as ",
"",
PairParts::new("", " as ", ""),
context,
shape,
SeparatorPlace::Front,
@ -196,9 +192,7 @@ pub fn format_expr(
ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
&**expr,
&**ty,
"",
": ",
"",
PairParts::new("", ": ", ""),
context,
shape,
SeparatorPlace::Back,
@ -215,9 +209,7 @@ pub fn format_expr(
rewrite_pair(
&**expr,
&**repeats,
lbr,
"; ",
rbr,
PairParts::new(lbr, "; ", rbr),
context,
shape,
SeparatorPlace::Back,
@ -253,9 +245,7 @@ pub fn format_expr(
rewrite_pair(
&*lhs,
&*rhs,
"",
&sp_delim,
"",
PairParts::new("", &sp_delim, ""),
context,
shape,
SeparatorPlace::Front,
@ -315,12 +305,17 @@ pub fn format_expr(
})
}
#[derive(new)]
pub struct PairParts<'a> {
prefix: &'a str,
infix: &'a str,
suffix: &'a str,
}
pub fn rewrite_pair<LHS, RHS>(
lhs: &LHS,
rhs: &RHS,
prefix: &str,
infix: &str,
suffix: &str,
pp: PairParts,
context: &RewriteContext,
shape: Shape,
separator_place: SeparatorPlace,
@ -330,7 +325,7 @@ where
RHS: Rewrite,
{
let lhs_overhead = match separator_place {
SeparatorPlace::Back => shape.used_width() + prefix.len() + infix.trim_right().len(),
SeparatorPlace::Back => shape.used_width() + pp.prefix.len() + pp.infix.trim_right().len(),
SeparatorPlace::Front => shape.used_width(),
};
let lhs_shape = Shape {
@ -338,12 +333,12 @@ where
..shape
};
let lhs_result = lhs.rewrite(context, lhs_shape)
.map(|lhs_str| format!("{}{}", prefix, lhs_str))?;
.map(|lhs_str| format!("{}{}", pp.prefix, lhs_str))?;
// Try to the both lhs and rhs on the same line.
let rhs_orig_result = shape
.offset_left(last_line_width(&lhs_result) + infix.len())
.and_then(|s| s.sub_width(suffix.len()))
.offset_left(last_line_width(&lhs_result) + pp.infix.len())
.and_then(|s| s.sub_width(pp.suffix.len()))
.and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
if let Some(ref rhs_result) = rhs_orig_result {
// If the rhs looks like block expression, we allow it to stay on the same line
@ -354,10 +349,16 @@ where
.map(|first_line| first_line.ends_with('{'))
.unwrap_or(false);
if !rhs_result.contains('\n') || allow_same_line {
let one_line_width = last_line_width(&lhs_result) + infix.len()
+ first_line_width(&rhs_result) + suffix.len();
let one_line_width = last_line_width(&lhs_result) + pp.infix.len()
+ first_line_width(rhs_result) + pp.suffix.len();
if one_line_width <= shape.width {
return Some(format!("{}{}{}{}", lhs_result, infix, rhs_result, suffix));
return Some(format!(
"{}{}{}{}",
lhs_result,
pp.infix,
rhs_result,
pp.suffix
));
}
}
}
@ -366,8 +367,8 @@ where
// Re-evaluate the rhs because we have more space now:
let mut rhs_shape = match context.config.control_style() {
Style::Legacy => shape
.sub_width(suffix.len() + prefix.len())?
.visual_indent(prefix.len()),
.sub_width(pp.suffix.len() + pp.prefix.len())?
.visual_indent(pp.prefix.len()),
Style::Rfc => {
// Try to calculate the initial constraint on the right hand side.
let rhs_overhead = shape.rhs_overhead(context.config);
@ -376,31 +377,25 @@ where
}
};
let infix = match separator_place {
SeparatorPlace::Back => infix.trim_right(),
SeparatorPlace::Front => infix.trim_left(),
SeparatorPlace::Back => pp.infix.trim_right(),
SeparatorPlace::Front => pp.infix.trim_left(),
};
if separator_place == SeparatorPlace::Front {
rhs_shape = rhs_shape.offset_left(infix.len())?;
}
let rhs_result = rhs.rewrite(context, rhs_shape)?;
match separator_place {
SeparatorPlace::Back => Some(format!(
"{}{}\n{}{}{}",
lhs_result,
infix,
rhs_shape.indent.to_string(context.config),
rhs_result,
suffix
)),
SeparatorPlace::Front => Some(format!(
"{}\n{}{}{}{}",
lhs_result,
rhs_shape.indent.to_string(context.config),
infix,
rhs_result,
suffix
)),
}
let indent_str = rhs_shape.indent.to_string(context.config);
let infix_with_sep = match separator_place {
SeparatorPlace::Back => format!("{}\n{}", infix, indent_str),
SeparatorPlace::Front => format!("\n{}{}", indent_str, infix),
};
Some(format!(
"{}{}{}{}",
lhs_result,
infix_with_sep,
rhs_result,
pp.suffix
))
}
pub fn rewrite_array<'a, I>(
@ -641,7 +636,7 @@ fn rewrite_closure(
};
if no_return_type && !needs_block {
// block.stmts.len() == 1
if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
if let Some(expr) = stmt_expr(&block.stmts[0]) {
if let Some(rw) = if is_block_closure_forced(expr) {
rewrite_closure_with_block(context, shape, &prefix, expr)
} else {
@ -2004,7 +1999,7 @@ pub fn rewrite_call(
rewrite_call_inner(
context,
callee,
&ptr_vec_to_ref_vec(&args),
&ptr_vec_to_ref_vec(args),
span,
shape,
context.config.fn_call_width(),

View File

@ -75,11 +75,11 @@ fn compare_path_list_items(a: &ast::PathListItem, b: &ast::PathListItem) -> Orde
}
fn compare_path_list_item_lists(
a_items: &Vec<ast::PathListItem>,
b_items: &Vec<ast::PathListItem>,
a_items: &[ast::PathListItem],
b_items: &[ast::PathListItem],
) -> Ordering {
let mut a = a_items.clone();
let mut b = b_items.clone();
let mut a = a_items.to_owned();
let mut b = b_items.to_owned();
a.sort_by(|a, b| compare_path_list_items(a, b));
b.sort_by(|a, b| compare_path_list_items(a, b));
for comparison_pair in a.iter().zip(b.iter()) {
@ -94,15 +94,14 @@ fn compare_path_list_item_lists(
fn compare_view_path_types(a: &ast::ViewPath_, b: &ast::ViewPath_) -> Ordering {
use syntax::ast::ViewPath_::*;
match (a, b) {
(&ViewPathSimple(..), &ViewPathSimple(..)) => Ordering::Equal,
(&ViewPathSimple(..), _) => Ordering::Less,
(&ViewPathGlob(_), &ViewPathSimple(..)) => Ordering::Greater,
(&ViewPathGlob(_), &ViewPathGlob(_)) => Ordering::Equal,
(&ViewPathGlob(_), &ViewPathList(..)) => Ordering::Less,
(&ViewPathSimple(..), &ViewPathSimple(..)) | (&ViewPathGlob(_), &ViewPathGlob(_)) => {
Ordering::Equal
}
(&ViewPathSimple(..), _) | (&ViewPathGlob(_), &ViewPathList(..)) => Ordering::Less,
(&ViewPathList(_, ref a_items), &ViewPathList(_, ref b_items)) => {
compare_path_list_item_lists(a_items, b_items)
}
(&ViewPathList(..), _) => Ordering::Greater,
(&ViewPathGlob(_), &ViewPathSimple(..)) | (&ViewPathList(..), _) => Ordering::Greater,
}
}
@ -293,7 +292,7 @@ impl<'a> FmtVisitor<'a> {
}
Some(ref s) => {
self.format_missing_with_indent(source!(self, span).lo());
self.buffer.push_str(&s);
self.buffer.push_str(s);
self.last_pos = source!(self, span).hi();
}
None => {

View File

@ -215,7 +215,7 @@ impl<'a> FnSig<'a> {
unsafety: unsafety,
visibility: visibility.clone(),
},
visit::FnKind::Method(_, ref method_sig, vis, _) => {
visit::FnKind::Method(_, method_sig, vis, _) => {
let mut fn_sig = FnSig::from_method_sig(method_sig, generics);
fn_sig.defaultness = defualtness;
if let Some(vis) = vis {
@ -313,10 +313,10 @@ impl<'a> FmtVisitor<'a> {
let (mut result, force_newline_brace) =
rewrite_fn_base(&context, indent, ident, fn_sig, span, newline_brace, true)?;
if self.config.fn_brace_style() == BraceStyle::AlwaysNextLine || force_newline_brace {
newline_brace = true;
} else if last_line_width(&result) + 2 > self.shape().width {
// 2 = ` {`
// 2 = ` {`
if self.config.fn_brace_style() == BraceStyle::AlwaysNextLine || force_newline_brace
|| last_line_width(&result) + 2 > self.shape().width
{
newline_brace = true;
} else if !result.contains('\n') {
newline_brace = false;
@ -411,6 +411,18 @@ impl<'a> FmtVisitor<'a> {
None
}
pub fn visit_static(&mut self, static_parts: &StaticParts) {
let rewrite = rewrite_static(&self.get_context(), static_parts, self.block_indent);
self.push_rewrite(static_parts.span, rewrite);
}
pub fn visit_struct(&mut self, struct_parts: &StructParts) {
let is_tuple = struct_parts.def.is_tuple();
let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None)
.map(|s| if is_tuple { s + ";" } else { s });
self.push_rewrite(struct_parts.span, rewrite);
}
pub fn visit_enum(
&mut self,
ident: ast::Ident,
@ -428,8 +440,6 @@ impl<'a> FmtVisitor<'a> {
let generics_str = format_generics(
&self.get_context(),
generics,
"{",
"{",
self.config.item_brace_style(),
enum_def.variants.is_empty(),
self.block_indent,
@ -531,12 +541,7 @@ impl<'a> FmtVisitor<'a> {
// FIXME: Should limit the width, as we have a trailing comma
format_struct(
&context,
"",
field.node.name,
&ast::Visibility::Inherited,
&field.node.data,
None,
field.span,
&StructParts::from_variant(field),
indent,
Some(self.config.struct_variant_width()),
)?
@ -546,7 +551,7 @@ impl<'a> FmtVisitor<'a> {
// 1 = ','
rewrite_assign_rhs(&context, lhs, expr, shape.sub_width(1)?)?
} else {
String::from(field.node.name.to_string())
field.node.name.to_string()
},
};
@ -670,7 +675,7 @@ pub fn format_impl(
result.push_str(&outer_indent_str);
}
if result.chars().last().unwrap() == '{' {
if result.ends_with('{') {
result.push_str(&sep);
}
result.push('}');
@ -857,40 +862,62 @@ fn rewrite_trait_ref(
}
}
pub fn format_struct(
context: &RewriteContext,
item_name: &str,
pub struct StructParts<'a> {
prefix: &'a str,
ident: ast::Ident,
vis: &ast::Visibility,
struct_def: &ast::VariantData,
generics: Option<&ast::Generics>,
vis: &'a ast::Visibility,
def: &'a ast::VariantData,
generics: Option<&'a ast::Generics>,
span: Span,
}
impl<'a> StructParts<'a> {
fn format_header(&self) -> String {
format_header(self.prefix, self.ident, self.vis)
}
fn from_variant(variant: &'a ast::Variant) -> Self {
StructParts {
prefix: "",
ident: variant.node.name,
vis: &ast::Visibility::Inherited,
def: &variant.node.data,
generics: None,
span: variant.span,
}
}
pub fn from_item(item: &'a ast::Item) -> Self {
let (prefix, def, generics) = match item.node {
ast::ItemKind::Struct(ref def, ref generics) => ("struct ", def, generics),
ast::ItemKind::Union(ref def, ref generics) => ("union ", def, generics),
_ => unreachable!(),
};
StructParts {
prefix: prefix,
ident: item.ident,
vis: &item.vis,
def: def,
generics: Some(generics),
span: item.span,
}
}
}
fn format_struct(
context: &RewriteContext,
struct_parts: &StructParts,
offset: Indent,
one_line_width: Option<usize>,
) -> Option<String> {
match *struct_def {
ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
context,
item_name,
ident,
vis,
fields,
generics,
span,
offset,
),
ast::VariantData::Struct(ref fields, _) => format_struct_struct(
context,
item_name,
ident,
vis,
fields,
generics,
span,
offset,
one_line_width,
),
match *struct_parts.def {
ast::VariantData::Unit(..) => Some(format_unit_struct(struct_parts)),
ast::VariantData::Tuple(ref fields, _) => {
format_tuple_struct(context, struct_parts, fields, offset)
}
ast::VariantData::Struct(ref fields, _) => {
format_struct_struct(context, struct_parts, fields, offset, one_line_width)
}
}
}
@ -1052,35 +1079,30 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent)
}
}
fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
format!("{};", format_header(item_name, ident, vis))
fn format_unit_struct(p: &StructParts) -> String {
format!("{};", format_header(p.prefix, p.ident, p.vis))
}
pub fn format_struct_struct(
context: &RewriteContext,
item_name: &str,
ident: ast::Ident,
vis: &ast::Visibility,
struct_parts: &StructParts,
fields: &[ast::StructField],
generics: Option<&ast::Generics>,
span: Span,
offset: Indent,
one_line_width: Option<usize>,
) -> Option<String> {
let mut result = String::with_capacity(1024);
let span = struct_parts.span;
let header_str = format_header(item_name, ident, vis);
let header_str = struct_parts.format_header();
result.push_str(&header_str);
let header_hi = span.lo() + BytePos(header_str.len() as u32);
let body_lo = context.codemap.span_after(span, "{");
let generics_str = match generics {
let generics_str = match struct_parts.generics {
Some(g) => format_generics(
context,
g,
"{",
"{",
context.config.item_brace_style(),
fields.is_empty(),
offset,
@ -1178,21 +1200,18 @@ fn get_bytepos_after_visibility(
fn format_tuple_struct(
context: &RewriteContext,
item_name: &str,
ident: ast::Ident,
vis: &ast::Visibility,
struct_parts: &StructParts,
fields: &[ast::StructField],
generics: Option<&ast::Generics>,
span: Span,
offset: Indent,
) -> Option<String> {
let mut result = String::with_capacity(1024);
let span = struct_parts.span;
let header_str = format_header(item_name, ident, vis);
let header_str = struct_parts.format_header();
result.push_str(&header_str);
let body_lo = if fields.is_empty() {
let lo = get_bytepos_after_visibility(context, vis, span, ")");
let lo = get_bytepos_after_visibility(context, struct_parts.vis, span, ")");
context.codemap.span_after(mk_sp(lo, span.hi()), "(")
} else {
fields[0].span.lo()
@ -1211,7 +1230,7 @@ fn format_tuple_struct(
}
};
let where_clause_str = match generics {
let where_clause_str = match struct_parts.generics {
Some(generics) => {
let budget = context.budget(last_line_width(&header_str));
let shape = Shape::legacy(budget, offset);
@ -1465,16 +1484,73 @@ pub fn rewrite_struct_field(
)
}
pub fn rewrite_static(
prefix: &str,
vis: &ast::Visibility,
pub struct StaticParts<'a> {
prefix: &'a str,
vis: &'a ast::Visibility,
ident: ast::Ident,
ty: &ast::Ty,
ty: &'a ast::Ty,
mutability: ast::Mutability,
expr_opt: Option<&ptr::P<ast::Expr>>,
offset: Indent,
expr_opt: Option<&'a ptr::P<ast::Expr>>,
span: Span,
}
impl<'a> StaticParts<'a> {
pub fn from_item(item: &'a ast::Item) -> Self {
let (prefix, ty, mutability, expr) = match item.node {
ast::ItemKind::Static(ref ty, mutability, ref expr) => ("static", ty, mutability, expr),
ast::ItemKind::Const(ref ty, ref expr) => {
("const", ty, ast::Mutability::Immutable, expr)
}
_ => unreachable!(),
};
StaticParts {
prefix: prefix,
vis: &item.vis,
ident: item.ident,
ty: ty,
mutability: mutability,
expr_opt: Some(expr),
span: item.span,
}
}
pub fn from_trait_item(ti: &'a ast::TraitItem) -> Self {
let (ty, expr_opt) = match ti.node {
ast::TraitItemKind::Const(ref ty, ref expr_opt) => (ty, expr_opt),
_ => unreachable!(),
};
StaticParts {
prefix: "const",
vis: &ast::Visibility::Inherited,
ident: ti.ident,
ty: ty,
mutability: ast::Mutability::Immutable,
expr_opt: expr_opt.as_ref(),
span: ti.span,
}
}
pub fn from_impl_item(ii: &'a ast::ImplItem) -> Self {
let (ty, expr) = match ii.node {
ast::ImplItemKind::Const(ref ty, ref expr) => (ty, expr),
_ => unreachable!(),
};
StaticParts {
prefix: "const",
vis: &ii.vis,
ident: ii.ident,
ty: ty,
mutability: ast::Mutability::Immutable,
expr_opt: Some(expr),
span: ii.span,
}
}
}
fn rewrite_static(
context: &RewriteContext,
static_parts: &StaticParts,
offset: Indent,
) -> Option<String> {
let colon = colon_spaces(
context.config.space_before_type_annotation(),
@ -1482,19 +1558,18 @@ pub fn rewrite_static(
);
let prefix = format!(
"{}{} {}{}{}",
format_visibility(vis),
prefix,
format_mutability(mutability),
ident,
format_visibility(static_parts.vis),
static_parts.prefix,
format_mutability(static_parts.mutability),
static_parts.ident,
colon,
);
// 2 = " =".len()
let ty_str = ty.rewrite(
context,
Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?,
)?;
let ty_shape =
Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?;
let ty_str = static_parts.ty.rewrite(context, ty_shape)?;
if let Some(expr) = expr_opt {
if let Some(expr) = static_parts.expr_opt {
let lhs = format!("{}{} =", prefix, ty_str);
// 1 = ;
let remaining_width = context.budget(offset.block_indent + 1);
@ -1503,7 +1578,9 @@ pub fn rewrite_static(
lhs,
expr,
Shape::legacy(remaining_width, offset.block_only()),
).and_then(|res| recover_comment_removed(res, span, context))
).and_then(|res| {
recover_comment_removed(res, static_parts.span, context)
})
.map(|s| if s.ends_with(';') { s } else { s + ";" })
} else {
Some(format!("{}{};", prefix, ty_str))
@ -2318,16 +2395,16 @@ fn rewrite_generics_inner(
impl<'a> Rewrite for GenericsArg<'a> {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
match *self {
GenericsArg::Lifetime(ref lifetime) => lifetime.rewrite(context, shape),
GenericsArg::TyParam(ref ty) => ty.rewrite(context, shape),
GenericsArg::Lifetime(lifetime) => lifetime.rewrite(context, shape),
GenericsArg::TyParam(ty) => ty.rewrite(context, shape),
}
}
}
impl<'a> Spanned for GenericsArg<'a> {
fn span(&self) -> Span {
match *self {
GenericsArg::Lifetime(ref lifetime) => lifetime.span(),
GenericsArg::TyParam(ref ty) => ty.span(),
GenericsArg::Lifetime(lifetime) => lifetime.span(),
GenericsArg::TyParam(ty) => ty.span(),
}
}
}
@ -2693,8 +2770,6 @@ fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> S
fn format_generics(
context: &RewriteContext,
generics: &ast::Generics,
opener: &str,
terminator: &str,
brace_style: BraceStyle,
force_same_line_brace: bool,
offset: Indent,
@ -2720,7 +2795,7 @@ fn format_generics(
brace_style,
Shape::legacy(budget, offset.block_only()),
Density::Tall,
terminator,
"{",
Some(span.hi()),
span_end_before_where,
option,
@ -2740,9 +2815,11 @@ fn format_generics(
// and hence we take the closer into account as well for one line budget.
// We assume that the closer has the same length as the opener.
let overhead = if force_same_line_brace {
1 + opener.len() + opener.len()
// 3 = ` {}`
3
} else {
1 + opener.len()
// 2 = ` {`
2
};
let forbid_same_line_brace = overhead > remaining_budget;
if !forbid_same_line_brace && same_line_brace {
@ -2751,7 +2828,7 @@ fn format_generics(
result.push('\n');
result.push_str(&offset.block_only().to_string(context.config));
}
result.push_str(opener);
result.push('{');
Some(result)
}

View File

@ -10,6 +10,8 @@
#![feature(rustc_private)]
#[macro_use]
extern crate derive_new;
extern crate diff;
#[macro_use]
extern crate log;
@ -307,7 +309,7 @@ where
// We always skip children for the "Plain" write mode, since there is
// nothing to distinguish the nested module contents.
let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
for (path, module) in modules::list_files(krate, parse_session.codemap()) {
for (path, module) in modules::list_files(krate, parse_session.codemap())? {
if skip_children && path.as_path() != main_file {
continue;
}

View File

@ -35,7 +35,7 @@ use rewrite::{Rewrite, RewriteContext};
use shape::{Indent, Shape};
use utils::mk_sp;
const FORCED_BRACKET_MACROS: &'static [&'static str] = &["vec!"];
const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
// FIXME: use the enum from libsyntax?
#[derive(Clone, Copy, PartialEq, Eq)]
@ -70,10 +70,10 @@ pub enum MacroArg {
impl Rewrite for MacroArg {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
match self {
&MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
&MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
&MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
match *self {
MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
}
}
}

View File

@ -10,6 +10,7 @@
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::io;
use syntax::ast;
use syntax::codemap;
@ -23,7 +24,7 @@ use utils::contains_skip;
pub fn list_files<'a>(
krate: &'a ast::Crate,
codemap: &codemap::CodeMap,
) -> BTreeMap<PathBuf, &'a ast::Mod> {
) -> Result<BTreeMap<PathBuf, &'a ast::Mod>, io::Error> {
let mut result = BTreeMap::new(); // Enforce file order determinism
let root_filename: PathBuf = codemap.span_to_filename(krate.span).into();
list_submodules(
@ -31,9 +32,9 @@ pub fn list_files<'a>(
root_filename.parent().unwrap(),
codemap,
&mut result,
);
)?;
result.insert(root_filename, &krate.module);
result
Ok(result)
}
/// Recursively list all external modules included in a module.
@ -42,7 +43,7 @@ fn list_submodules<'a>(
search_dir: &Path,
codemap: &codemap::CodeMap,
result: &mut BTreeMap<PathBuf, &'a ast::Mod>,
) {
) -> Result<(), io::Error> {
debug!("list_submodules: search_dir: {:?}", search_dir);
for item in &module.items {
if let ast::ItemKind::Mod(ref sub_mod) = item.node {
@ -52,15 +53,16 @@ fn list_submodules<'a>(
let dir_path = if is_internal {
search_dir.join(&item.ident.to_string())
} else {
let mod_path = module_file(item.ident, &item.attrs, search_dir, codemap);
let mod_path = module_file(item.ident, &item.attrs, search_dir, codemap)?;
let dir_path = mod_path.parent().unwrap().to_owned();
result.insert(mod_path, sub_mod);
dir_path
};
list_submodules(sub_mod, &dir_path, codemap, result);
list_submodules(sub_mod, &dir_path, codemap, result)?;
}
}
}
Ok(())
}
/// Find the file corresponding to an external mod
@ -69,13 +71,16 @@ fn module_file(
attrs: &[ast::Attribute],
dir_path: &Path,
codemap: &codemap::CodeMap,
) -> PathBuf {
) -> Result<PathBuf, io::Error> {
if let Some(path) = parser::Parser::submod_path_from_attr(attrs, dir_path) {
return path;
return Ok(path);
}
match parser::Parser::default_submod_path(id, dir_path, codemap).result {
Ok(parser::ModulePathSuccess { path, .. }) => path,
Err(_) => panic!("Couldn't find module {}", id),
Ok(parser::ModulePathSuccess { path, .. }) => Ok(path),
Err(_) => Err(io::Error::new(
io::ErrorKind::Other,
format!("Couldn't find module {}", id),
)),
}
}

View File

@ -16,7 +16,7 @@ use spanned::Spanned;
use codemap::SpanUtils;
use comment::FindUncommented;
use expr::{can_be_overflowed_expr, rewrite_call_inner, rewrite_pair, rewrite_unary_prefix,
wrap_struct_field};
wrap_struct_field, PairParts};
use lists::{itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
struct_lit_tactic, write_list, DefinitiveListTactic, SeparatorPlace, SeparatorTactic};
use rewrite::{Rewrite, RewriteContext};
@ -65,9 +65,7 @@ impl Rewrite for Pat {
rewrite_pair(
&**lhs,
&**rhs,
"",
infix,
"",
PairParts::new("", infix, ""),
context,
shape,
SeparatorPlace::Front,

View File

@ -19,7 +19,7 @@ use syntax::symbol::keywords;
use spanned::Spanned;
use codemap::SpanUtils;
use config::{IndentStyle, Style, TypeDensity};
use expr::{rewrite_pair, rewrite_tuple, rewrite_unary_prefix, wrap_args_with_parens};
use expr::{rewrite_pair, rewrite_tuple, rewrite_unary_prefix, wrap_args_with_parens, PairParts};
use items::{format_generics_item_list, generics_shape_from_config};
use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListTactic, Separator,
SeparatorPlace, SeparatorTactic};
@ -695,7 +695,7 @@ impl Rewrite for ast::Ty {
}
ast::TyKind::Tup(ref items) => rewrite_tuple(
context,
&::utils::ptr_vec_to_ref_vec(&items),
&::utils::ptr_vec_to_ref_vec(items),
self.span,
shape,
),
@ -709,9 +709,7 @@ impl Rewrite for ast::Ty {
rewrite_pair(
&**ty,
&**repeats,
lbr,
"; ",
rbr,
PairParts::new(lbr, "; ", rbr),
context,
shape,
SeparatorPlace::Back,

View File

@ -19,7 +19,7 @@ use rewrite::RewriteContext;
use shape::Shape;
// When we get scoped annotations, we should have rustfmt::skip.
const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
const SKIP_ANNOTATION: &str = "rustfmt_skip";
// Computes the length of a string's last line, minus offset.
pub fn extra_offset(text: &str, shape: Shape) -> usize {
@ -298,7 +298,6 @@ macro_rules! impl_enum_serialize_and_deserialize {
impl<'de> ::serde::de::Deserialize<'de> for $e {
fn deserialize<D>(d: D) -> Result<Self, D::Error>
where D: ::serde::Deserializer<'de> {
use std::ascii::AsciiExt;
use serde::de::{Error, Visitor};
use std::marker::PhantomData;
use std::fmt;
@ -328,7 +327,6 @@ macro_rules! impl_enum_serialize_and_deserialize {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
use std::ascii::AsciiExt;
$(
if stringify!($x).eq_ignore_ascii_case(s) {
return Ok($e::$x);

View File

@ -23,9 +23,8 @@ use comment::{contains_comment, recover_missing_comment_in_span, remove_trailing
CodeCharKind, CommentCodeSlices, FindUncommented};
use comment::rewrite_comment;
use config::{BraceStyle, Config};
use items::{format_impl, format_struct, format_struct_struct, format_trait,
rewrite_associated_impl_type, rewrite_associated_type, rewrite_static,
rewrite_type_alias, FnSig};
use items::{format_impl, format_trait, rewrite_associated_impl_type, rewrite_associated_type,
rewrite_type_alias, FnSig, StaticParts, StructParts};
use lists::{itemize_list, write_list, DefinitiveListTactic, ListFormatting, SeparatorPlace,
SeparatorTactic};
use macros::{rewrite_macro, MacroPosition};
@ -197,12 +196,11 @@ impl<'a> FmtVisitor<'a> {
}
}
let mut unindent_comment = self.is_if_else_block && !b.stmts.is_empty();
if unindent_comment {
let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
unindent_comment = snippet.contains("//") || snippet.contains("/*");
}
snippet.contains("//") || snippet.contains("/*")
};
// FIXME: we should compress any newlines here to just one
if unindent_comment {
self.block_indent = self.block_indent.block_unindent(self.config);
@ -243,24 +241,13 @@ impl<'a> FmtVisitor<'a> {
generics: &ast::Generics,
fd: &ast::FnDecl,
s: Span,
_: ast::NodeId,
defaultness: ast::Defaultness,
inner_attrs: Option<&[ast::Attribute]>,
) {
let indent = self.block_indent;
let block;
let rewrite = match fk {
visit::FnKind::ItemFn(ident, _, _, _, _, b) => {
block = b;
self.rewrite_fn(
indent,
ident,
&FnSig::from_fn_kind(&fk, generics, fd, defaultness),
mk_sp(s.lo(), b.span.lo()),
b,
)
}
visit::FnKind::Method(ident, _, _, b) => {
visit::FnKind::ItemFn(ident, _, _, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
block = b;
self.rewrite_fn(
indent,
@ -357,22 +344,8 @@ impl<'a> FmtVisitor<'a> {
let rw = rewrite_extern_crate(&self.get_context(), item);
self.push_rewrite(item.span, rw);
}
ast::ItemKind::Struct(ref def, ref generics) => {
let rewrite = format_struct(
&self.get_context(),
"struct ",
item.ident,
&item.vis,
def,
Some(generics),
item.span,
self.block_indent,
None,
).map(|s| match *def {
ast::VariantData::Tuple(..) => s + ";",
_ => s,
});
self.push_rewrite(item.span, rewrite);
ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
self.visit_struct(&StructParts::from_item(item));
}
ast::ItemKind::Enum(ref def, ref generics) => {
self.format_missing_with_indent(source!(self, item.span).lo());
@ -390,33 +363,8 @@ impl<'a> FmtVisitor<'a> {
self.format_missing_with_indent(source!(self, item.span).lo());
self.format_foreign_mod(foreign_mod, item.span);
}
ast::ItemKind::Static(ref ty, mutability, ref expr) => {
let rewrite = rewrite_static(
"static",
&item.vis,
item.ident,
ty,
mutability,
Some(expr),
self.block_indent,
item.span,
&self.get_context(),
);
self.push_rewrite(item.span, rewrite);
}
ast::ItemKind::Const(ref ty, ref expr) => {
let rewrite = rewrite_static(
"const",
&item.vis,
item.ident,
ty,
ast::Mutability::Immutable,
Some(expr),
self.block_indent,
item.span,
&self.get_context(),
);
self.push_rewrite(item.span, rewrite);
ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
self.visit_static(&StaticParts::from_item(item));
}
ast::ItemKind::AutoImpl(..) => {
// FIXME(#78): format impl definitions.
@ -427,7 +375,6 @@ impl<'a> FmtVisitor<'a> {
generics,
decl,
item.span,
item.id,
ast::Defaultness::Final,
Some(&item.attrs),
)
@ -444,20 +391,6 @@ impl<'a> FmtVisitor<'a> {
);
self.push_rewrite(item.span, rewrite);
}
ast::ItemKind::Union(ref def, ref generics) => {
let rewrite = format_struct_struct(
&self.get_context(),
"union ",
item.ident,
&item.vis,
def.fields(),
Some(generics),
item.span,
self.block_indent,
None,
);
self.push_rewrite(item.span, rewrite);
}
ast::ItemKind::GlobalAsm(..) => {
let snippet = Some(self.snippet(item.span));
self.push_rewrite(item.span, snippet);
@ -479,20 +412,7 @@ impl<'a> FmtVisitor<'a> {
}
match ti.node {
ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
let rewrite = rewrite_static(
"const",
&ast::Visibility::Inherited,
ti.ident,
ty,
ast::Mutability::Immutable,
expr_opt.as_ref(),
self.block_indent,
ti.span,
&self.get_context(),
);
self.push_rewrite(ti.span, rewrite);
}
ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
ast::TraitItemKind::Method(ref sig, None) => {
let indent = self.block_indent;
let rewrite =
@ -505,7 +425,6 @@ impl<'a> FmtVisitor<'a> {
&ti.generics,
&sig.decl,
ti.span,
ti.id,
ast::Defaultness::Final,
Some(&ti.attrs),
);
@ -541,25 +460,11 @@ impl<'a> FmtVisitor<'a> {
&ii.generics,
&sig.decl,
ii.span,
ii.id,
ii.defaultness,
Some(&ii.attrs),
);
}
ast::ImplItemKind::Const(ref ty, ref expr) => {
let rewrite = rewrite_static(
"const",
&ii.vis,
ii.ident,
ty,
ast::Mutability::Immutable,
Some(expr),
self.block_indent,
ii.span,
&self.get_context(),
);
self.push_rewrite(ii.span, rewrite);
}
ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
ast::ImplItemKind::Type(ref ty) => {
let rewrite = rewrite_associated_impl_type(
ii.ident,