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.
107 // FIXME: we can't use a reference here because to convert `try!` to `?` we
108 // synthesise the AST node. However, I think we could use `Cow` and that
109 // would remove a lot of cloning.
115 Vec<ast::GenericArg>,
116 Vec<ptr::P<ast::Expr>>,
118 StructField(ast::Ident),
119 TupleField(ast::Ident, bool),
123 fn is_block_like(&self, context: &RewriteContext, reps: &str) -> bool {
125 ChainItemKind::Parent(ref expr) => is_block_expr(context, expr, reps),
126 ChainItemKind::MethodCall(..) => reps.contains('\n'),
127 ChainItemKind::StructField(..) | ChainItemKind::TupleField(..) => false,
131 fn is_tup_field_access(expr: &ast::Expr) -> bool {
133 ast::ExprKind::Field(_, ref field) => {
134 field.name.to_string().chars().all(|c| c.is_digit(10))
140 fn from_ast(expr: &ast::Expr) -> (ChainItemKind, Span) {
142 ast::ExprKind::MethodCall(ref segment, ref expressions) => {
143 let types = if let Some(ref generic_args) = segment.args {
144 if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
152 let kind = ChainItemKind::MethodCall(segment.clone(), types, expressions.clone());
155 ast::ExprKind::Field(ref nested, field) => {
156 let kind = if Self::is_tup_field_access(expr) {
157 ChainItemKind::TupleField(field, Self::is_tup_field_access(nested))
159 ChainItemKind::StructField(field)
163 _ => (ChainItemKind::Parent(expr.clone()), expr.span),
168 impl Rewrite for ChainItem {
169 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
170 let shape = shape.sub_width(self.tries)?;
171 let rewrite = match self.kind {
172 ChainItemKind::Parent(ref expr) => expr.rewrite(context, shape)?,
173 ChainItemKind::MethodCall(ref segment, ref types, ref exprs) => {
174 Self::rewrite_method_call(segment.ident, types, exprs, self.span, context, shape)?
176 ChainItemKind::StructField(ident) => format!(".{}", ident.name),
177 ChainItemKind::TupleField(ident, nested) => {
178 format!("{}.{}", if nested { " " } else { "" }, ident.name)
181 Some(format!("{}{}", rewrite, "?".repeat(self.tries)))
186 fn new(expr: &ast::Expr, tries: usize) -> ChainItem {
187 let (kind, span) = ChainItemKind::from_ast(expr);
188 ChainItem { kind, tries, span }
191 fn rewrite_method_call(
192 method_name: ast::Ident,
193 types: &[ast::GenericArg],
194 args: &[ptr::P<ast::Expr>],
196 context: &RewriteContext,
198 ) -> Option<String> {
199 let (lo, type_str) = if types.is_empty() {
200 (args[0].span.hi(), String::new())
202 let type_list = types
204 .map(|ty| ty.rewrite(context, shape))
205 .collect::<Option<Vec<_>>>()?;
207 let type_str = format!("::<{}>", type_list.join(", "));
209 (types.last().unwrap().span().hi(), type_str)
212 let callee_str = format!(".{}{}", method_name, type_str);
213 let span = mk_sp(lo, span.hi());
215 rewrite_call(context, &callee_str, &args[1..], span, shape)
222 children: Vec<ChainItem>,
226 fn from_ast(expr: &ast::Expr, context: &RewriteContext) -> Chain {
227 let subexpr_list = Self::make_subexpr_list(expr, context);
229 // Un-parse the expression tree into ChainItems
230 let mut children = vec![];
231 let mut sub_tries = 0;
232 for subexpr in &subexpr_list {
234 ast::ExprKind::Try(_) => sub_tries += 1,
236 children.push(ChainItem::new(subexpr, sub_tries));
243 parent: children.pop().unwrap(),
248 // Returns a Vec of the prefixes of the chain.
249 // E.g., for input `a.b.c` we return [`a.b.c`, `a.b`, 'a']
250 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> Vec<ast::Expr> {
251 let mut subexpr_list = vec![expr.clone()];
253 while let Some(subexpr) = Self::pop_expr_chain(subexpr_list.last().unwrap(), context) {
254 subexpr_list.push(subexpr.clone());
260 // Returns the expression's subexpression, if it exists. When the subexpr
261 // is a try! macro, we'll convert it to shorthand when the option is set.
262 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
264 ast::ExprKind::MethodCall(_, ref expressions) => {
265 Some(Self::convert_try(&expressions[0], context))
267 ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) => {
268 Some(Self::convert_try(subexpr, context))
274 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
276 ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
277 if let Some(subexpr) = convert_try_mac(mac, context) {
288 impl Rewrite for Chain {
289 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
290 debug!("rewrite chain {:?} {:?}", self, shape);
292 let mut formatter = match context.config.indent_style() {
293 IndentStyle::Block => Box::new(ChainFormatterBlock::new(self)) as Box<ChainFormatter>,
294 IndentStyle::Visual => Box::new(ChainFormatterVisual::new(self)) as Box<ChainFormatter>,
297 formatter.format_root(&self.parent, context, shape)?;
298 if let Some(result) = formatter.pure_root() {
299 return wrap_str(result, context.config.max_width(), shape);
302 // Decide how to layout the rest of the chain.
303 let child_shape = formatter.child_shape(context, shape)?;
305 formatter.format_children(context, child_shape)?;
306 formatter.format_last_child(context, shape, child_shape)?;
308 let result = formatter.join_rewrites(context, child_shape)?;
309 wrap_str(result, context.config.max_width(), shape)
313 // There are a few types for formatting chains. This is because there is a lot
314 // in common between formatting with block vs visual indent, but they are
315 // different enough that branching on the indent all over the place gets ugly.
316 // Anything that can format a chain is a ChainFormatter.
317 trait ChainFormatter {
318 // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
319 // Root is the parent plus any other chain items placed on the first line to
320 // avoid an orphan. E.g.,
325 // If `bar` were not part of the root, then foo would be orphaned and 'float'.
329 context: &RewriteContext,
332 fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape>;
333 fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()>;
334 fn format_last_child(
336 context: &RewriteContext,
340 fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String>;
341 // Returns `Some` if the chain is only a root, None otherwise.
342 fn pure_root(&mut self) -> Option<String>;
345 // Data and behaviour that is shared by both chain formatters. The concrete
346 // formatters can delegate much behaviour to `ChainFormatterShared`.
347 struct ChainFormatterShared<'a> {
348 // The current working set of child items.
349 children: &'a [ChainItem],
350 // The current rewrites of items (includes trailing `?`s, but not any way to
351 // connect the rewrites together).
352 rewrites: Vec<String>,
353 // Whether the chain can fit on one line.
354 fits_single_line: bool,
355 // The number of children in the chain. This is not equal to `self.children.len()`
356 // because `self.children` will change size as we process the chain.
360 impl<'a> ChainFormatterShared<'a> {
361 fn new(chain: &'a Chain) -> ChainFormatterShared<'a> {
362 ChainFormatterShared {
363 children: &chain.children,
364 rewrites: Vec::with_capacity(chain.children.len() + 1),
365 fits_single_line: false,
366 child_count: chain.children.len(),
370 fn pure_root(&mut self) -> Option<String> {
371 if self.children.is_empty() {
372 assert_eq!(self.rewrites.len(), 1);
373 Some(self.rewrites.pop().unwrap())
379 // Rewrite the last child. The last child of a chain requires special treatment. We need to
380 // know whether 'overflowing' the last child make a better formatting:
382 // A chain with overflowing the last child:
384 // parent.child1.child2.last_child(
391 // A chain without overflowing the last child (in vertical layout):
396 // .last_child(a, b, c)
399 // In particular, overflowing is effective when the last child is a method with a multi-lined
400 // block-like argument (e.g. closure):
402 // parent.child1.child2.last_child(|a, b, c| {
403 // let x = foo(a, b, c);
404 // let y = bar(a, b, c);
411 fn format_last_child(
414 context: &RewriteContext,
418 let last = &self.children[0];
420 may_extend && last_line_extendable(&self.rewrites[self.rewrites.len() - 1]);
421 let prev_last_line_width = last_line_width(&self.rewrites[self.rewrites.len() - 1]);
423 // Total of all items excluding the last.
424 let almost_total = if extendable {
427 self.rewrites.iter().fold(0, |a, b| a + b.len())
429 let one_line_budget = if self.child_count == 1 {
432 min(shape.width, context.config.width_heuristics().chain_width)
433 }.saturating_sub(almost_total);
435 let all_in_one_line =
436 self.rewrites.iter().all(|s| !s.contains('\n')) && one_line_budget > 0;
437 let last_shape = if all_in_one_line {
438 shape.sub_width(last.tries)?
439 } else if extendable {
440 child_shape.sub_width(last.tries)?
442 child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?
445 let mut last_subexpr_str = None;
446 if all_in_one_line || extendable {
447 // First we try to 'overflow' the last child and see if it looks better than using
449 if let Some(one_line_shape) = last_shape.offset_left(almost_total) {
450 if let Some(rw) = last.rewrite(context, one_line_shape) {
451 // We allow overflowing here only if both of the following conditions match:
452 // 1. The entire chain fits in a single line except the last child.
453 // 2. `last_child_str.lines().count() >= 5`.
454 let line_count = rw.lines().count();
455 let could_fit_single_line = first_line_width(&rw) <= one_line_budget;
456 if could_fit_single_line && line_count >= 5 {
457 last_subexpr_str = Some(rw);
458 self.fits_single_line = all_in_one_line;
460 // We could not know whether overflowing is better than using vertical
461 // layout, just by looking at the overflowed rewrite. Now we rewrite the
462 // last child on its own line, and compare two rewrites to choose which is
464 let last_shape = child_shape
465 .sub_width(shape.rhs_overhead(context.config) + last.tries)?;
466 match last.rewrite(context, last_shape) {
467 Some(ref new_rw) if !could_fit_single_line => {
468 last_subexpr_str = Some(new_rw.clone());
470 Some(ref new_rw) if new_rw.lines().count() >= line_count => {
471 last_subexpr_str = Some(rw);
472 self.fits_single_line = could_fit_single_line && all_in_one_line;
474 new_rw @ Some(..) => {
475 last_subexpr_str = new_rw;
478 last_subexpr_str = Some(rw);
479 self.fits_single_line = could_fit_single_line && all_in_one_line;
487 last_subexpr_str = last_subexpr_str.or_else(|| last.rewrite(context, last_shape));
488 self.rewrites.push(last_subexpr_str?);
494 context: &RewriteContext,
496 block_like_iter: impl Iterator<Item = bool>,
497 ) -> Option<String> {
498 let connector = if self.fits_single_line {
499 // Yay, we can put everything on one line.
503 if *context.force_one_line_chain.borrow() {
506 child_shape.to_string_with_newline(context.config)
509 let mut rewrite_iter = self.rewrites.iter();
510 let mut result = rewrite_iter.next().unwrap().clone();
512 for (rewrite, prev_is_block_like) in rewrite_iter.zip(block_like_iter) {
513 if !prev_is_block_like {
514 result.push_str(&connector);
516 result.push_str(&rewrite);
523 // Formats a chain using block indent.
524 struct ChainFormatterBlock<'a> {
525 shared: ChainFormatterShared<'a>,
526 // For each rewrite, whether the corresponding item is block-like.
527 is_block_like: Vec<bool>,
530 impl<'a> ChainFormatterBlock<'a> {
531 fn new(chain: &'a Chain) -> ChainFormatterBlock<'a> {
532 ChainFormatterBlock {
533 shared: ChainFormatterShared::new(chain),
534 is_block_like: Vec::with_capacity(chain.children.len() + 1),
539 impl<'a> ChainFormatter for ChainFormatterBlock<'a> {
543 context: &RewriteContext,
546 let mut root_rewrite: String = parent.rewrite(context, shape)?;
548 let mut root_ends_with_block = parent.kind.is_block_like(context, &root_rewrite);
549 let tab_width = context.config.tab_spaces().saturating_sub(shape.offset);
551 while root_rewrite.len() <= tab_width && !root_rewrite.contains('\n') {
552 let item = &self.shared.children[self.shared.children.len() - 1];
553 let shape = shape.offset_left(root_rewrite.len())?;
554 match &item.rewrite(context, shape) {
555 Some(rewrite) => root_rewrite.push_str(rewrite),
559 root_ends_with_block = item.kind.is_block_like(context, &root_rewrite);
561 self.shared.children = &self.shared.children[..self.shared.children.len() - 1];
562 if self.shared.children.is_empty() {
566 self.is_block_like.push(root_ends_with_block);
567 self.shared.rewrites.push(root_rewrite);
571 fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape> {
573 if self.is_block_like[0] {
574 shape.block_indent(0)
576 shape.block_indent(context.config.tab_spaces())
577 }.with_max_width(context.config),
581 fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
582 for item in self.shared.children[1..].iter().rev() {
583 let rewrite = item.rewrite(context, child_shape)?;
585 .push(item.kind.is_block_like(context, &rewrite));
586 self.shared.rewrites.push(rewrite);
591 fn format_last_child(
593 context: &RewriteContext,
598 .format_last_child(true, context, shape, child_shape)
601 fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
603 .join_rewrites(context, child_shape, self.is_block_like.iter().cloned())
606 fn pure_root(&mut self) -> Option<String> {
607 self.shared.pure_root()
611 // Format a chain using visual indent.
612 struct ChainFormatterVisual<'a> {
613 shared: ChainFormatterShared<'a>,
614 // The extra offset from the chain's shape to the position of the `.`
618 impl<'a> ChainFormatterVisual<'a> {
619 fn new(chain: &'a Chain) -> ChainFormatterVisual<'a> {
620 ChainFormatterVisual {
621 shared: ChainFormatterShared::new(chain),
627 impl<'a> ChainFormatter for ChainFormatterVisual<'a> {
631 context: &RewriteContext,
634 let parent_shape = shape.visual_indent(0);
635 let mut root_rewrite = parent.rewrite(context, parent_shape)?;
636 let multiline = root_rewrite.contains('\n');
637 self.offset = if multiline {
638 last_line_width(&root_rewrite).saturating_sub(shape.used_width())
640 trimmed_last_line_width(&root_rewrite)
643 if !multiline || parent.kind.is_block_like(context, &root_rewrite) {
644 let item = &self.shared.children[self.shared.children.len() - 1];
645 let child_shape = parent_shape
646 .visual_indent(self.offset)
647 .sub_width(self.offset)?;
648 let rewrite = item.rewrite(context, child_shape)?;
649 match wrap_str(rewrite, context.config.max_width(), shape) {
650 Some(rewrite) => root_rewrite.push_str(&rewrite),
652 // We couldn't fit in at the visual indent, try the last
654 let rewrite = item.rewrite(context, parent_shape)?;
655 root_rewrite.push_str(&rewrite);
660 self.shared.children = &self.shared.children[..self.shared.children.len() - 1];
663 self.shared.rewrites.push(root_rewrite);
667 fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape> {
669 .with_max_width(context.config)
670 .offset_left(self.offset)
671 .map(|s| s.visual_indent(0))
674 fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
675 for item in self.shared.children[1..].iter().rev() {
676 let rewrite = item.rewrite(context, child_shape)?;
677 self.shared.rewrites.push(rewrite);
682 fn format_last_child(
684 context: &RewriteContext,
689 .format_last_child(false, context, shape, child_shape)
692 fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
694 .join_rewrites(context, child_shape, iter::repeat(false))
697 fn pure_root(&mut self) -> Option<String> {
698 self.shared.pure_root()
702 // States whether an expression's last line exclusively consists of closing
703 // parens, braces, and brackets in its idiomatic formatting.
704 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
706 ast::ExprKind::Mac(..)
707 | ast::ExprKind::Call(..)
708 | ast::ExprKind::MethodCall(..)
709 | ast::ExprKind::Struct(..)
710 | ast::ExprKind::While(..)
711 | ast::ExprKind::WhileLet(..)
712 | ast::ExprKind::If(..)
713 | ast::ExprKind::IfLet(..)
714 | ast::ExprKind::Block(..)
715 | ast::ExprKind::Loop(..)
716 | ast::ExprKind::ForLoop(..)
717 | ast::ExprKind::Match(..) => repr.contains('\n'),
718 ast::ExprKind::Paren(ref expr)
719 | ast::ExprKind::Binary(_, _, ref expr)
720 | ast::ExprKind::Index(_, ref expr)
721 | ast::ExprKind::Unary(_, ref expr)
722 | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
723 | ast::ExprKind::Try(ref expr)
724 | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
725 // This can only be a string lit
726 ast::ExprKind::Lit(_) => {
727 repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()