Skip to content

Commit fb40a27

Browse files
committed
Merge pull request #85 from cassiersg/tuple
Implement reformat of tuple litterals
2 parents 9049413 + 7a6b4db commit fb40a27

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

src/expr.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,45 @@ impl<'a> FmtVisitor<'a> {
194194
format!("{}: {}", name, expr)
195195
}
196196

197+
fn rewrite_tuple_lit(&mut self, items: &[ptr::P<ast::Expr>], width: usize, offset: usize)
198+
-> String {
199+
// opening paren
200+
let indent = offset + 1;
201+
// In case of length 1, need a trailing comma
202+
if items.len() == 1 {
203+
return format!("({},)", self.rewrite_expr(&*items[0], width - 3, indent));
204+
}
205+
// Only last line has width-1 as budget, other may take max_width
206+
let item_strs: Vec<_> =
207+
items.iter()
208+
.enumerate()
209+
.map(|(i, item)| self.rewrite_expr(
210+
item,
211+
// last line : given width (minus "("+")"), other lines : max_width
212+
// (minus "("+","))
213+
if i == items.len() - 1 { width - 2 } else { config!(max_width) - indent - 2 },
214+
indent))
215+
.collect();
216+
let tactics = if item_strs.iter().any(|s| s.contains('\n')) {
217+
ListTactic::Vertical
218+
} else {
219+
ListTactic::HorizontalVertical
220+
};
221+
// FIXME handle comments
222+
let item_strs: Vec<_> = item_strs.into_iter().map(|s| (s, String::new())).collect();
223+
let fmt = ListFormatting {
224+
tactic: tactics,
225+
separator: ",",
226+
trailing_separator: SeparatorTactic::Never,
227+
indent: indent,
228+
h_width: width - 2,
229+
v_width: width - 2,
230+
};
231+
let item_str = write_list(&item_strs, &fmt);
232+
format!("({})", item_str)
233+
}
234+
235+
197236
pub fn rewrite_expr(&mut self, expr: &ast::Expr, width: usize, offset: usize) -> String {
198237
match expr.node {
199238
ast::Expr_::ExprLit(ref l) => {
@@ -219,6 +258,9 @@ impl<'a> FmtVisitor<'a> {
219258
width,
220259
offset);
221260
}
261+
ast::Expr_::ExprTup(ref items) => {
262+
return self.rewrite_tuple_lit(items, width, offset);
263+
}
222264
_ => {}
223265
}
224266

tests/idem/tuple.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// Test tuple litterals
2+
3+
fn foo() {
4+
let a = (a, a, a, a, a);
5+
let aaaaaaaaaaaaaaaa = (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaa, aaaaaaaaaaaaaa);
6+
let aaaaaaaaaaaaaaaaaaaaaa = (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
7+
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
8+
aaaaaaaaaaaaaaaaaaaaaaaaa,
9+
aaaa);
10+
let a = (a,);
11+
}

0 commit comments

Comments
 (0)