1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Formatting of chained expressions, i.e. expressions which are chained by
12 //! dots: struct and enum field access, method calls, and try shorthand (?).
14 //! Instead of walking these subexpressions one-by-one, as is our usual strategy
15 //! for expression formatting, we collect maximal sequences of these expressions
16 //! and handle them simultaneously.
18 //! Whenever possible, the entire chain is put on a single line. If that fails,
19 //! we put each subexpression on a separate, much like the (default) function
20 //! argument function argument strategy.
22 //! Depends on config options: `chain_indent` is the indent to use for
23 //! blocks in the parent/root/base of the chain (and the rest of the chain's
25 //! E.g., `let foo = { aaaa; bbb; ccc }.bar.baz();`, we would layout for the
26 //! following values of `chain_indent`:
50 //! If the first item in the chain is a block expression, we align the dots with
68 use config::IndentStyle;
69 use expr::rewrite_call;
70 use macros::convert_try_mac;
71 use rewrite::{Rewrite, RewriteContext};
74 use utils::{first_line_width, last_line_extendable, last_line_width, mk_sp, wrap_str};
80 use syntax::codemap::Span;
81 use syntax::{ast, ptr};
83 pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -> Option<String> {
84 let chain = Chain::from_ast(expr, context);
85 debug!("rewrite_chain {:?} {:?}", chain, shape);
87 // If this is just an expression with some `?`s, then format it trivially and
89 if chain.children.is_empty() {
90 return chain.parent.rewrite(context, shape);
93 chain.rewrite(context, shape)
96 // An expression plus trailing `?`s to be formatted together.
99 // FIXME: we can't use a reference here because to convert `try!` to `?` we
100 // synthesise the AST node. However, I think we could use `Cow` and that
101 // would remove a lot of cloning.
106 impl Rewrite for ChainItem {
107 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
108 let rewrite = self.expr.rewrite(context, shape.sub_width(self.tries)?)?;
109 Some(format!("{}{}", rewrite, "?".repeat(self.tries)))
114 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
115 // `.c` and any trailing `?`s.
118 context: &RewriteContext,
120 ) -> Option<String> {
121 let shape = shape.sub_width(self.tries)?;
122 let mut rewrite = match self.expr.node {
123 ast::ExprKind::MethodCall(ref segment, ref expressions) => {
124 let types = match segment.args {
125 Some(ref params) => match **params {
126 ast::GenericArgs::AngleBracketed(ref data) => &data.args[..],
131 Self::rewrite_method_call(segment.ident, types, expressions, self.expr.span, context, shape)?
133 ast::ExprKind::Field(ref nested, ref field) => {
134 let space = if Self::is_tup_field_access(&self.expr) && Self::is_tup_field_access(nested) {
139 let result = format!("{}.{}", space, field.name);
140 if result.len() <= shape.width {
148 rewrite.push_str(&"?".repeat(self.tries));
152 fn is_tup_field_access(expr: &ast::Expr) -> bool {
154 ast::ExprKind::Field(_, ref field) => {
155 field.name.to_string().chars().all(|c| c.is_digit(10))
161 fn rewrite_method_call(
162 method_name: ast::Ident,
163 types: &[ast::GenericArg],
164 args: &[ptr::P<ast::Expr>],
166 context: &RewriteContext,
168 ) -> Option<String> {
169 let (lo, type_str) = if types.is_empty() {
170 (args[0].span.hi(), String::new())
172 let type_list = types
174 .map(|ty| ty.rewrite(context, shape))
175 .collect::<Option<Vec<_>>>()?;
177 let type_str = format!("::<{}>", type_list.join(", "));
179 (types.last().unwrap().span().hi(), type_str)
182 let callee_str = format!(".{}{}", method_name, type_str);
183 let span = mk_sp(lo, span.hi());
185 rewrite_call(context, &callee_str, &args[1..], span, shape)
192 children: Vec<ChainItem>,
196 fn from_ast(expr: &ast::Expr, context: &RewriteContext) -> Chain {
197 let subexpr_list = Self::make_subexpr_list(expr, context);
199 // Un-parse the expression tree into ChainItems
200 let mut children = vec![];
201 let mut sub_tries = 0;
202 for subexpr in subexpr_list {
204 ast::ExprKind::Try(_) => sub_tries += 1,
206 children.push(ChainItem {
216 parent: children.pop().unwrap(),
221 // Returns a Vec of the prefixes of the chain.
222 // E.g., for input `a.b.c` we return [`a.b.c`, `a.b`, 'a']
223 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> Vec<ast::Expr> {
224 let mut subexpr_list = vec![expr.clone()];
226 while let Some(subexpr) = Self::pop_expr_chain(subexpr_list.last().unwrap(), context) {
227 subexpr_list.push(subexpr.clone());
233 // Returns the expression's subexpression, if it exists. When the subexpr
234 // is a try! macro, we'll convert it to shorthand when the option is set.
235 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
237 ast::ExprKind::MethodCall(_, ref expressions) => {
238 Some(Self::convert_try(&expressions[0], context))
240 ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) => {
241 Some(Self::convert_try(subexpr, context))
247 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
249 ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
250 if let Some(subexpr) = convert_try_mac(mac, context) {
261 impl Rewrite for Chain {
262 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
263 debug!("rewrite chain {:?} {:?}", self, shape);
265 let mut formatter = match context.config.indent_style() {
266 IndentStyle::Block => Box::new(ChainFormatterBlock::new(self)) as Box<ChainFormatter>,
267 IndentStyle::Visual => Box::new(ChainFormatterVisual::new(self)) as Box<ChainFormatter>,
270 formatter.format_root(&self.parent, context, shape)?;
271 if let result @ Some(_) = formatter.pure_root() {
275 // Decide how to layout the rest of the chain.
276 let child_shape = formatter.child_shape(context, shape);
278 formatter.format_children(context, child_shape)?;
279 formatter.format_last_child(context, shape, child_shape)?;
281 let result = formatter.join_rewrites(context, child_shape)?;
282 wrap_str(result, context.config.max_width(), shape)
286 // There are a few types for formatting chains. This is because there is a lot
287 // in common between formatting with block vs visual indent, but they are
288 // different enough that branching on the indent all over the place gets ugly.
289 // Anything that can format a chain is a ChainFormatter.
290 trait ChainFormatter {
291 // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
292 // Root is the parent plus any other chain items placed on the first line to
293 // avoid an orphan. E.g.,
298 // If `bar` were not part of the root, then baz would be orphaned and 'float'.
299 fn format_root(&mut self, parent: &ChainItem, context: &RewriteContext, shape: Shape) -> Option<()>;
300 fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Shape;
301 fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()>;
302 fn format_last_child(&mut self, context: &RewriteContext, shape: Shape, child_shape: Shape) -> Option<()>;
303 fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String>;
304 // Returns `Some` if the chain is only a root, None otherwise.
305 fn pure_root(&mut self) -> Option<String>;
308 // Data and behaviour that is shared by both chain formatters. The concrete
309 // formatters can delegate much behaviour to `ChainFormatterShared`.
310 struct ChainFormatterShared<'a> {
311 // The current working set of child items.
312 children: &'a[ChainItem],
313 // The current rewrites of items (includes trailing `?`s, but not any way to
314 // connect the rewrites together).
315 rewrites: Vec<String>,
316 // Whether the chain can fit on one line.
317 fits_single_line: bool,
318 // The number of children in the chain. This is not equal to `self.children.len()`
319 // because `self.children` will change size as we process the chain.
323 impl <'a> ChainFormatterShared<'a> {
324 fn new(chain: &'a Chain) -> ChainFormatterShared<'a> {
325 ChainFormatterShared {
326 children: &chain.children,
327 rewrites: Vec::with_capacity(chain.children.len() + 1),
328 fits_single_line: false,
329 child_count: chain.children.len(),
333 fn pure_root(&mut self) -> Option<String> {
334 if self.children.is_empty() {
335 assert_eq!(self.rewrites.len(), 1);
336 Some(self.rewrites.pop().unwrap())
342 // Rewrite the last child. The last child of a chain requires special treatment. We need to
343 // know whether 'overflowing' the last child make a better formatting:
345 // A chain with overflowing the last child:
347 // parent.child1.child2.last_child(
354 // A chain without overflowing the last child (in vertical layout):
359 // .last_child(a, b, c)
362 // In particular, overflowing is effective when the last child is a method with a multi-lined
363 // block-like argument (e.g. closure):
365 // parent.child1.child2.last_child(|a, b, c| {
366 // let x = foo(a, b, c);
367 // let y = bar(a, b, c);
374 fn format_last_child(&mut self, may_extend: bool, context: &RewriteContext, shape: Shape, child_shape: Shape) -> Option<()> {
375 let last = &self.children[0];
376 let extendable = may_extend && last_line_extendable(&self.rewrites[self.rewrites.len() - 1]);
378 // Total of all items excluding the last.
379 let almost_total = if extendable {
380 last_line_width(&self.rewrites[self.rewrites.len() - 1])
382 self.rewrites.iter().fold(0, |a, b| a + b.len())
384 let one_line_budget = if self.child_count == 1 {
387 min(shape.width, context.config.width_heuristics().chain_width)
388 }.saturating_sub(almost_total);
390 let all_in_one_line = self.rewrites.iter().all(|s| !s.contains('\n')) && one_line_budget > 0;
391 let last_shape = if all_in_one_line {
392 shape.sub_width(last.tries)?
394 child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?
397 let mut last_subexpr_str = None;
398 if all_in_one_line || extendable {
399 // First we try to 'overflow' the last child and see if it looks better than using
401 if let Some(shape) = last_shape.offset_left(almost_total) {
402 if let Some(rw) = last.rewrite_postfix(context, shape) {
403 // We allow overflowing here only if both of the following conditions match:
404 // 1. The entire chain fits in a single line except the last child.
405 // 2. `last_child_str.lines().count() >= 5`.
406 let line_count = rw.lines().count();
407 let could_fit_single_line = first_line_width(&rw) <= one_line_budget;
408 if could_fit_single_line && line_count >= 5 {
409 last_subexpr_str = Some(rw);
410 self.fits_single_line = all_in_one_line;
412 // We could not know whether overflowing is better than using vertical
413 // layout, just by looking at the overflowed rewrite. Now we rewrite the
414 // last child on its own line, and compare two rewrites to choose which is
416 match last.rewrite_postfix(context, last_shape) {
417 Some(ref new_rw) if !could_fit_single_line => {
418 last_subexpr_str = Some(new_rw.clone());
420 Some(ref new_rw) if new_rw.lines().count() >= line_count => {
421 last_subexpr_str = Some(rw);
422 self.fits_single_line = could_fit_single_line && all_in_one_line;
424 new_rw @ Some(..) => {
425 last_subexpr_str = new_rw;
428 last_subexpr_str = Some(rw);
429 self.fits_single_line = could_fit_single_line && all_in_one_line;
437 last_subexpr_str = last_subexpr_str.or_else(|| last.rewrite_postfix(context, last_shape));
438 self.rewrites.push(last_subexpr_str?);
442 fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape, block_like_iter: impl Iterator<Item=bool>) -> Option<String> {
443 let connector = if self.fits_single_line {
444 // Yay, we can put everything on one line.
448 if *context.force_one_line_chain.borrow() {
451 child_shape.indent.to_string_with_newline(context.config)
454 let mut rewrite_iter = self.rewrites.iter();
455 let mut result = rewrite_iter.next().unwrap().clone();
457 for (rewrite, prev_is_block_like) in rewrite_iter.zip(block_like_iter) {
458 if !prev_is_block_like {
459 result.push_str(&connector);
461 result.push_str(&rewrite);
468 // Formats a chain using block indent.
469 struct ChainFormatterBlock<'a> {
470 shared: ChainFormatterShared<'a>,
471 // For each rewrite, whether the corresponding item is block-like.
472 is_block_like: Vec<bool>,
475 impl <'a> ChainFormatterBlock<'a> {
476 fn new(chain: &'a Chain) -> ChainFormatterBlock<'a> {
477 ChainFormatterBlock {
478 shared: ChainFormatterShared::new(chain),
479 is_block_like: Vec::with_capacity(chain.children.len() + 1),
484 impl <'a> ChainFormatter for ChainFormatterBlock<'a> {
485 fn format_root(&mut self, parent: &ChainItem, context: &RewriteContext, shape: Shape) -> Option<()> {
486 let mut root_rewrite: String = parent.rewrite(context, shape)?;
488 let mut root_ends_with_block = is_block_expr(context, &parent.expr, &root_rewrite);
489 let tab_width = context.config.tab_spaces().saturating_sub(shape.offset);
491 while root_rewrite.len() <= tab_width && !root_rewrite.contains('\n') {
492 let item = &self.shared.children[self.shared.children.len() - 1];
493 let shape = shape.offset_left(root_rewrite.len())?;
494 match &item.rewrite_postfix(context, shape) {
495 Some(rewrite) => root_rewrite.push_str(rewrite),
499 root_ends_with_block = is_block_expr(context, &item.expr, &root_rewrite);
501 self.shared.children = &self.shared.children[..self.shared.children.len() - 1];
502 if self.shared.children.is_empty() {
506 self.is_block_like.push(root_ends_with_block);
507 self.shared.rewrites.push(root_rewrite);
511 fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Shape {
512 if self.is_block_like[0] {
515 shape.block_indent(context.config.tab_spaces())
516 }.with_max_width(context.config)
519 fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
520 for item in self.shared.children[1..].iter().rev() {
521 let rewrite = item.rewrite_postfix(context, child_shape)?;
522 self.is_block_like.push(is_block_expr(context, &item.expr, &rewrite));
523 self.shared.rewrites.push(rewrite);
528 fn format_last_child(&mut self, context: &RewriteContext, shape: Shape, child_shape: Shape) -> Option<()> {
529 self.shared.format_last_child(true, context, shape, child_shape)
532 fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
533 self.shared.join_rewrites(context, child_shape, self.is_block_like.iter().cloned())
536 fn pure_root(&mut self) -> Option<String> {
537 self.shared.pure_root()
541 // Format a chain using visual indent.
542 struct ChainFormatterVisual<'a> {
543 shared: ChainFormatterShared<'a>,
546 impl<'a> ChainFormatterVisual<'a> {
547 fn new(chain: &'a Chain) -> ChainFormatterVisual<'a> {
548 ChainFormatterVisual {
549 shared: ChainFormatterShared::new(chain),
554 impl <'a> ChainFormatter for ChainFormatterVisual<'a> {
555 fn format_root(&mut self, parent: &ChainItem, context: &RewriteContext, shape: Shape) -> Option<()> {
556 // Determines if we can continue formatting a given expression on the same line.
557 fn is_continuable(expr: &ast::Expr) -> bool {
559 ast::ExprKind::Path(..) => true,
564 // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
565 let parent_shape = if is_block_expr(context, &parent.expr, "\n") {
566 shape.visual_indent(0)
570 let mut root_rewrite = parent.rewrite(context, parent_shape)?;
572 if !root_rewrite.contains('\n') && is_continuable(&parent.expr) {
573 let item = &self.shared.children[self.shared.children.len() - 1];
574 let overhead = last_line_width(&root_rewrite);
575 let shape = parent_shape.offset_left(overhead)?;
576 let rewrite = item.rewrite_postfix(context, shape)?;
577 root_rewrite.push_str(&rewrite);
579 self.shared.children = &self.shared.children[..self.shared.children.len() - 1];
582 self.shared.rewrites.push(root_rewrite);
586 fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Shape {
587 shape.visual_indent(0).with_max_width(context.config)
590 fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
591 for item in self.shared.children[1..].iter().rev() {
592 let rewrite = item.rewrite_postfix(context, child_shape)?;
593 self.shared.rewrites.push(rewrite);
598 fn format_last_child(&mut self, context: &RewriteContext, shape: Shape, child_shape: Shape) -> Option<()> {
599 self.shared.format_last_child(false, context, shape, child_shape)
602 fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
603 self.shared.join_rewrites(context, child_shape, iter::repeat(false))
606 fn pure_root(&mut self) -> Option<String> {
607 self.shared.pure_root()
611 // States whether an expression's last line exclusively consists of closing
612 // parens, braces, and brackets in its idiomatic formatting.
613 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
615 ast::ExprKind::Mac(..)
616 | ast::ExprKind::Call(..)
617 | ast::ExprKind::MethodCall(..) => {
618 context.use_block_indent() && repr.contains('\n')
620 ast::ExprKind::Struct(..)
621 | ast::ExprKind::While(..)
622 | ast::ExprKind::WhileLet(..)
623 | ast::ExprKind::If(..)
624 | ast::ExprKind::IfLet(..)
625 | ast::ExprKind::Block(..)
626 | ast::ExprKind::Loop(..)
627 | ast::ExprKind::ForLoop(..)
628 | ast::ExprKind::Match(..) => repr.contains('\n'),
629 ast::ExprKind::Paren(ref expr)
630 | ast::ExprKind::Binary(_, _, ref expr)
631 | ast::ExprKind::Index(_, ref expr)
632 | ast::ExprKind::Unary(_, ref expr)
633 | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
634 | ast::ExprKind::Try(ref expr)
635 | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),