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};
75 first_line_width, last_line_extendable, last_line_width, mk_sp, trimmed_last_line_width,
83 use syntax::codemap::Span;
84 use syntax::{ast, ptr};
86 pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -> Option<String> {
87 let chain = Chain::from_ast(expr, context);
88 debug!("rewrite_chain {:?} {:?}", chain, shape);
90 // If this is just an expression with some `?`s, then format it trivially and
92 if chain.children.is_empty() {
93 return chain.parent.rewrite(context, shape);
96 chain.rewrite(context, shape)
99 // An expression plus trailing `?`s to be formatted together.
102 // FIXME: we can't use a reference here because to convert `try!` to `?` we
103 // synthesise the AST node. However, I think we could use `Cow` and that
104 // would remove a lot of cloning.
109 impl Rewrite for ChainItem {
110 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
111 let rewrite = self.expr.rewrite(context, shape.sub_width(self.tries)?)?;
112 Some(format!("{}{}", rewrite, "?".repeat(self.tries)))
117 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
118 // `.c` and any trailing `?`s.
119 fn rewrite_postfix(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
120 let shape = shape.sub_width(self.tries)?;
121 let mut rewrite = match self.expr.node {
122 ast::ExprKind::MethodCall(ref segment, ref expressions) => {
123 let types = match segment.args {
124 Some(ref params) => match **params {
125 ast::GenericArgs::AngleBracketed(ref data) => &data.args[..],
130 Self::rewrite_method_call(
139 ast::ExprKind::Field(ref nested, ref field) => {
141 if Self::is_tup_field_access(&self.expr) && Self::is_tup_field_access(nested) {
146 let result = format!("{}.{}", space, field.name);
147 if result.len() <= shape.width {
155 rewrite.push_str(&"?".repeat(self.tries));
159 fn is_tup_field_access(expr: &ast::Expr) -> bool {
161 ast::ExprKind::Field(_, ref field) => {
162 field.name.to_string().chars().all(|c| c.is_digit(10))
168 fn rewrite_method_call(
169 method_name: ast::Ident,
170 types: &[ast::GenericArg],
171 args: &[ptr::P<ast::Expr>],
173 context: &RewriteContext,
175 ) -> Option<String> {
176 let (lo, type_str) = if types.is_empty() {
177 (args[0].span.hi(), String::new())
179 let type_list = types
181 .map(|ty| ty.rewrite(context, shape))
182 .collect::<Option<Vec<_>>>()?;
184 let type_str = format!("::<{}>", type_list.join(", "));
186 (types.last().unwrap().span().hi(), type_str)
189 let callee_str = format!(".{}{}", method_name, type_str);
190 let span = mk_sp(lo, span.hi());
192 rewrite_call(context, &callee_str, &args[1..], span, shape)
199 children: Vec<ChainItem>,
203 fn from_ast(expr: &ast::Expr, context: &RewriteContext) -> Chain {
204 let subexpr_list = Self::make_subexpr_list(expr, context);
206 // Un-parse the expression tree into ChainItems
207 let mut children = vec![];
208 let mut sub_tries = 0;
209 for subexpr in subexpr_list {
211 ast::ExprKind::Try(_) => sub_tries += 1,
213 children.push(ChainItem {
223 parent: children.pop().unwrap(),
228 // Returns a Vec of the prefixes of the chain.
229 // E.g., for input `a.b.c` we return [`a.b.c`, `a.b`, 'a']
230 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> Vec<ast::Expr> {
231 let mut subexpr_list = vec![expr.clone()];
233 while let Some(subexpr) = Self::pop_expr_chain(subexpr_list.last().unwrap(), context) {
234 subexpr_list.push(subexpr.clone());
240 // Returns the expression's subexpression, if it exists. When the subexpr
241 // is a try! macro, we'll convert it to shorthand when the option is set.
242 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
244 ast::ExprKind::MethodCall(_, ref expressions) => {
245 Some(Self::convert_try(&expressions[0], context))
247 ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) => {
248 Some(Self::convert_try(subexpr, context))
254 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
256 ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
257 if let Some(subexpr) = convert_try_mac(mac, context) {
268 impl Rewrite for Chain {
269 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
270 debug!("rewrite chain {:?} {:?}", self, shape);
272 let mut formatter = match context.config.indent_style() {
273 IndentStyle::Block => Box::new(ChainFormatterBlock::new(self)) as Box<ChainFormatter>,
274 IndentStyle::Visual => Box::new(ChainFormatterVisual::new(self)) as Box<ChainFormatter>,
277 formatter.format_root(&self.parent, context, shape)?;
278 if let Some(result) = formatter.pure_root() {
279 return wrap_str(result, context.config.max_width(), shape);
282 // Decide how to layout the rest of the chain.
283 let child_shape = formatter.child_shape(context, shape)?;
285 formatter.format_children(context, child_shape)?;
286 formatter.format_last_child(context, shape, child_shape)?;
288 let result = formatter.join_rewrites(context, child_shape)?;
289 wrap_str(result, context.config.max_width(), shape)
293 // There are a few types for formatting chains. This is because there is a lot
294 // in common between formatting with block vs visual indent, but they are
295 // different enough that branching on the indent all over the place gets ugly.
296 // Anything that can format a chain is a ChainFormatter.
297 trait ChainFormatter {
298 // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
299 // Root is the parent plus any other chain items placed on the first line to
300 // avoid an orphan. E.g.,
305 // If `bar` were not part of the root, then foo would be orphaned and 'float'.
309 context: &RewriteContext,
312 fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape>;
313 fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()>;
314 fn format_last_child(
316 context: &RewriteContext,
320 fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String>;
321 // Returns `Some` if the chain is only a root, None otherwise.
322 fn pure_root(&mut self) -> Option<String>;
325 // Data and behaviour that is shared by both chain formatters. The concrete
326 // formatters can delegate much behaviour to `ChainFormatterShared`.
327 struct ChainFormatterShared<'a> {
328 // The current working set of child items.
329 children: &'a [ChainItem],
330 // The current rewrites of items (includes trailing `?`s, but not any way to
331 // connect the rewrites together).
332 rewrites: Vec<String>,
333 // Whether the chain can fit on one line.
334 fits_single_line: bool,
335 // The number of children in the chain. This is not equal to `self.children.len()`
336 // because `self.children` will change size as we process the chain.
340 impl<'a> ChainFormatterShared<'a> {
341 fn new(chain: &'a Chain) -> ChainFormatterShared<'a> {
342 ChainFormatterShared {
343 children: &chain.children,
344 rewrites: Vec::with_capacity(chain.children.len() + 1),
345 fits_single_line: false,
346 child_count: chain.children.len(),
350 fn pure_root(&mut self) -> Option<String> {
351 if self.children.is_empty() {
352 assert_eq!(self.rewrites.len(), 1);
353 Some(self.rewrites.pop().unwrap())
359 // Rewrite the last child. The last child of a chain requires special treatment. We need to
360 // know whether 'overflowing' the last child make a better formatting:
362 // A chain with overflowing the last child:
364 // parent.child1.child2.last_child(
371 // A chain without overflowing the last child (in vertical layout):
376 // .last_child(a, b, c)
379 // In particular, overflowing is effective when the last child is a method with a multi-lined
380 // block-like argument (e.g. closure):
382 // parent.child1.child2.last_child(|a, b, c| {
383 // let x = foo(a, b, c);
384 // let y = bar(a, b, c);
391 fn format_last_child(
394 context: &RewriteContext,
398 let last = &self.children[0];
400 may_extend && last_line_extendable(&self.rewrites[self.rewrites.len() - 1]);
401 let prev_last_line_width = last_line_width(&self.rewrites[self.rewrites.len() - 1]);
403 // Total of all items excluding the last.
404 let almost_total = if extendable {
407 self.rewrites.iter().fold(0, |a, b| a + b.len())
409 let one_line_budget = if self.child_count == 1 {
412 min(shape.width, context.config.width_heuristics().chain_width)
413 }.saturating_sub(almost_total);
415 let all_in_one_line =
416 self.rewrites.iter().all(|s| !s.contains('\n')) && one_line_budget > 0;
417 let last_shape = if all_in_one_line {
418 shape.sub_width(last.tries)?
419 } else if extendable {
420 child_shape.sub_width(last.tries)?
422 child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?
425 let mut last_subexpr_str = None;
426 if all_in_one_line || extendable {
427 // First we try to 'overflow' the last child and see if it looks better than using
429 if let Some(one_line_shape) = last_shape.offset_left(almost_total) {
430 if let Some(rw) = last.rewrite_postfix(context, one_line_shape) {
431 // We allow overflowing here only if both of the following conditions match:
432 // 1. The entire chain fits in a single line except the last child.
433 // 2. `last_child_str.lines().count() >= 5`.
434 let line_count = rw.lines().count();
435 let could_fit_single_line = first_line_width(&rw) <= one_line_budget;
436 if could_fit_single_line && line_count >= 5 {
437 last_subexpr_str = Some(rw);
438 self.fits_single_line = all_in_one_line;
440 // We could not know whether overflowing is better than using vertical
441 // layout, just by looking at the overflowed rewrite. Now we rewrite the
442 // last child on its own line, and compare two rewrites to choose which is
444 let last_shape = child_shape
445 .sub_width(shape.rhs_overhead(context.config) + last.tries)?;
446 match last.rewrite_postfix(context, last_shape) {
447 Some(ref new_rw) if !could_fit_single_line => {
448 last_subexpr_str = Some(new_rw.clone());
450 Some(ref new_rw) if new_rw.lines().count() >= line_count => {
451 last_subexpr_str = Some(rw);
452 self.fits_single_line = could_fit_single_line && all_in_one_line;
454 new_rw @ Some(..) => {
455 last_subexpr_str = new_rw;
458 last_subexpr_str = Some(rw);
459 self.fits_single_line = could_fit_single_line && all_in_one_line;
467 last_subexpr_str = last_subexpr_str.or_else(|| last.rewrite_postfix(context, last_shape));
468 self.rewrites.push(last_subexpr_str?);
474 context: &RewriteContext,
476 block_like_iter: impl Iterator<Item = bool>,
477 ) -> Option<String> {
478 let connector = if self.fits_single_line {
479 // Yay, we can put everything on one line.
483 if *context.force_one_line_chain.borrow() {
486 child_shape.to_string_with_newline(context.config)
489 let mut rewrite_iter = self.rewrites.iter();
490 let mut result = rewrite_iter.next().unwrap().clone();
492 for (rewrite, prev_is_block_like) in rewrite_iter.zip(block_like_iter) {
493 if !prev_is_block_like {
494 result.push_str(&connector);
496 result.push_str(&rewrite);
503 // Formats a chain using block indent.
504 struct ChainFormatterBlock<'a> {
505 shared: ChainFormatterShared<'a>,
506 // For each rewrite, whether the corresponding item is block-like.
507 is_block_like: Vec<bool>,
510 impl<'a> ChainFormatterBlock<'a> {
511 fn new(chain: &'a Chain) -> ChainFormatterBlock<'a> {
512 ChainFormatterBlock {
513 shared: ChainFormatterShared::new(chain),
514 is_block_like: Vec::with_capacity(chain.children.len() + 1),
519 impl<'a> ChainFormatter for ChainFormatterBlock<'a> {
523 context: &RewriteContext,
526 let mut root_rewrite: String = parent.rewrite(context, shape)?;
528 let mut root_ends_with_block = is_block_expr(context, &parent.expr, &root_rewrite);
529 let tab_width = context.config.tab_spaces().saturating_sub(shape.offset);
531 while root_rewrite.len() <= tab_width && !root_rewrite.contains('\n') {
532 let item = &self.shared.children[self.shared.children.len() - 1];
533 let shape = shape.offset_left(root_rewrite.len())?;
534 match &item.rewrite_postfix(context, shape) {
535 Some(rewrite) => root_rewrite.push_str(rewrite),
539 root_ends_with_block = is_block_expr(context, &item.expr, &root_rewrite);
541 self.shared.children = &self.shared.children[..self.shared.children.len() - 1];
542 if self.shared.children.is_empty() {
546 self.is_block_like.push(root_ends_with_block);
547 self.shared.rewrites.push(root_rewrite);
551 fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape> {
553 if self.is_block_like[0] {
554 shape.block_indent(0)
556 shape.block_indent(context.config.tab_spaces())
557 }.with_max_width(context.config),
561 fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
562 for item in self.shared.children[1..].iter().rev() {
563 let rewrite = item.rewrite_postfix(context, child_shape)?;
565 .push(is_block_expr(context, &item.expr, &rewrite));
566 self.shared.rewrites.push(rewrite);
571 fn format_last_child(
573 context: &RewriteContext,
578 .format_last_child(true, context, shape, child_shape)
581 fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
583 .join_rewrites(context, child_shape, self.is_block_like.iter().cloned())
586 fn pure_root(&mut self) -> Option<String> {
587 self.shared.pure_root()
591 // Format a chain using visual indent.
592 struct ChainFormatterVisual<'a> {
593 shared: ChainFormatterShared<'a>,
594 // The extra offset from the chain's shape to the position of the `.`
598 impl<'a> ChainFormatterVisual<'a> {
599 fn new(chain: &'a Chain) -> ChainFormatterVisual<'a> {
600 ChainFormatterVisual {
601 shared: ChainFormatterShared::new(chain),
607 impl<'a> ChainFormatter for ChainFormatterVisual<'a> {
611 context: &RewriteContext,
614 let parent_shape = shape.visual_indent(0);
615 let mut root_rewrite = parent.rewrite(context, parent_shape)?;
616 let multiline = root_rewrite.contains('\n');
617 self.offset = if multiline {
618 last_line_width(&root_rewrite).saturating_sub(shape.used_width())
620 trimmed_last_line_width(&root_rewrite)
623 if !multiline || is_block_expr(context, &parent.expr, &root_rewrite) {
624 let item = &self.shared.children[self.shared.children.len() - 1];
625 let child_shape = parent_shape
626 .visual_indent(self.offset)
627 .sub_width(self.offset)?;
628 let rewrite = item.rewrite_postfix(context, child_shape)?;
629 match wrap_str(rewrite, context.config.max_width(), shape) {
630 Some(rewrite) => root_rewrite.push_str(&rewrite),
632 // We couldn't fit in at the visual indent, try the last
634 let rewrite = item.rewrite_postfix(context, parent_shape)?;
635 root_rewrite.push_str(&rewrite);
640 self.shared.children = &self.shared.children[..self.shared.children.len() - 1];
643 self.shared.rewrites.push(root_rewrite);
647 fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape> {
649 .with_max_width(context.config)
650 .offset_left(self.offset)
651 .map(|s| s.visual_indent(0))
654 fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
655 for item in self.shared.children[1..].iter().rev() {
656 let rewrite = item.rewrite_postfix(context, child_shape)?;
657 self.shared.rewrites.push(rewrite);
662 fn format_last_child(
664 context: &RewriteContext,
669 .format_last_child(false, context, shape, child_shape)
672 fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
674 .join_rewrites(context, child_shape, iter::repeat(false))
677 fn pure_root(&mut self) -> Option<String> {
678 self.shared.pure_root()
682 // States whether an expression's last line exclusively consists of closing
683 // parens, braces, and brackets in its idiomatic formatting.
684 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
686 ast::ExprKind::Mac(..)
687 | ast::ExprKind::Call(..)
688 | ast::ExprKind::MethodCall(..)
689 | ast::ExprKind::Struct(..)
690 | ast::ExprKind::While(..)
691 | ast::ExprKind::WhileLet(..)
692 | ast::ExprKind::If(..)
693 | ast::ExprKind::IfLet(..)
694 | ast::ExprKind::Block(..)
695 | ast::ExprKind::Loop(..)
696 | ast::ExprKind::ForLoop(..)
697 | ast::ExprKind::Match(..) => repr.contains('\n'),
698 ast::ExprKind::Paren(ref expr)
699 | ast::ExprKind::Binary(_, _, ref expr)
700 | ast::ExprKind::Index(_, ref expr)
701 | ast::ExprKind::Unary(_, ref expr)
702 | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
703 | ast::ExprKind::Try(ref expr)
704 | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
705 // This can only be a string lit
706 ast::ExprKind::Lit(_) => {
707 repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()