chains: factor into objects

This commit is contained in:
Nick Cameron 2018-07-11 12:01:39 +12:00
parent 86314bf09f
commit a56ff9d02f

View file

@ -111,7 +111,7 @@ struct Chain {
impl Chain { impl Chain {
fn from_ast(expr: &ast::Expr, context: &RewriteContext) -> Chain { fn from_ast(expr: &ast::Expr, context: &RewriteContext) -> Chain {
let mut subexpr_list = make_subexpr_list(expr, context); let mut subexpr_list = Self::make_subexpr_list(expr, context);
// Un-parse the expression tree into ChainItems // Un-parse the expression tree into ChainItems
let mut children = vec![]; let mut children = vec![];
@ -139,10 +139,67 @@ impl Chain {
children, children,
} }
} }
// Returns a Vec of the prefixes of the chain.
// E.g., for input `a.b.c` we return [`a.b.c`, `a.b`, 'a']
fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> Vec<ast::Expr> {
let mut subexpr_list = vec![expr.clone()];
while let Some(subexpr) = Self::pop_expr_chain(subexpr_list.last().unwrap(), context) {
subexpr_list.push(subexpr.clone());
}
subexpr_list
}
// Returns the expression's subexpression, if it exists. When the subexpr
// is a try! macro, we'll convert it to shorthand when the option is set.
fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
match expr.node {
ast::ExprKind::MethodCall(_, ref expressions) => {
Some(Self::convert_try(&expressions[0], context))
}
ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) => {
Some(Self::convert_try(subexpr, context))
}
_ => None,
}
}
fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
match expr.node {
ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
if let Some(subexpr) = convert_try_mac(mac, context) {
subexpr
} else {
expr.clone()
}
}
_ => expr.clone(),
}
}
} }
fn rewrite_chain_block(chain: Chain, context: &RewriteContext, shape: Shape) -> Option<String> { // TODO comments
debug!("rewrite_chain_block {:?} {:?}", chain, shape); struct ChainFormatterBlock<'a> {
children: &'a[ChainItem],
rewrites: Vec<String>,
root_ends_with_block: bool,
is_block_like: Vec<bool>,
fits_single_line: bool,
}
impl <'a> ChainFormatterBlock<'a> {
fn new(chain: &'a Chain) -> ChainFormatterBlock<'a> {
ChainFormatterBlock {
children: &chain.children,
root_ends_with_block: false,
rewrites: Vec::with_capacity(chain.children.len() + 1),
is_block_like: Vec::with_capacity(chain.children.len() + 1),
fits_single_line: false,
}
}
// Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`. // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
// Root is the parent plus any other chain items placed on the first line to // Root is the parent plus any other chain items placed on the first line to
// avoid an orphan. E.g., // avoid an orphan. E.g.,
@ -151,73 +208,53 @@ fn rewrite_chain_block(chain: Chain, context: &RewriteContext, shape: Shape) ->
// .baz() // .baz()
// ``` // ```
// If `bar` were not part of the root, then baz would be orphaned and 'float'. // If `bar` were not part of the root, then baz would be orphaned and 'float'.
let mut root_rewrite = chain.parent.expr fn format_root(&mut self, parent: &ChainItem, context: &RewriteContext, shape: Shape) -> Option<()> {
.rewrite(context, shape) let mut root_rewrite: String = parent.expr
.map(|parent_rw| parent_rw + &"?".repeat(chain.parent.tries))?; .rewrite(context, shape)
.map(|parent_rw| parent_rw + &"?".repeat(parent.tries))?;
let mut children: &[_] = &chain.children; self.root_ends_with_block = is_block_expr(context, &parent.expr, &root_rewrite);
let mut root_ends_with_block = is_block_expr(context, &chain.parent.expr, &root_rewrite); let tab_width = context.config.tab_spaces().saturating_sub(shape.offset);
let tab_width = context.config.tab_spaces().saturating_sub(shape.offset);
while root_rewrite.len() <= tab_width && !root_rewrite.contains('\n') { while root_rewrite.len() <= tab_width && !root_rewrite.contains('\n') {
let item = &children[0]; let item = &self.children[0];
let shape = shape.offset_left(root_rewrite.len())?; let shape = shape.offset_left(root_rewrite.len())?;
match rewrite_chain_subexpr(&item.expr, context, shape) { match rewrite_chain_subexpr(&item.expr, context, shape) {
Some(rewrite) => { Some(rewrite) => {
root_rewrite.push_str(&rewrite); root_rewrite.push_str(&rewrite);
root_rewrite.push_str(&"?".repeat(item.tries)); root_rewrite.push_str(&"?".repeat(item.tries));
}
None => break,
} }
None => break,
}
root_ends_with_block = is_block_expr(context, &item.expr, &root_rewrite); self.root_ends_with_block = is_block_expr(context, &item.expr, &root_rewrite);
children = &children[1..]; self.children = &self.children[1..];
if children.is_empty() { if self.children.is_empty() {
return Some(root_rewrite); break;
}
} }
self.rewrites.push(root_rewrite);
Some(())
} }
// Separate out the last item in the chain for special treatment below. fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Shape {
let last = &children[children.len() - 1]; if self.root_ends_with_block {
children = &children[..children.len() - 1]; shape
} else {
// Decide how to layout the rest of the chain. shape.block_indent(context.config.tab_spaces())
let child_shape = if root_ends_with_block { }.with_max_width(context.config)
shape
} else {
shape.block_indent(context.config.tab_spaces())
}.with_max_width(context.config);
let mut rewrites: Vec<String> = Vec::with_capacity(children.len() + 2);
rewrites.push(root_rewrite);
let mut is_block_like = Vec::with_capacity(children.len() + 2);
is_block_like.push(root_ends_with_block);
for item in children {
let rewrite = rewrite_chain_subexpr(&item.expr, context, child_shape)?;
is_block_like.push(is_block_expr(context, &item.expr, &rewrite));
rewrites.push(format!("{}{}", rewrite, "?".repeat(item.tries)));
} }
// Total of all items excluding the last. fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
let extend_last_subexpr = last_line_extendable(&rewrites[rewrites.len() - 1]); self.is_block_like.push(self.root_ends_with_block);
let almost_total = if extend_last_subexpr { for item in &self.children[..self.children.len()] {
last_line_width(&rewrites[rewrites.len() - 1]) let rewrite = rewrite_chain_subexpr(&item.expr, context, child_shape)?;
} else { self.is_block_like.push(is_block_expr(context, &item.expr, &rewrite));
rewrites.iter().fold(0, |a, b| a + b.len()) self.rewrites.push(format!("{}{}", rewrite, "?".repeat(item.tries)));
} + last.tries; }
let one_line_budget = if rewrites.len() == 1 { Some(())
shape.width }
} else {
min(shape.width, context.config.width_heuristics().chain_width)
};
let all_in_one_line = rewrites.iter().all(|s| !s.contains('\n'))
&& almost_total < one_line_budget;
let last_shape = if all_in_one_line {
shape.sub_width(last.tries)?
} else {
child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?
};
// Rewrite the last child. The last child of a chain requires special treatment. We need to // Rewrite the last child. The last child of a chain requires special treatment. We need to
// know whether 'overflowing' the last child make a better formatting: // know whether 'overflowing' the last child make a better formatting:
@ -251,239 +288,279 @@ fn rewrite_chain_block(chain: Chain, context: &RewriteContext, shape: Shape) ->
// result // result
// }) // })
// ``` // ```
fn format_last_child(&mut self, context: &RewriteContext, shape: Shape, child_shape: Shape) -> Option<()> {
let last = &self.children[self.children.len() - 1];
let extendable = last_line_extendable(&self.rewrites[self.rewrites.len() - 1]);
// Total of all items excluding the last.
let almost_total = if extendable {
last_line_width(&self.rewrites[self.rewrites.len() - 1])
} else {
self.rewrites.iter().fold(0, |a, b| a + b.len())
} + last.tries;
let one_line_budget = if self.rewrites.len() == 1 {
shape.width
} else {
min(shape.width, context.config.width_heuristics().chain_width)
}.saturating_sub(almost_total);
let mut last_subexpr_str = None; let all_in_one_line = self.rewrites.iter().all(|s| !s.contains('\n')) && one_line_budget > 0;
let mut fits_single_line = false; let last_shape = if all_in_one_line {
if all_in_one_line || extend_last_subexpr { shape.sub_width(last.tries)?
// First we try to 'overflow' the last child and see if it looks better than using } else {
// vertical layout. child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?
if let Some(shape) = last_shape.offset_left(almost_total) { };
if let Some(rw) = rewrite_chain_subexpr(&last.expr, context, shape) {
// We allow overflowing here only if both of the following conditions match: let mut last_subexpr_str = None;
// 1. The entire chain fits in a single line except the last child. if all_in_one_line || extendable {
// 2. `last_child_str.lines().count() >= 5`. // First we try to 'overflow' the last child and see if it looks better than using
let line_count = rw.lines().count(); // vertical layout.
let could_fit_single_line = almost_total + first_line_width(&rw) <= one_line_budget; if let Some(shape) = last_shape.offset_left(almost_total) {
if fits_single_line && line_count >= 5 { if let Some(rw) = rewrite_chain_subexpr(&last.expr, context, shape) {
last_subexpr_str = Some(rw); // We allow overflowing here only if both of the following conditions match:
fits_single_line = true; // 1. The entire chain fits in a single line except the last child.
} else { // 2. `last_child_str.lines().count() >= 5`.
// We could not know whether overflowing is better than using vertical layout, let line_count = rw.lines().count();
// just by looking at the overflowed rewrite. Now we rewrite the last child let could_fit_single_line = first_line_width(&rw) <= one_line_budget;
// on its own line, and compare two rewrites to choose which is better. if could_fit_single_line && line_count >= 5 {
match rewrite_chain_subexpr(&last.expr, context, last_shape) { last_subexpr_str = Some(rw);
Some(ref new_rw) if !could_fit_single_line => { self.fits_single_line = all_in_one_line;
last_subexpr_str = Some(new_rw.clone()); } else {
} // We could not know whether overflowing is better than using vertical layout,
Some(ref new_rw) if new_rw.lines().count() >= line_count => { // just by looking at the overflowed rewrite. Now we rewrite the last child
last_subexpr_str = Some(rw); // on its own line, and compare two rewrites to choose which is better.
fits_single_line = could_fit_single_line; match rewrite_chain_subexpr(&last.expr, context, last_shape) {
} Some(ref new_rw) if !could_fit_single_line => {
new_rw @ Some(..) => { last_subexpr_str = Some(new_rw.clone());
last_subexpr_str = new_rw; }
} Some(ref new_rw) if new_rw.lines().count() >= line_count => {
_ => { last_subexpr_str = Some(rw);
last_subexpr_str = Some(rw); self.fits_single_line = could_fit_single_line && all_in_one_line;
fits_single_line = could_fit_single_line; }
new_rw @ Some(..) => {
last_subexpr_str = new_rw;
}
_ => {
last_subexpr_str = Some(rw);
self.fits_single_line = could_fit_single_line && all_in_one_line;
}
} }
} }
} }
} }
} }
last_subexpr_str = last_subexpr_str.or_else(|| rewrite_chain_subexpr(&last.expr, context, last_shape));
self.rewrites.push(format!("{}{}", last_subexpr_str?, "?".repeat(last.tries)));
Some(())
} }
last_subexpr_str = last_subexpr_str.or_else(|| rewrite_chain_subexpr(&last.expr, context, last_shape));
rewrites.push(format!("{}{}", last_subexpr_str?, "?".repeat(last.tries)));
// We should never look at this, since we only look at the block-ness of the fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
// previous item in the chain. let connector = if self.fits_single_line {
is_block_like.push(false); // Yay, we can put everything on one line.
Cow::from("")
} else {
// Use new lines.
if *context.force_one_line_chain.borrow() {
return None;
}
child_shape.indent.to_string_with_newline(context.config)
};
let connector = if fits_single_line && all_in_one_line { let mut rewrite_iter = self.rewrites.iter();
// Yay, we can put everything on one line. let mut result = rewrite_iter.next().unwrap().clone();
Cow::from("")
} else { for (rewrite, prev_is_block_like) in rewrite_iter.zip(self.is_block_like.iter()) {
// Use new lines. if rewrite != "?" && !prev_is_block_like {
if *context.force_one_line_chain.borrow() { result.push_str(&connector);
return None; }
result.push_str(&rewrite);
} }
child_shape.indent.to_string_with_newline(context.config)
};
let result = join_rewrites(&rewrites, &is_block_like, &connector); Some(result)
}
}
fn rewrite_chain_block(chain: Chain, context: &RewriteContext, shape: Shape) -> Option<String> {
debug!("rewrite_chain_block {:?} {:?}", chain, shape);
let mut formatter = ChainFormatterBlock::new(&chain);
formatter.format_root(&chain.parent, context, shape)?;
if formatter.children.is_empty() {
assert_eq!(formatter.rewrites.len(), 1);
return Some(formatter.rewrites.pop().unwrap());
}
// Decide how to layout the rest of the chain.
let child_shape = formatter.child_shape(context, shape);
formatter.format_children(context, child_shape)?;
formatter.format_last_child(context, shape, child_shape)?;
let result = formatter.join_rewrites(context, child_shape)?;
Some(result) Some(result)
} }
fn rewrite_chain_visual(chain: Chain, context: &RewriteContext, shape: Shape) -> Option<String> { struct ChainFormatterVisual<'a> {
// Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`. children: &'a[ChainItem],
let parent_shape = if is_block_expr(context, &chain.parent.expr, "\n") { rewrites: Vec<String>,
shape.visual_indent(0) fits_single_line: bool,
} else { }
shape
};
let mut children: &[_] = &chain.children;
let mut root_rewrite = chain.parent.expr
.rewrite(context, parent_shape)
.map(|parent_rw| parent_rw + &"?".repeat(chain.parent.tries))?;
if !root_rewrite.contains('\n') && is_continuable(&chain.parent.expr) { impl<'a> ChainFormatterVisual<'a> {
let item = &children[0]; fn new(chain: &'a Chain) -> ChainFormatterVisual<'a> {
let overhead = last_line_width(&root_rewrite); ChainFormatterVisual {
let shape = parent_shape.offset_left(overhead)?; children: &chain.children,
let rewrite = rewrite_chain_subexpr(&item.expr, context, shape)?; rewrites: Vec::with_capacity(chain.children.len() + 1),
root_rewrite.push_str(&rewrite); fits_single_line: false,
root_rewrite.push_str(&"?".repeat(item.tries));
children = &children[1..];
if children.is_empty() {
return Some(root_rewrite);
} }
} }
let last = &children[children.len() - 1]; fn format_root(&mut self, parent: &ChainItem, context: &RewriteContext, shape: Shape) -> Option<()> {
children = &children[..children.len() - 1]; // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
let parent_shape = if is_block_expr(context, &parent.expr, "\n") {
shape.visual_indent(0)
} else {
shape
};
let mut root_rewrite = parent.expr
.rewrite(context, parent_shape)
.map(|parent_rw| parent_rw + &"?".repeat(parent.tries))?;
let child_shape = shape.visual_indent(0).with_max_width(context.config); if !root_rewrite.contains('\n') && Self::is_continuable(&parent.expr) {
let item = &self.children[0];
let overhead = last_line_width(&root_rewrite);
let shape = parent_shape.offset_left(overhead)?;
let rewrite = rewrite_chain_subexpr(&item.expr, context, shape)?;
root_rewrite.push_str(&rewrite);
root_rewrite.push_str(&"?".repeat(item.tries));
let mut rewrites: Vec<String> = Vec::with_capacity(children.len() + 2); self.children = &self.children[1..];
rewrites.push(root_rewrite); }
for item in chain.children.iter() {
let rewrite = rewrite_chain_subexpr(&item.expr, context, child_shape)?; self.rewrites.push(root_rewrite);
rewrites.push(format!("{}{}", rewrite, "?".repeat(item.tries))); Some(())
} }
// Total of all items excluding the last. // Determines if we can continue formatting a given expression on the same line.
let almost_total = rewrites.iter().fold(0, |a, b| a + b.len()) + last.tries; fn is_continuable(expr: &ast::Expr) -> bool {
let one_line_budget = if rewrites.len() == 1 { match expr.node {
shape.width ast::ExprKind::Path(..) => true,
} else { _ => false,
min(shape.width, context.config.width_heuristics().chain_width) }
}; }
let all_in_one_line = rewrites.iter().all(|s| !s.contains('\n'))
&& almost_total < one_line_budget;
let last_shape = child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?;
// Rewrite the last child. The last child of a chain requires special treatment. We need to fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
// know whether 'overflowing' the last child make a better formatting: for item in &self.children[..self.children.len() - 1] {
// let rewrite = rewrite_chain_subexpr(&item.expr, context, child_shape)?;
// A chain with overflowing the last child: self.rewrites.push(format!("{}{}", rewrite, "?".repeat(item.tries)));
// ``` }
// parent.child1.child2.last_child( Some(())
// a, }
// b,
// c,
// )
// ```
//
// A chain without overflowing the last child (in vertical layout):
// ```
// parent
// .child1
// .child2
// .last_child(a, b, c)
// ```
//
// In particular, overflowing is effective when the last child is a method with a multi-lined
// block-like argument (e.g. closure):
// ```
// parent.child1.child2.last_child(|a, b, c| {
// let x = foo(a, b, c);
// let y = bar(a, b, c);
//
// // ...
//
// result
// })
// ```
let mut last_subexpr_str = None; fn format_last_child(&mut self, context: &RewriteContext, shape: Shape, child_shape: Shape) -> Option<()> {
let mut fits_single_line = false; let last = &self.children[self.children.len() - 1];
if all_in_one_line {
// First we try to 'overflow' the last child and see if it looks better than using // Total of all items excluding the last.
// vertical layout. let almost_total = self.rewrites.iter().fold(0, |a, b| a + b.len()) + last.tries;
if let Some(shape) = parent_shape.offset_left(almost_total) { let one_line_budget = if self.rewrites.len() == 1 {
if let Some(rw) = rewrite_chain_subexpr(&last.expr, context, shape) { shape.width
// We allow overflowing here only if both of the following conditions match: } else {
// 1. The entire chain fits in a single line except the last child. min(shape.width, context.config.width_heuristics().chain_width)
// 2. `last_child_str.lines().count() >= 5`. };
let line_count = rw.lines().count(); let all_in_one_line = self.rewrites.iter().all(|s| !s.contains('\n'))
let could_fit_single_line = almost_total + first_line_width(&rw) <= one_line_budget; && almost_total < one_line_budget;
if could_fit_single_line && line_count >= 5 { let last_shape = child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?;
last_subexpr_str = Some(rw);
fits_single_line = true;
} else { let mut last_subexpr_str = None;
// We could not know whether overflowing is better than using vertical layout, if all_in_one_line {
// just by looking at the overflowed rewrite. Now we rewrite the last child // First we try to 'overflow' the last child and see if it looks better than using
// on its own line, and compare two rewrites to choose which is better. // vertical layout.
match rewrite_chain_subexpr(&last.expr, context, last_shape) { if let Some(shape) = shape.offset_left(almost_total) {
Some(ref new_rw) if !could_fit_single_line => { if let Some(rw) = rewrite_chain_subexpr(&last.expr, context, shape) {
last_subexpr_str = Some(new_rw.clone()); // We allow overflowing here only if both of the following conditions match:
} // 1. The entire chain fits in a single line except the last child.
Some(ref new_rw) if new_rw.lines().count() >= line_count => { // 2. `last_child_str.lines().count() >= 5`.
last_subexpr_str = Some(rw); let line_count = rw.lines().count();
fits_single_line = could_fit_single_line; let could_fit_single_line = almost_total + first_line_width(&rw) <= one_line_budget;
} if could_fit_single_line && line_count >= 5 {
new_rw @ Some(..) => { last_subexpr_str = Some(rw);
last_subexpr_str = new_rw; self.fits_single_line = all_in_one_line;
} } else {
_ => { // We could not know whether overflowing is better than using vertical layout,
last_subexpr_str = Some(rw); // just by looking at the overflowed rewrite. Now we rewrite the last child
fits_single_line = could_fit_single_line; // on its own line, and compare two rewrites to choose which is better.
match rewrite_chain_subexpr(&last.expr, context, last_shape) {
Some(ref new_rw) if !could_fit_single_line => {
last_subexpr_str = Some(new_rw.clone());
}
Some(ref new_rw) if new_rw.lines().count() >= line_count => {
last_subexpr_str = Some(rw);
self.fits_single_line = could_fit_single_line && all_in_one_line;
}
new_rw @ Some(..) => {
last_subexpr_str = new_rw;
}
_ => {
last_subexpr_str = Some(rw);
self.fits_single_line = could_fit_single_line && all_in_one_line;
}
} }
} }
} }
} }
} }
let last_subexpr_str = last_subexpr_str.or_else(|| rewrite_chain_subexpr(&last.expr, context, last_shape));
self.rewrites.push(format!("{}{}", last_subexpr_str?, "?".repeat(last.tries)));
Some(())
} }
last_subexpr_str = last_subexpr_str.or_else(|| rewrite_chain_subexpr(&last.expr, context, last_shape)); fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
rewrites.push(last_subexpr_str?); let connector = if self.fits_single_line {
// Yay, we can put everything on one line.
Cow::from("")
} else {
// Use new lines.
if *context.force_one_line_chain.borrow() {
return None;
}
child_shape.indent.to_string_with_newline(context.config)
};
let connector = if fits_single_line && all_in_one_line { let mut rewrite_iter = self.rewrites.iter();
// Yay, we can put everything on one line. let mut result = rewrite_iter.next().unwrap().clone();
Cow::from("")
} else { for rewrite in rewrite_iter {
// Use new lines. result.push_str(&connector);
if *context.force_one_line_chain.borrow() { result.push_str(&rewrite);
return None;
} }
child_shape.indent.to_string_with_newline(context.config)
};
let result = format!("{}{}", Some(result)
join_rewrites_vis(&rewrites, &connector), }
"?".repeat(last.tries), }
);
fn rewrite_chain_visual(chain: Chain, context: &RewriteContext, shape: Shape) -> Option<String> {
let mut formatter = ChainFormatterVisual::new(&chain);
formatter.format_root(&chain.parent, context, shape)?;
if formatter.children.is_empty() {
assert_eq!(formatter.rewrites.len(), 1);
return Some(formatter.rewrites.pop().unwrap());
}
let child_shape = shape.visual_indent(0).with_max_width(context.config);
formatter.format_children(context, child_shape)?;
formatter.format_last_child(context, shape, child_shape)?;
let result = formatter.join_rewrites(context, child_shape)?;
wrap_str(result, context.config.max_width(), shape) wrap_str(result, context.config.max_width(), shape)
} }
fn join_rewrites(rewrites: &[String], is_block_like: &[bool], connector: &str) -> String {
let mut rewrite_iter = rewrites.iter();
let mut result = rewrite_iter.next().unwrap().clone();
for (rewrite, prev_is_block_like) in rewrite_iter.zip(is_block_like.iter()) {
if rewrite != "?" && !prev_is_block_like {
result.push_str(connector);
}
result.push_str(&rewrite);
}
result
}
fn join_rewrites_vis(rewrites: &[String], connector: &str) -> String {
let mut rewrite_iter = rewrites.iter();
let mut result = rewrite_iter.next().unwrap().clone();
for rewrite in rewrite_iter {
if rewrite != "?" {
result.push_str(connector);
}
result.push_str(&rewrite);
}
result
}
// States whether an expression's last line exclusively consists of closing // States whether an expression's last line exclusively consists of closing
// parens, braces, and brackets in its idiomatic formatting. // parens, braces, and brackets in its idiomatic formatting.
fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool { fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
@ -513,45 +590,6 @@ fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool
} }
} }
// Returns a Vec of the prefixes of the chain.
// E.g., for input `a.b.c` we return [`a.b.c`, `a.b`, 'a']
fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> Vec<ast::Expr> {
let mut subexpr_list = vec![expr.clone()];
while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
subexpr_list.push(subexpr.clone());
}
subexpr_list
}
// Returns the expression's subexpression, if it exists. When the subexpr
// is a try! macro, we'll convert it to shorthand when the option is set.
fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
match expr.node {
ast::ExprKind::MethodCall(_, ref expressions) => {
Some(convert_try(&expressions[0], context))
}
ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) => {
Some(convert_try(subexpr, context))
}
_ => None,
}
}
fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
match expr.node {
ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
if let Some(subexpr) = convert_try_mac(mac, context) {
subexpr
} else {
expr.clone()
}
}
_ => expr.clone(),
}
}
// Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
// `.c`. // `.c`.
fn rewrite_chain_subexpr( fn rewrite_chain_subexpr(
@ -600,14 +638,6 @@ fn is_tup_field_access(expr: &ast::Expr) -> bool {
} }
} }
// Determines if we can continue formatting a given expression on the same line.
fn is_continuable(expr: &ast::Expr) -> bool {
match expr.node {
ast::ExprKind::Path(..) => true,
_ => false,
}
}
fn rewrite_method_call( fn rewrite_method_call(
method_name: ast::Ident, method_name: ast::Ident,
types: &[ast::GenericArg], types: &[ast::GenericArg],