Update indentation heuristics for single arg functions

This commit is contained in:
Marcus Klaas 2015-09-09 23:09:39 +02:00
parent c680bb4030
commit 659c9b9037
13 changed files with 170 additions and 150 deletions

View File

@ -23,8 +23,8 @@ pub fn rewrite_chain(orig_expr: &ast::Expr,
-> Option<String> {
let mut expr = orig_expr;
let mut rewrites = Vec::new();
let indent = context.block_indent + context.config.tab_spaces;
let max_width = context.config.max_width - context.config.tab_spaces;
let indent = offset + context.config.tab_spaces;
let max_width = try_opt!(context.config.max_width.checked_sub(indent));
loop {
match expr.node {
@ -103,7 +103,8 @@ pub fn rewrite_chain(orig_expr: &ast::Expr,
// Put the first link on the same line as parent, if it fits.
let first_connector = if parent_rewrite.len() + rewrites[0].len() <= width &&
!rewrites[0].contains('\n') {
!rewrites[0].contains('\n') ||
parent_rewrite.len() <= context.config.tab_spaces {
""
} else {
&connector[..]
@ -128,6 +129,10 @@ fn rewrite_method_call(method_name: ast::Ident,
};
let callee_str = format!(".{}{}", method_name, type_str);
let inner_context = &RewriteContext {
block_indent: offset,
..*context
};
rewrite_call(context, &callee_str, args, span, width, offset)
rewrite_call(inner_context, &callee_str, args, span, width, offset)
}

View File

@ -41,9 +41,9 @@ pub fn rewrite_comment(orig: &str, block_style: bool, width: usize, offset: usiz
let line_breaks = s.chars().filter(|&c| c == '\n').count();
let (_, mut s) = s.lines()
.enumerate()
.map(|(i, mut line)| {
line = line.trim();
.enumerate()
.map(|(i, mut line)| {
line = line.trim();
// Drop old closer.
if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
@ -166,11 +166,11 @@ pub fn contains_comment(text: &str) -> bool {
pub fn uncommented(text: &str) -> String {
CharClasses::new(text.chars())
.filter_map(|(s, c)| {
match s {
CodeCharKind::Normal => Some(c),
CodeCharKind::Comment => None,
}
})
match s {
CodeCharKind::Normal => Some(c),
CodeCharKind::Comment => None,
}
})
.collect()
}

View File

@ -1022,8 +1022,8 @@ fn rewrite_struct_lit<'a>(context: &RewriteContext,
};
let field_iter = fields.into_iter()
.map(StructLitField::Regular)
.chain(base.into_iter().map(StructLitField::Base));
.map(StructLitField::Regular)
.chain(base.into_iter().map(StructLitField::Base));
let inner_context = &RewriteContext { block_indent: indent, ..*context };
@ -1035,7 +1035,8 @@ fn rewrite_struct_lit<'a>(context: &RewriteContext,
StructLitField::Regular(ref field) => field.span.lo,
StructLitField::Base(ref expr) => {
let last_field_hi = fields.last()
.map_or(span.lo, |field| field.span.hi);
.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();

View File

@ -38,10 +38,10 @@ impl Rewrite for ast::ViewPath {
let path_str = try_opt!(path.rewrite(context, width - ident_str.len() - 4, offset));
Some(if path.segments.last().unwrap().identifier == ident {
path_str
} else {
format!("{} as {}", path_str, ident_str)
})
path_str
} else {
format!("{} as {}", path_str, ident_str)
})
}
}
}

View File

@ -333,12 +333,12 @@ impl<'a> FmtVisitor<'a> {
// FIXME: the comment for the self argument is dropped. This is blocked
// on rust issue #27522.
let min_args = explicit_self
.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args))
.map(|self_str| {
arg_item_strs[0] = self_str;
2
})
.unwrap_or(1);
.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args))
.map(|self_str| {
arg_item_strs[0] = self_str;
2
})
.unwrap_or(1);
// Comments between args
let mut arg_items = Vec::new();
@ -761,9 +761,9 @@ impl<'a> FmtVisitor<'a> {
let indent = self.block_indent + self.config.tab_spaces;
let mut attr_str = field.node
.attrs
.rewrite(&self.get_context(), self.config.max_width - indent, indent)
.unwrap();
.attrs
.rewrite(&self.get_context(), self.config.max_width - indent, indent)
.unwrap();
if !attr_str.is_empty() {
attr_str.push('\n');
attr_str.push_str(&make_indent(indent));
@ -804,18 +804,18 @@ impl<'a> FmtVisitor<'a> {
// FIXME: don't unwrap
let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset).unwrap());
let ty_strs = tys.iter()
.map(|ty_param| ty_param.rewrite(&context, h_budget, offset).unwrap());
.map(|ty_param| ty_param.rewrite(&context, h_budget, offset).unwrap());
// Extract comments between generics.
let lt_spans = lifetimes.iter()
.map(|l| {
let hi = if l.bounds.is_empty() {
l.lifetime.span.hi
} else {
l.bounds[l.bounds.len() - 1].span.hi
};
codemap::mk_sp(l.lifetime.span.lo, hi)
});
.map(|l| {
let hi = if l.bounds.is_empty() {
l.lifetime.span.hi
} else {
l.bounds[l.bounds.len() - 1].span.hi
};
codemap::mk_sp(l.lifetime.span.lo, hi)
});
let ty_spans = tys.iter().map(span_for_ty_param);
let items = itemize_list(self.codemap,

View File

@ -283,22 +283,23 @@ impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
};
// Post-comment
let next_start = match self.inner.peek() {
Some(ref next_item) => (self.get_lo)(next_item),
None => self.next_span_start,
};
let post_snippet = self.codemap
.span_to_snippet(codemap::mk_sp((self.get_hi)(&item), next_start))
.unwrap();
let next_start = match self.inner.peek() {
Some(ref next_item) => (self.get_lo)(next_item),
None => self.next_span_start,
};
let post_snippet = self.codemap
.span_to_snippet(codemap::mk_sp((self.get_hi)(&item),
next_start))
.unwrap();
let comment_end = match self.inner.peek() {
Some(..) => {
let block_open_index = post_snippet.find("/*");
let newline_index = post_snippet.find('\n');
let separator_index = post_snippet.find_uncommented(",").unwrap();
let comment_end = match self.inner.peek() {
Some(..) => {
let block_open_index = post_snippet.find("/*");
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.
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

View File

@ -197,11 +197,11 @@ fn rewrite_segment(segment: &ast::PathSegment,
!data.types.is_empty() ||
!data.bindings.is_empty() => {
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)))
.collect::<Vec<_>>();
.iter()
.map(SegmentParam::LifeTime)
.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);
let list_lo = span_after(codemap::mk_sp(*span_lo, span_hi), "<", context.codemap);
@ -273,54 +273,66 @@ impl Rewrite for ast::WherePredicate {
// TODO dead spans?
// TODO assumes we'll always fit on one line...
Some(match *self {
ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
ref bounded_ty,
ref bounds,
..}) => {
if !bound_lifetimes.is_empty() {
let lifetime_str = bound_lifetimes.iter()
.map(|lt| lt.rewrite(context, width, offset).unwrap())
.collect::<Vec<_>>()
.join(", ");
let type_str = pprust::ty_to_string(bounded_ty);
ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
ref bounded_ty,
ref bounds,
.. }) => {
if !bound_lifetimes.is_empty() {
let lifetime_str = bound_lifetimes.iter()
.map(|lt| lt.rewrite(context, width, offset).unwrap())
.collect::<Vec<_>>()
.join(", ");
let type_str = pprust::ty_to_string(bounded_ty);
// 8 = "for<> : ".len()
let used_width = lifetime_str.len() + type_str.len() + 8;
let bounds_str = bounds.iter()
.map(|ty_bound| ty_bound.rewrite(context, width - used_width, offset + used_width).unwrap())
.collect::<Vec<_>>()
.join(" + ");
let used_width = lifetime_str.len() + type_str.len() + 8;
let bounds_str = bounds.iter()
.map(|ty_bound| {
ty_bound
.rewrite(context,
width - used_width,
offset + used_width)
.unwrap()
})
.collect::<Vec<_>>()
.join(" + ");
format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
} else {
let type_str = pprust::ty_to_string(bounded_ty);
format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
} else {
let type_str = pprust::ty_to_string(bounded_ty);
// 2 = ": ".len()
let used_width = type_str.len() + 2;
let bounds_str = bounds.iter()
.map(|ty_bound| ty_bound.rewrite(context, width - used_width, offset + used_width).unwrap())
.collect::<Vec<_>>()
.join(" + ");
let used_width = type_str.len() + 2;
let bounds_str = bounds.iter()
.map(|ty_bound| {
ty_bound
.rewrite(context,
width - used_width,
offset + used_width)
.unwrap()
})
.collect::<Vec<_>>()
.join(" + ");
format!("{}: {}", type_str, bounds_str)
}
format!("{}: {}", type_str, bounds_str)
}
ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
ref bounds,
..}) => {
format!("{}: {}",
}
ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
ref bounds,
.. }) => {
format!("{}: {}",
pprust::lifetime_to_string(lifetime),
bounds.iter().map(pprust::lifetime_to_string)
.collect::<Vec<_>>().join(" + "))
}
ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
let ty_str = pprust::ty_to_string(ty);
}
ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
let ty_str = pprust::ty_to_string(ty);
// 3 = " = ".len()
let used_width = 3 + ty_str.len();
let path_str = try_opt!(path.rewrite(context,
let used_width = 3 + ty_str.len();
let path_str = try_opt!(path.rewrite(context,
width - used_width,
offset + used_width));
format!("{} = {}", path_str, ty_str)
}
})
format!("{} = {}", path_str, ty_str)
}
})
}
}
@ -370,10 +382,10 @@ impl Rewrite for ast::TyParam {
result.push_str(": ");
let bounds = self.bounds
.iter()
.map(|ty_bound| ty_bound.rewrite(context, width, offset).unwrap())
.collect::<Vec<_>>()
.join(" + ");
.iter()
.map(|ty_bound| ty_bound.rewrite(context, width, offset).unwrap())
.collect::<Vec<_>>()
.join(" + ");
result.push_str(&bounds);
}
@ -391,10 +403,10 @@ impl Rewrite for ast::PolyTraitRef {
fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
if !self.bound_lifetimes.is_empty() {
let lifetime_str = self.bound_lifetimes
.iter()
.map(|lt| lt.rewrite(context, width, offset).unwrap())
.collect::<Vec<_>>()
.join(", ");
.iter()
.map(|lt| lt.rewrite(context, width, offset).unwrap())
.collect::<Vec<_>>()
.join(", ");
// 6 is "for<> ".len()
let extra_offset = lifetime_str.len() + 6;
let max_path_width = try_opt!(width.checked_sub(extra_offset));

View File

@ -97,11 +97,11 @@ pub fn end_typaram(typaram: &ast::TyParam) -> BytePos {
typaram.bounds
.last()
.map(|bound| {
match *bound {
ast::RegionTyParamBound(ref lt) => lt.span,
ast::TraitTyParamBound(ref prt, _) => prt.span,
}
})
match *bound {
ast::RegionTyParamBound(ref lt) => lt.span,
ast::TraitTyParamBound(ref prt, _) => prt.span,
}
})
.unwrap_or(typaram.span)
.hi
}

View File

@ -289,8 +289,10 @@ impl<'a> FmtVisitor<'a> {
true
} else {
let rewrite = attrs
.rewrite(&self.get_context(), self.config.max_width - self.block_indent, self.block_indent)
.unwrap();
.rewrite(&self.get_context(),
self.config.max_width - self.block_indent,
self.block_indent)
.unwrap();
self.buffer.push_str(&rewrite);
let last = attrs.last().unwrap();
self.last_pos = last.span.hi;

View File

@ -120,8 +120,8 @@ pub fn idempotent_check(filename: String) -> Result<(), HashMap<String, Vec<Mism
// panic to return a result in case of failure. This has the advantage of smoothing the road to
// multithreaded rustfmt
thread::catch_panic(move || {
run(args, WriteMode::Return(HANDLE_RESULT), config);
}).map_err(|any| *any.downcast().ok().expect("Downcast failed."))
run(args, WriteMode::Return(HANDLE_RESULT), config);
}).map_err(|any| *any.downcast().ok().expect("Downcast failed."))
}
@ -153,19 +153,19 @@ fn read_significant_comments(file_name: &str) -> HashMap<String, String> {
// Matches lines containing significant comments or whitespace.
let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)").ok()
.expect("Failed creating pattern 2.");
.expect("Failed creating pattern 2.");
reader.lines()
.map(|line| line.ok().expect("Failed getting line."))
.take_while(|line| line_regex.is_match(&line))
.filter_map(|line| {
regex.captures_iter(&line)
.next()
.map(|capture| {
(capture.at(1).expect("Couldn't unwrap capture.").to_owned(),
capture.at(2).expect("Couldn't unwrap capture.").to_owned())
})
})
regex.captures_iter(&line)
.next()
.map(|capture| {
(capture.at(1).expect("Couldn't unwrap capture.").to_owned(),
capture.at(2).expect("Couldn't unwrap capture.").to_owned())
})
})
.collect()
}

View File

@ -9,31 +9,30 @@ fn main() {
b: WithType, // argument
// ignored
_| {
(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb)
};
(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb)
};
let block_body = move |xxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
ref yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy| {
xxxxxxxxxxxxxxxxxxxxxxxxxxxxx + yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
};
xxxxxxxxxxxxxxxxxxxxxxxxxxxxx + yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
};
let loooooooooooooong_name = |field| {
// TODO(#27): format comments.
if field.node.attrs.len() > 0 {
field.node.attrs[0].span.lo
} else {
field.span.lo
}
};
if field.node.attrs.len() > 0 {
field.node.attrs[0].span.lo
} else {
field.span.lo
}
};
let block_me = |field| {
if true_story() {
1
} else {
2
}
};
if true_story() {
1
} else {
2
}
};
let unblock_me = |trivial| closure();
@ -44,17 +43,17 @@ fn main() {
};
let test = || {
do_something();
do_something_else();
};
do_something();
do_something_else();
};
let arg_test = |big_argument_name, test123| {
looooooooooooooooooong_function_naaaaaaaaaaaaaaaaame()
};
looooooooooooooooooong_function_naaaaaaaaaaaaaaaaame()
};
let arg_test = |big_argument_name, test123| {
looooooooooooooooooong_function_naaaaaaaaaaaaaaaaame()
};
looooooooooooooooooong_function_naaaaaaaaaaaaaaaaame()
};
let simple_closure = move || -> () {};

View File

@ -4,6 +4,6 @@
fn matcher() {
Some(while true {
test();
})
test();
})
}

View File

@ -89,13 +89,13 @@ fn bar() {
}
syntactically_correct(loop {
sup('?');
},
sup('?');
},
if cond {
0
} else {
1
});
0
} else {
1
});
let third = ..10;
let infi_range = ..;