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 codemap::SpanUtils;
69 use comment::rewrite_comment;
70 use config::IndentStyle;
71 use expr::rewrite_call;
72 use macros::convert_try_mac;
73 use rewrite::{Rewrite, RewriteContext};
76 first_line_width, last_line_extendable, last_line_width, mk_sp, trimmed_last_line_width,
84 use syntax::codemap::Span;
85 use syntax::{ast, ptr};
87 pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -> Option<String> {
88 let chain = Chain::from_ast(expr, context);
89 debug!("rewrite_chain {:?} {:?}", chain, shape);
91 // If this is just an expression with some `?`s, then format it trivially and
93 if chain.children.is_empty() {
94 return chain.parent.rewrite(context, shape);
97 chain.rewrite(context, shape)
100 // An expression plus trailing `?`s to be formatted together.
108 // FIXME: we can't use a reference here because to convert `try!` to `?` we
109 // synthesise the AST node. However, I think we could use `Cow` and that
110 // would remove a lot of cloning.
116 Vec<ast::GenericArg>,
117 Vec<ptr::P<ast::Expr>>,
119 StructField(ast::Ident),
120 TupleField(ast::Ident, bool),
125 fn is_block_like(&self, context: &RewriteContext, reps: &str) -> bool {
127 ChainItemKind::Parent(ref expr) => is_block_expr(context, expr, reps),
128 ChainItemKind::MethodCall(..) => reps.contains('\n'),
129 ChainItemKind::StructField(..)
130 | ChainItemKind::TupleField(..)
131 | ChainItemKind::Comment => false,
135 fn is_tup_field_access(expr: &ast::Expr) -> bool {
137 ast::ExprKind::Field(_, ref field) => {
138 field.name.to_string().chars().all(|c| c.is_digit(10))
144 fn from_ast(context: &RewriteContext, expr: &ast::Expr) -> (ChainItemKind, Span) {
145 let (kind, span) = match expr.node {
146 ast::ExprKind::MethodCall(ref segment, ref expressions) => {
147 let types = if let Some(ref generic_args) = segment.args {
148 if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
156 let span = mk_sp(expressions[0].span.hi(), expr.span.hi());
157 let kind = ChainItemKind::MethodCall(segment.clone(), types, expressions.clone());
160 ast::ExprKind::Field(ref nested, field) => {
161 let kind = if Self::is_tup_field_access(expr) {
162 ChainItemKind::TupleField(field, Self::is_tup_field_access(nested))
164 ChainItemKind::StructField(field)
166 let span = mk_sp(nested.span.hi(), field.span.hi());
169 _ => return (ChainItemKind::Parent(expr.clone()), expr.span),
172 // Remove comments from the span.
173 let lo = context.snippet_provider.span_before(span, ".");
174 (kind, mk_sp(lo, span.hi()))
178 impl Rewrite for ChainItem {
179 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
180 let shape = shape.sub_width(self.tries)?;
181 let rewrite = match self.kind {
182 ChainItemKind::Parent(ref expr) => expr.rewrite(context, shape)?,
183 ChainItemKind::MethodCall(ref segment, ref types, ref exprs) => {
184 Self::rewrite_method_call(segment.ident, types, exprs, self.span, context, shape)?
186 ChainItemKind::StructField(ident) => format!(".{}", ident.name),
187 ChainItemKind::TupleField(ident, nested) => {
188 format!("{}.{}", if nested { " " } else { "" }, ident.name)
190 ChainItemKind::Comment => rewrite_comment(
191 context.snippet(self.span).trim(),
197 Some(format!("{}{}", rewrite, "?".repeat(self.tries)))
202 fn new(context: &RewriteContext, expr: &ast::Expr, tries: usize) -> ChainItem {
203 let (kind, span) = ChainItemKind::from_ast(context, expr);
204 ChainItem { kind, tries, span }
207 fn comment(span: Span) -> ChainItem {
209 kind: ChainItemKind::Comment,
215 fn is_comment(&self) -> bool {
217 ChainItemKind::Comment => true,
222 fn rewrite_method_call(
223 method_name: ast::Ident,
224 types: &[ast::GenericArg],
225 args: &[ptr::P<ast::Expr>],
227 context: &RewriteContext,
229 ) -> Option<String> {
230 let type_str = if types.is_empty() {
233 let type_list = types
235 .map(|ty| ty.rewrite(context, shape))
236 .collect::<Option<Vec<_>>>()?;
238 format!("::<{}>", type_list.join(", "))
240 let callee_str = format!(".{}{}", method_name, type_str);
241 rewrite_call(context, &callee_str, &args[1..], span, shape)
248 children: Vec<ChainItem>,
252 fn from_ast(expr: &ast::Expr, context: &RewriteContext) -> Chain {
253 let subexpr_list = Self::make_subexpr_list(expr, context);
255 // Un-parse the expression tree into ChainItems
256 let mut rev_children = vec![];
257 let mut sub_tries = 0;
258 for subexpr in &subexpr_list {
260 ast::ExprKind::Try(_) => sub_tries += 1,
262 rev_children.push(ChainItem::new(context, subexpr, sub_tries));
268 fn is_tries(s: &str) -> bool {
269 s.chars().all(|c| c == '?')
272 let parent = rev_children.pop().unwrap();
273 let mut children = vec![];
274 let mut prev_hi = parent.span.hi();
275 for chain_item in rev_children.into_iter().rev() {
276 let comment_span = mk_sp(prev_hi, chain_item.span.lo());
277 let comment_snippet = context.snippet(comment_span);
278 // FIXME: Figure out the way to get a correct span when converting `try!` to `?`.
279 if !(context.config.use_try_shorthand()
280 || comment_snippet.trim().is_empty()
281 || is_tries(comment_snippet.trim()))
283 children.push(ChainItem::comment(comment_span));
285 prev_hi = chain_item.span.hi();
286 children.push(chain_item);
289 Chain { parent, children }
292 // Returns a Vec of the prefixes of the chain.
293 // E.g., for input `a.b.c` we return [`a.b.c`, `a.b`, 'a']
294 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> Vec<ast::Expr> {
295 let mut subexpr_list = vec![expr.clone()];
297 while let Some(subexpr) = Self::pop_expr_chain(subexpr_list.last().unwrap(), context) {
298 subexpr_list.push(subexpr.clone());
304 // Returns the expression's subexpression, if it exists. When the subexpr
305 // is a try! macro, we'll convert it to shorthand when the option is set.
306 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
308 ast::ExprKind::MethodCall(_, ref expressions) => {
309 Some(Self::convert_try(&expressions[0], context))
311 ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) => {
312 Some(Self::convert_try(subexpr, context))
318 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
320 ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
321 if let Some(subexpr) = convert_try_mac(mac, context) {
332 impl Rewrite for Chain {
333 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
334 debug!("rewrite chain {:?} {:?}", self, shape);
336 let mut formatter = match context.config.indent_style() {
337 IndentStyle::Block => Box::new(ChainFormatterBlock::new(self)) as Box<ChainFormatter>,
338 IndentStyle::Visual => Box::new(ChainFormatterVisual::new(self)) as Box<ChainFormatter>,
341 formatter.format_root(&self.parent, context, shape)?;
342 if let Some(result) = formatter.pure_root() {
343 return wrap_str(result, context.config.max_width(), shape);
346 // Decide how to layout the rest of the chain.
347 let child_shape = formatter.child_shape(context, shape)?;
349 formatter.format_children(context, child_shape)?;
350 formatter.format_last_child(context, shape, child_shape)?;
352 let result = formatter.join_rewrites(context, child_shape)?;
353 wrap_str(result, context.config.max_width(), shape)
357 // There are a few types for formatting chains. This is because there is a lot
358 // in common between formatting with block vs visual indent, but they are
359 // different enough that branching on the indent all over the place gets ugly.
360 // Anything that can format a chain is a ChainFormatter.
361 trait ChainFormatter {
362 // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
363 // Root is the parent plus any other chain items placed on the first line to
364 // avoid an orphan. E.g.,
369 // If `bar` were not part of the root, then foo would be orphaned and 'float'.
373 context: &RewriteContext,
376 fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape>;
377 fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()>;
378 fn format_last_child(
380 context: &RewriteContext,
384 fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String>;
385 // Returns `Some` if the chain is only a root, None otherwise.
386 fn pure_root(&mut self) -> Option<String>;
389 // Data and behaviour that is shared by both chain formatters. The concrete
390 // formatters can delegate much behaviour to `ChainFormatterShared`.
391 struct ChainFormatterShared<'a> {
392 // The current working set of child items.
393 children: &'a [ChainItem],
394 // The current rewrites of items (includes trailing `?`s, but not any way to
395 // connect the rewrites together).
396 rewrites: Vec<String>,
397 // Whether the chain can fit on one line.
398 fits_single_line: bool,
399 // The number of children in the chain. This is not equal to `self.children.len()`
400 // because `self.children` will change size as we process the chain.
404 impl<'a> ChainFormatterShared<'a> {
405 fn new(chain: &'a Chain) -> ChainFormatterShared<'a> {
406 ChainFormatterShared {
407 children: &chain.children,
408 rewrites: Vec::with_capacity(chain.children.len() + 1),
409 fits_single_line: false,
410 child_count: chain.children.len(),
414 fn pure_root(&mut self) -> Option<String> {
415 if self.children.is_empty() {
416 assert_eq!(self.rewrites.len(), 1);
417 Some(self.rewrites.pop().unwrap())
423 // Rewrite the last child. The last child of a chain requires special treatment. We need to
424 // know whether 'overflowing' the last child make a better formatting:
426 // A chain with overflowing the last child:
428 // parent.child1.child2.last_child(
435 // A chain without overflowing the last child (in vertical layout):
440 // .last_child(a, b, c)
443 // In particular, overflowing is effective when the last child is a method with a multi-lined
444 // block-like argument (e.g. closure):
446 // parent.child1.child2.last_child(|a, b, c| {
447 // let x = foo(a, b, c);
448 // let y = bar(a, b, c);
455 fn format_last_child(
458 context: &RewriteContext,
462 let last = self.children.last()?;
463 let extendable = may_extend && last_line_extendable(&self.rewrites[0]);
464 let prev_last_line_width = last_line_width(&self.rewrites[0]);
466 // Total of all items excluding the last.
467 let almost_total = if extendable {
470 self.rewrites.iter().fold(0, |a, b| a + b.len())
472 let one_line_budget = if self.child_count == 1 {
475 min(shape.width, context.config.width_heuristics().chain_width)
476 }.saturating_sub(almost_total);
478 let all_in_one_line = !self.children.iter().any(ChainItem::is_comment)
479 && self.rewrites.iter().all(|s| !s.contains('\n'))
480 && one_line_budget > 0;
481 let last_shape = if all_in_one_line {
482 shape.sub_width(last.tries)?
483 } else if extendable {
484 child_shape.sub_width(last.tries)?
486 child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?
489 let mut last_subexpr_str = None;
490 if all_in_one_line || extendable {
491 // First we try to 'overflow' the last child and see if it looks better than using
493 if let Some(one_line_shape) = last_shape.offset_left(almost_total) {
494 if let Some(rw) = last.rewrite(context, one_line_shape) {
495 // We allow overflowing here only if both of the following conditions match:
496 // 1. The entire chain fits in a single line except the last child.
497 // 2. `last_child_str.lines().count() >= 5`.
498 let line_count = rw.lines().count();
499 let could_fit_single_line = first_line_width(&rw) <= one_line_budget;
500 if could_fit_single_line && line_count >= 5 {
501 last_subexpr_str = Some(rw);
502 self.fits_single_line = all_in_one_line;
504 // We could not know whether overflowing is better than using vertical
505 // layout, just by looking at the overflowed rewrite. Now we rewrite the
506 // last child on its own line, and compare two rewrites to choose which is
508 let last_shape = child_shape
509 .sub_width(shape.rhs_overhead(context.config) + last.tries)?;
510 match last.rewrite(context, last_shape) {
511 Some(ref new_rw) if !could_fit_single_line => {
512 last_subexpr_str = Some(new_rw.clone());
514 Some(ref new_rw) if new_rw.lines().count() >= line_count => {
515 last_subexpr_str = Some(rw);
516 self.fits_single_line = could_fit_single_line && all_in_one_line;
518 new_rw @ Some(..) => {
519 last_subexpr_str = new_rw;
522 last_subexpr_str = Some(rw);
523 self.fits_single_line = could_fit_single_line && all_in_one_line;
531 last_subexpr_str = last_subexpr_str.or_else(|| last.rewrite(context, last_shape));
532 self.rewrites.push(last_subexpr_str?);
538 context: &RewriteContext,
540 block_like_iter: impl Iterator<Item = bool>,
541 ) -> Option<String> {
542 let connector = if self.fits_single_line {
543 // Yay, we can put everything on one line.
547 if *context.force_one_line_chain.borrow() {
550 child_shape.to_string_with_newline(context.config)
553 let mut rewrite_iter = self.rewrites.iter();
554 let mut result = rewrite_iter.next().unwrap().clone();
556 for (rewrite, prev_is_block_like) in rewrite_iter.zip(block_like_iter) {
557 if !prev_is_block_like {
558 result.push_str(&connector);
559 } else if rewrite.starts_with('/') {
560 // This is comment, add a space before it.
563 result.push_str(&rewrite);
570 // Formats a chain using block indent.
571 struct ChainFormatterBlock<'a> {
572 shared: ChainFormatterShared<'a>,
573 // For each rewrite, whether the corresponding item is block-like.
574 is_block_like: Vec<bool>,
577 impl<'a> ChainFormatterBlock<'a> {
578 fn new(chain: &'a Chain) -> ChainFormatterBlock<'a> {
579 ChainFormatterBlock {
580 shared: ChainFormatterShared::new(chain),
581 is_block_like: Vec::with_capacity(chain.children.len() + 1),
586 impl<'a> ChainFormatter for ChainFormatterBlock<'a> {
590 context: &RewriteContext,
593 let mut root_rewrite: String = parent.rewrite(context, shape)?;
595 let mut root_ends_with_block = parent.kind.is_block_like(context, &root_rewrite);
596 let tab_width = context.config.tab_spaces().saturating_sub(shape.offset);
598 while root_rewrite.len() <= tab_width && !root_rewrite.contains('\n') {
599 let item = &self.shared.children[0];
600 if let ChainItemKind::Comment = item.kind {
603 let shape = shape.offset_left(root_rewrite.len())?;
604 match &item.rewrite(context, shape) {
605 Some(rewrite) => root_rewrite.push_str(rewrite),
609 root_ends_with_block = item.kind.is_block_like(context, &root_rewrite);
611 self.shared.children = &self.shared.children[1..];
612 if self.shared.children.is_empty() {
616 self.is_block_like.push(root_ends_with_block);
617 self.shared.rewrites.push(root_rewrite);
621 fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape> {
623 if self.is_block_like[0] {
624 shape.block_indent(0)
626 shape.block_indent(context.config.tab_spaces())
627 }.with_max_width(context.config),
631 fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
632 for item in &self.shared.children[..self.shared.children.len() - 1] {
633 let rewrite = item.rewrite(context, child_shape)?;
635 .push(item.kind.is_block_like(context, &rewrite));
636 self.shared.rewrites.push(rewrite);
641 fn format_last_child(
643 context: &RewriteContext,
648 .format_last_child(true, context, shape, child_shape)
651 fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
653 .join_rewrites(context, child_shape, self.is_block_like.iter().cloned())
656 fn pure_root(&mut self) -> Option<String> {
657 self.shared.pure_root()
661 // Format a chain using visual indent.
662 struct ChainFormatterVisual<'a> {
663 shared: ChainFormatterShared<'a>,
664 // The extra offset from the chain's shape to the position of the `.`
668 impl<'a> ChainFormatterVisual<'a> {
669 fn new(chain: &'a Chain) -> ChainFormatterVisual<'a> {
670 ChainFormatterVisual {
671 shared: ChainFormatterShared::new(chain),
677 impl<'a> ChainFormatter for ChainFormatterVisual<'a> {
681 context: &RewriteContext,
684 let parent_shape = shape.visual_indent(0);
685 let mut root_rewrite = parent.rewrite(context, parent_shape)?;
686 let multiline = root_rewrite.contains('\n');
687 self.offset = if multiline {
688 last_line_width(&root_rewrite).saturating_sub(shape.used_width())
690 trimmed_last_line_width(&root_rewrite)
693 if !multiline || parent.kind.is_block_like(context, &root_rewrite) {
694 let item = &self.shared.children[0];
695 if let ChainItemKind::Comment = item.kind {
696 self.shared.rewrites.push(root_rewrite);
699 let child_shape = parent_shape
700 .visual_indent(self.offset)
701 .sub_width(self.offset)?;
702 let rewrite = item.rewrite(context, child_shape)?;
703 match wrap_str(rewrite, context.config.max_width(), shape) {
704 Some(rewrite) => root_rewrite.push_str(&rewrite),
706 // We couldn't fit in at the visual indent, try the last
708 let rewrite = item.rewrite(context, parent_shape)?;
709 root_rewrite.push_str(&rewrite);
714 self.shared.children = &self.shared.children[1..];
717 self.shared.rewrites.push(root_rewrite);
721 fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape> {
723 .with_max_width(context.config)
724 .offset_left(self.offset)
725 .map(|s| s.visual_indent(0))
728 fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
729 for item in &self.shared.children[..self.shared.children.len() - 1] {
730 let rewrite = item.rewrite(context, child_shape)?;
731 self.shared.rewrites.push(rewrite);
736 fn format_last_child(
738 context: &RewriteContext,
743 .format_last_child(false, context, shape, child_shape)
746 fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
748 .join_rewrites(context, child_shape, iter::repeat(false))
751 fn pure_root(&mut self) -> Option<String> {
752 self.shared.pure_root()
756 // States whether an expression's last line exclusively consists of closing
757 // parens, braces, and brackets in its idiomatic formatting.
758 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
760 ast::ExprKind::Mac(..)
761 | ast::ExprKind::Call(..)
762 | ast::ExprKind::MethodCall(..)
763 | ast::ExprKind::Struct(..)
764 | ast::ExprKind::While(..)
765 | ast::ExprKind::WhileLet(..)
766 | ast::ExprKind::If(..)
767 | ast::ExprKind::IfLet(..)
768 | ast::ExprKind::Block(..)
769 | ast::ExprKind::Loop(..)
770 | ast::ExprKind::ForLoop(..)
771 | ast::ExprKind::Match(..) => repr.contains('\n'),
772 ast::ExprKind::Paren(ref expr)
773 | ast::ExprKind::Binary(_, _, ref expr)
774 | ast::ExprKind::Index(_, ref expr)
775 | ast::ExprKind::Unary(_, ref expr)
776 | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
777 | ast::ExprKind::Try(ref expr)
778 | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
779 // This can only be a string lit
780 ast::ExprKind::Lit(_) => {
781 repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()