1
Fork 0

Format tuple-like structs

This commit is contained in:
Marcus Klaas 2015-06-23 15:58:58 +02:00
parent 66c6fe5334
commit 0ef5db9496
22 changed files with 1075 additions and 514 deletions

View file

@ -8,17 +8,15 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use utils::*;
use lists::{write_list, ListFormatting, SeparatorTactic, ListTactic};
use rewrite::{Rewrite, RewriteContext};
use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic, ListTactic};
use string::{StringFormat, rewrite_string};
use syntax::{ast, ptr};
use syntax::codemap::{Pos, Span};
use syntax::codemap::{Pos, Span, BytePos};
use syntax::parse::token;
use syntax::print::pprust;
use MIN_STRING;
impl Rewrite for ast::Expr {
fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
match self.node {
@ -33,7 +31,7 @@ impl Rewrite for ast::Expr {
}
}
ast::Expr_::ExprCall(ref callee, ref args) => {
return rewrite_call(context, callee, args, width, offset);
return rewrite_call(context, callee, args, self.span, width, offset);
}
ast::Expr_::ExprParen(ref subexpr) => {
return rewrite_paren(context, subexpr, width, offset);
@ -46,7 +44,7 @@ impl Rewrite for ast::Expr {
offset);
}
ast::Expr_::ExprTup(ref items) => {
return rewrite_tuple_lit(context, items, width, offset);
return rewrite_tuple_lit(context, items, self.span, width, offset);
}
_ => {}
}
@ -55,9 +53,12 @@ impl Rewrite for ast::Expr {
}
}
fn rewrite_string_lit(context: &RewriteContext, s: &str, span: Span, width: usize, offset: usize) -> Option<String> {
// FIXME I bet this stomps unicode escapes in the source string
fn rewrite_string_lit(context: &RewriteContext,
s: &str,
span: Span,
width: usize,
offset: usize)
-> Option<String> {
// Check if there is anything to fix: we always try to fixup multi-line
// strings, or if the string is too long for the line.
let l_loc = context.codemap.lookup_char_pos(span.lo);
@ -65,102 +66,63 @@ fn rewrite_string_lit(context: &RewriteContext, s: &str, span: Span, width: usiz
if l_loc.line == r_loc.line && r_loc.col.to_usize() <= context.config.max_width {
return context.codemap.span_to_snippet(span).ok();
}
let fmt = StringFormat {
opener: "\"",
closer: "\"",
line_start: " ",
line_end: "\\",
width: width,
offset: offset,
trim_end: false
};
// TODO if lo.col > IDEAL - 10, start a new line (need cur indent for that)
let s = s.escape_default();
let offset = offset + 1;
let indent = make_indent(offset);
let indent = &indent;
let mut cur_start = 0;
let mut result = String::with_capacity(round_up_to_power_of_two(s.len()));
result.push('"');
loop {
let max_chars = if cur_start == 0 {
// First line.
width - 2 // 2 = " + \
} else {
context.config.max_width - offset - 1 // 1 = either \ or ;
};
let mut cur_end = cur_start + max_chars;
if cur_end >= s.len() {
result.push_str(&s[cur_start..]);
break;
}
// Make sure we're on a char boundary.
cur_end = next_char(&s, cur_end);
// Push cur_end left until we reach whitespace
while !s.char_at(cur_end-1).is_whitespace() {
cur_end = prev_char(&s, cur_end);
if cur_end - cur_start < MIN_STRING {
// We can't break at whitespace, fall back to splitting
// anywhere that doesn't break an escape sequence
cur_end = next_char(&s, cur_start + max_chars);
while s.char_at(prev_char(&s, cur_end)) == '\\' {
cur_end = prev_char(&s, cur_end);
}
break;
}
}
// Make sure there is no whitespace to the right of the break.
while cur_end < s.len() && s.char_at(cur_end).is_whitespace() {
cur_end = next_char(&s, cur_end+1);
}
result.push_str(&s[cur_start..cur_end]);
result.push_str("\\\n");
result.push_str(indent);
cur_start = cur_end;
}
result.push('"');
Some(result)
Some(rewrite_string(&s.escape_default(), &fmt))
}
fn rewrite_call(context: &RewriteContext,
callee: &ast::Expr,
args: &[ptr::P<ast::Expr>],
span: Span,
width: usize,
offset: usize)
-> Option<String>
{
-> Option<String> {
debug!("rewrite_call, width: {}, offset: {}", width, offset);
// TODO using byte lens instead of char lens (and probably all over the place too)
let callee_str = try_opt!(callee.rewrite(context, width, offset));
debug!("rewrite_call, callee_str: `{:?}`", callee_str);
debug!("rewrite_call, callee_str: `{}`", callee_str);
if args.len() == 0 {
return Some(format!("{}()", callee_str));
}
// 2 is for parens.
let remaining_width = width - callee_str.len() - 2;
let offset = callee_str.len() + 1 + offset;
let arg_count = args.len();
let args_str = if arg_count > 0 {
let args_rewritten: Vec<_> =
try_opt!(args.iter()
.map(|arg| arg.rewrite(context, remaining_width, offset)
.map(|arg_str| (arg_str, String::new())))
.collect());
let fmt = ListFormatting {
tactic: ListTactic::HorizontalVertical,
separator: ",",
trailing_separator: SeparatorTactic::Never,
indent: offset,
h_width: remaining_width,
v_width: remaining_width,
};
write_list(&args_rewritten, &fmt)
} else {
String::new()
let items = itemize_list(context.codemap,
Vec::new(),
args.iter(),
",",
")",
|item| item.span.lo,
|item| item.span.hi,
|item| item.rewrite(context, remaining_width, offset)
.unwrap(), // FIXME: don't unwrap, take span literal
callee.span.hi + BytePos(1),
span.hi);
let fmt = ListFormatting {
tactic: ListTactic::HorizontalVertical,
separator: ",",
trailing_separator: SeparatorTactic::Never,
indent: offset,
h_width: remaining_width,
v_width: remaining_width,
is_expression: true,
};
Some(format!("{}({})", callee_str, args_str))
Some(format!("{}({})", callee_str, write_list(&items, &fmt)))
}
fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, width: usize, offset: usize) -> Option<String> {
@ -198,8 +160,9 @@ fn rewrite_struct_lit(context: &RewriteContext,
indent + 2)
.map(|s| format!("..{}", s))))
.collect());
// FIXME comments
let field_strs: Vec<_> = field_strs.into_iter().map(|s| (s, String::new())).collect();
let field_strs: Vec<_> = field_strs.into_iter().map(ListItem::from_str).collect();
let fmt = ListFormatting {
tactic: ListTactic::HorizontalVertical,
separator: ",",
@ -211,14 +174,15 @@ fn rewrite_struct_lit(context: &RewriteContext,
indent: indent,
h_width: budget,
v_width: budget,
is_expression: true,
};
let fields_str = write_list(&field_strs, &fmt);
Some(format!("{} {{ {} }}", path_str, fields_str))
// FIXME if the usual multi-line layout is too wide, we should fall back to
// Foo {
// a: ...,
// }
// FIXME if the usual multi-line layout is too wide, we should fall back to
// Foo {
// a: ...,
// }
}
fn rewrite_field(context: &RewriteContext, field: &ast::Field, width: usize, offset: usize) -> Option<String> {
@ -230,43 +194,42 @@ fn rewrite_field(context: &RewriteContext, field: &ast::Field, width: usize, off
fn rewrite_tuple_lit(context: &RewriteContext,
items: &[ptr::P<ast::Expr>],
span: Span,
width: usize,
offset: usize)
-> Option<String> {
// opening paren
let indent = offset + 1;
// In case of length 1, need a trailing comma
if items.len() == 1 {
return items[0].rewrite(context, width - 3, indent).map(|s| format!("({},)", s));
}
// Only last line has width-1 as budget, other may take max_width
let item_strs: Vec<_> =
try_opt!(items.iter()
.enumerate()
.map(|(i, item)| {
let rem_width = if i == items.len() - 1 {
width - 2
} else {
context.config.max_width - indent - 2
};
item.rewrite(context, rem_width, indent)
})
.collect());
let tactics = if item_strs.iter().any(|s| s.contains('\n')) {
ListTactic::Vertical
} else {
ListTactic::HorizontalVertical
};
// FIXME handle comments
let item_strs: Vec<_> = item_strs.into_iter().map(|s| (s, String::new())).collect();
let fmt = ListFormatting {
tactic: tactics,
separator: ",",
trailing_separator: SeparatorTactic::Never,
indent: indent,
h_width: width - 2,
v_width: width - 2,
};
let item_str = write_list(&item_strs, &fmt);
Some(format!("({})", item_str))
}
let indent = offset + 1;
let items = itemize_list(context.codemap,
Vec::new(),
items.into_iter(),
",",
")",
|item| item.span.lo,
|item| item.span.hi,
|item| item.rewrite(context,
context.config.max_width - indent - 2,
indent)
.unwrap(), // FIXME: don't unwrap, take span literal
span.lo + BytePos(1), // Remove parens
span.hi - BytePos(1));
// In case of length 1, need a trailing comma
let trailing_separator_tactic = if items.len() == 1 {
SeparatorTactic::Always
} else {
SeparatorTactic::Never
};
let fmt = ListFormatting {
tactic: ListTactic::HorizontalVertical,
separator: ",",
trailing_separator: trailing_separator_tactic,
indent: indent,
h_width: width - 2,
v_width: width - 2,
is_expression: true,
};
Some(format!("({})", write_list(&items, &fmt)))
}