]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
Reformat
[rust.git] / src / chains.rs
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.
4 //
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.
10
11 //! Formatting of chained expressions, i.e. expressions which are chained by
12 //! dots: struct and enum field access, method calls, and try shorthand (?).
13 //!
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.
17 //!
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.
21 //!
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
24 //! alignment).
25 //! E.g., `let foo = { aaaa; bbb; ccc }.bar.baz();`, we would layout for the
26 //! following values of `chain_indent`:
27 //! Block:
28 //!
29 //! ```ignore
30 //! let foo = {
31 //!     aaaa;
32 //!     bbb;
33 //!     ccc
34 //! }.bar
35 //!     .baz();
36 //! ```
37 //!
38 //! Visual:
39 //!
40 //! ```ignore
41 //! let foo = {
42 //!               aaaa;
43 //!               bbb;
44 //!               ccc
45 //!           }
46 //!           .bar
47 //!           .baz();
48 //! ```
49 //!
50 //! If the first item in the chain is a block expression, we align the dots with
51 //! the braces.
52 //! Block:
53 //!
54 //! ```ignore
55 //! let a = foo.bar
56 //!     .baz()
57 //!     .qux
58 //! ```
59 //!
60 //! Visual:
61 //!
62 //! ```ignore
63 //! let a = foo.bar
64 //!            .baz()
65 //!            .qux
66 //! ```
67
68 use comment::rewrite_comment;
69 use config::IndentStyle;
70 use expr::rewrite_call;
71 use lists::{extract_post_comment, extract_pre_comment, get_comment_end};
72 use macros::convert_try_mac;
73 use rewrite::{Rewrite, RewriteContext};
74 use shape::Shape;
75 use source_map::SpanUtils;
76 use utils::{
77     first_line_width, last_line_extendable, last_line_width, mk_sp, trimmed_last_line_width,
78     wrap_str,
79 };
80
81 use std::borrow::Cow;
82 use std::cmp::min;
83 use std::iter;
84
85 use syntax::source_map::{BytePos, Span};
86 use syntax::{ast, ptr};
87
88 pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -> Option<String> {
89     let chain = Chain::from_ast(expr, context);
90     debug!("rewrite_chain {:?} {:?}", chain, shape);
91
92     // If this is just an expression with some `?`s, then format it trivially and
93     // return early.
94     if chain.children.is_empty() {
95         return chain.parent.rewrite(context, shape);
96     }
97
98     chain.rewrite(context, shape)
99 }
100
101 #[derive(Debug)]
102 enum CommentPosition {
103     Back,
104     Top,
105 }
106
107 // An expression plus trailing `?`s to be formatted together.
108 #[derive(Debug)]
109 struct ChainItem {
110     kind: ChainItemKind,
111     tries: usize,
112     span: Span,
113 }
114
115 // FIXME: we can't use a reference here because to convert `try!` to `?` we
116 // synthesise the AST node. However, I think we could use `Cow` and that
117 // would remove a lot of cloning.
118 #[derive(Debug)]
119 enum ChainItemKind {
120     Parent(ast::Expr),
121     MethodCall(
122         ast::PathSegment,
123         Vec<ast::GenericArg>,
124         Vec<ptr::P<ast::Expr>>,
125     ),
126     StructField(ast::Ident),
127     TupleField(ast::Ident, bool),
128     Comment(String, CommentPosition),
129 }
130
131 impl ChainItemKind {
132     fn is_block_like(&self, context: &RewriteContext, reps: &str) -> bool {
133         match self {
134             ChainItemKind::Parent(ref expr) => is_block_expr(context, expr, reps),
135             ChainItemKind::MethodCall(..) => reps.contains('\n'),
136             ChainItemKind::StructField(..)
137             | ChainItemKind::TupleField(..)
138             | ChainItemKind::Comment(..) => false,
139         }
140     }
141
142     fn is_tup_field_access(expr: &ast::Expr) -> bool {
143         match expr.node {
144             ast::ExprKind::Field(_, ref field) => {
145                 field.name.to_string().chars().all(|c| c.is_digit(10))
146             }
147             _ => false,
148         }
149     }
150
151     fn from_ast(context: &RewriteContext, expr: &ast::Expr) -> (ChainItemKind, Span) {
152         let (kind, span) = match expr.node {
153             ast::ExprKind::MethodCall(ref segment, ref expressions) => {
154                 let types = if let Some(ref generic_args) = segment.args {
155                     if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
156                         data.args.clone()
157                     } else {
158                         vec![]
159                     }
160                 } else {
161                     vec![]
162                 };
163                 let span = mk_sp(expressions[0].span.hi(), expr.span.hi());
164                 let kind = ChainItemKind::MethodCall(segment.clone(), types, expressions.clone());
165                 (kind, span)
166             }
167             ast::ExprKind::Field(ref nested, field) => {
168                 let kind = if Self::is_tup_field_access(expr) {
169                     ChainItemKind::TupleField(field, Self::is_tup_field_access(nested))
170                 } else {
171                     ChainItemKind::StructField(field)
172                 };
173                 let span = mk_sp(nested.span.hi(), field.span.hi());
174                 (kind, span)
175             }
176             _ => return (ChainItemKind::Parent(expr.clone()), expr.span),
177         };
178
179         // Remove comments from the span.
180         let lo = context.snippet_provider.span_before(span, ".");
181         (kind, mk_sp(lo, span.hi()))
182     }
183 }
184
185 impl Rewrite for ChainItem {
186     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
187         let shape = shape.sub_width(self.tries)?;
188         let rewrite = match self.kind {
189             ChainItemKind::Parent(ref expr) => expr.rewrite(context, shape)?,
190             ChainItemKind::MethodCall(ref segment, ref types, ref exprs) => {
191                 Self::rewrite_method_call(segment.ident, types, exprs, self.span, context, shape)?
192             }
193             ChainItemKind::StructField(ident) => format!(".{}", ident.name),
194             ChainItemKind::TupleField(ident, nested) => {
195                 format!("{}.{}", if nested { " " } else { "" }, ident.name)
196             }
197             ChainItemKind::Comment(ref comment, _) => {
198                 rewrite_comment(comment, false, shape, context.config)?
199             }
200         };
201         Some(format!("{}{}", rewrite, "?".repeat(self.tries)))
202     }
203 }
204
205 impl ChainItem {
206     fn new(context: &RewriteContext, expr: &ast::Expr, tries: usize) -> ChainItem {
207         let (kind, span) = ChainItemKind::from_ast(context, expr);
208         ChainItem { kind, tries, span }
209     }
210
211     fn comment(span: Span, comment: String, pos: CommentPosition) -> ChainItem {
212         ChainItem {
213             kind: ChainItemKind::Comment(comment, pos),
214             tries: 0,
215             span,
216         }
217     }
218
219     fn is_comment(&self) -> bool {
220         match self.kind {
221             ChainItemKind::Comment(..) => true,
222             _ => false,
223         }
224     }
225
226     fn rewrite_method_call(
227         method_name: ast::Ident,
228         types: &[ast::GenericArg],
229         args: &[ptr::P<ast::Expr>],
230         span: Span,
231         context: &RewriteContext,
232         shape: Shape,
233     ) -> Option<String> {
234         let type_str = if types.is_empty() {
235             String::new()
236         } else {
237             let type_list = types
238                 .iter()
239                 .map(|ty| ty.rewrite(context, shape))
240                 .collect::<Option<Vec<_>>>()?;
241
242             format!("::<{}>", type_list.join(", "))
243         };
244         let callee_str = format!(".{}{}", method_name, type_str);
245         rewrite_call(context, &callee_str, &args[1..], span, shape)
246     }
247 }
248
249 #[derive(Debug)]
250 struct Chain {
251     parent: ChainItem,
252     children: Vec<ChainItem>,
253 }
254
255 impl Chain {
256     fn from_ast(expr: &ast::Expr, context: &RewriteContext) -> Chain {
257         let subexpr_list = Self::make_subexpr_list(expr, context);
258
259         // Un-parse the expression tree into ChainItems
260         let mut rev_children = vec![];
261         let mut sub_tries = 0;
262         for subexpr in &subexpr_list {
263             match subexpr.node {
264                 ast::ExprKind::Try(_) => sub_tries += 1,
265                 _ => {
266                     rev_children.push(ChainItem::new(context, subexpr, sub_tries));
267                     sub_tries = 0;
268                 }
269             }
270         }
271
272         fn is_tries(s: &str) -> bool {
273             s.chars().all(|c| c == '?')
274         }
275
276         fn handle_post_comment(
277             post_comment_span: Span,
278             post_comment_snippet: &str,
279             prev_span_end: &mut BytePos,
280             children: &mut Vec<ChainItem>,
281         ) {
282             let white_spaces: &[_] = &[' ', '\t'];
283             if post_comment_snippet
284                 .trim_matches(white_spaces)
285                 .starts_with('\n')
286             {
287                 // No post comment.
288                 return;
289             }
290             // HACK: Treat `?`s as separators.
291             let trimmed_snippet = post_comment_snippet.trim_matches('?');
292             let comment_end = get_comment_end(trimmed_snippet, "?", "", false);
293             let maybe_post_comment = extract_post_comment(trimmed_snippet, comment_end, "?")
294                 .and_then(|comment| {
295                     if comment.is_empty() {
296                         None
297                     } else {
298                         Some((comment, comment_end))
299                     }
300                 });
301
302             if let Some((post_comment, comment_end)) = maybe_post_comment {
303                 children.push(ChainItem::comment(
304                     post_comment_span,
305                     post_comment,
306                     CommentPosition::Back,
307                 ));
308                 *prev_span_end = *prev_span_end + BytePos(comment_end as u32);
309             }
310         }
311
312         let parent = rev_children.pop().unwrap();
313         let mut children = vec![];
314         let mut prev_span_end = parent.span.hi();
315         let mut iter = rev_children.into_iter().rev().peekable();
316         if let Some(first_chain_item) = iter.peek() {
317             let comment_span = mk_sp(prev_span_end, first_chain_item.span.lo());
318             let comment_snippet = context.snippet(comment_span);
319             if !is_tries(comment_snippet.trim()) {
320                 handle_post_comment(
321                     comment_span,
322                     comment_snippet,
323                     &mut prev_span_end,
324                     &mut children,
325                 );
326             }
327         }
328         while let Some(chain_item) = iter.next() {
329             let comment_snippet = context.snippet(chain_item.span);
330             // FIXME: Figure out the way to get a correct span when converting `try!` to `?`.
331             let handle_comment =
332                 !(context.config.use_try_shorthand() || is_tries(comment_snippet.trim()));
333
334             // Pre-comment
335             if handle_comment {
336                 let pre_comment_span = mk_sp(prev_span_end, chain_item.span.lo());
337                 let pre_comment_snippet = context.snippet(pre_comment_span);
338                 let pre_comment_snippet = pre_comment_snippet.trim().trim_matches('?');
339                 let (pre_comment, _) = extract_pre_comment(pre_comment_snippet);
340                 match pre_comment {
341                     Some(ref comment) if !comment.is_empty() => {
342                         children.push(ChainItem::comment(
343                             pre_comment_span,
344                             comment.to_owned(),
345                             CommentPosition::Top,
346                         ));
347                     }
348                     _ => (),
349                 }
350             }
351
352             prev_span_end = chain_item.span.hi();
353             children.push(chain_item);
354
355             // Post-comment
356             if !handle_comment || iter.peek().is_none() {
357                 continue;
358             }
359
360             let next_lo = iter.peek().unwrap().span.lo();
361             let post_comment_span = mk_sp(prev_span_end, next_lo);
362             let post_comment_snippet = context.snippet(post_comment_span);
363             handle_post_comment(
364                 post_comment_span,
365                 post_comment_snippet,
366                 &mut prev_span_end,
367                 &mut children,
368             );
369         }
370
371         Chain { parent, children }
372     }
373
374     // Returns a Vec of the prefixes of the chain.
375     // E.g., for input `a.b.c` we return [`a.b.c`, `a.b`, 'a']
376     fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> Vec<ast::Expr> {
377         let mut subexpr_list = vec![expr.clone()];
378
379         while let Some(subexpr) = Self::pop_expr_chain(subexpr_list.last().unwrap(), context) {
380             subexpr_list.push(subexpr.clone());
381         }
382
383         subexpr_list
384     }
385
386     // Returns the expression's subexpression, if it exists. When the subexpr
387     // is a try! macro, we'll convert it to shorthand when the option is set.
388     fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
389         match expr.node {
390             ast::ExprKind::MethodCall(_, ref expressions) => {
391                 Some(Self::convert_try(&expressions[0], context))
392             }
393             ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) => {
394                 Some(Self::convert_try(subexpr, context))
395             }
396             _ => None,
397         }
398     }
399
400     fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
401         match expr.node {
402             ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
403                 if let Some(subexpr) = convert_try_mac(mac, context) {
404                     subexpr
405                 } else {
406                     expr.clone()
407                 }
408             }
409             _ => expr.clone(),
410         }
411     }
412 }
413
414 impl Rewrite for Chain {
415     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
416         debug!("rewrite chain {:?} {:?}", self, shape);
417
418         let mut formatter = match context.config.indent_style() {
419             IndentStyle::Block => Box::new(ChainFormatterBlock::new(self)) as Box<ChainFormatter>,
420             IndentStyle::Visual => Box::new(ChainFormatterVisual::new(self)) as Box<ChainFormatter>,
421         };
422
423         formatter.format_root(&self.parent, context, shape)?;
424         if let Some(result) = formatter.pure_root() {
425             return wrap_str(result, context.config.max_width(), shape);
426         }
427
428         // Decide how to layout the rest of the chain.
429         let child_shape = formatter.child_shape(context, shape)?;
430
431         formatter.format_children(context, child_shape)?;
432         formatter.format_last_child(context, shape, child_shape)?;
433
434         let result = formatter.join_rewrites(context, child_shape)?;
435         wrap_str(result, context.config.max_width(), shape)
436     }
437 }
438
439 // There are a few types for formatting chains. This is because there is a lot
440 // in common between formatting with block vs visual indent, but they are
441 // different enough that branching on the indent all over the place gets ugly.
442 // Anything that can format a chain is a ChainFormatter.
443 trait ChainFormatter {
444     // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
445     // Root is the parent plus any other chain items placed on the first line to
446     // avoid an orphan. E.g.,
447     // ```
448     // foo.bar
449     //     .baz()
450     // ```
451     // If `bar` were not part of the root, then foo would be orphaned and 'float'.
452     fn format_root(
453         &mut self,
454         parent: &ChainItem,
455         context: &RewriteContext,
456         shape: Shape,
457     ) -> Option<()>;
458     fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape>;
459     fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()>;
460     fn format_last_child(
461         &mut self,
462         context: &RewriteContext,
463         shape: Shape,
464         child_shape: Shape,
465     ) -> Option<()>;
466     fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String>;
467     // Returns `Some` if the chain is only a root, None otherwise.
468     fn pure_root(&mut self) -> Option<String>;
469 }
470
471 // Data and behaviour that is shared by both chain formatters. The concrete
472 // formatters can delegate much behaviour to `ChainFormatterShared`.
473 struct ChainFormatterShared<'a> {
474     // The current working set of child items.
475     children: &'a [ChainItem],
476     // The current rewrites of items (includes trailing `?`s, but not any way to
477     // connect the rewrites together).
478     rewrites: Vec<String>,
479     // Whether the chain can fit on one line.
480     fits_single_line: bool,
481     // The number of children in the chain. This is not equal to `self.children.len()`
482     // because `self.children` will change size as we process the chain.
483     child_count: usize,
484 }
485
486 impl<'a> ChainFormatterShared<'a> {
487     fn new(chain: &'a Chain) -> ChainFormatterShared<'a> {
488         ChainFormatterShared {
489             children: &chain.children,
490             rewrites: Vec::with_capacity(chain.children.len() + 1),
491             fits_single_line: false,
492             child_count: chain.children.len(),
493         }
494     }
495
496     fn pure_root(&mut self) -> Option<String> {
497         if self.children.is_empty() {
498             assert_eq!(self.rewrites.len(), 1);
499             Some(self.rewrites.pop().unwrap())
500         } else {
501             None
502         }
503     }
504
505     // Rewrite the last child. The last child of a chain requires special treatment. We need to
506     // know whether 'overflowing' the last child make a better formatting:
507     //
508     // A chain with overflowing the last child:
509     // ```
510     // parent.child1.child2.last_child(
511     //     a,
512     //     b,
513     //     c,
514     // )
515     // ```
516     //
517     // A chain without overflowing the last child (in vertical layout):
518     // ```
519     // parent
520     //     .child1
521     //     .child2
522     //     .last_child(a, b, c)
523     // ```
524     //
525     // In particular, overflowing is effective when the last child is a method with a multi-lined
526     // block-like argument (e.g. closure):
527     // ```
528     // parent.child1.child2.last_child(|a, b, c| {
529     //     let x = foo(a, b, c);
530     //     let y = bar(a, b, c);
531     //
532     //     // ...
533     //
534     //     result
535     // })
536     // ```
537     fn format_last_child(
538         &mut self,
539         may_extend: bool,
540         context: &RewriteContext,
541         shape: Shape,
542         child_shape: Shape,
543     ) -> Option<()> {
544         let last = self.children.last()?;
545         let extendable = may_extend && last_line_extendable(&self.rewrites[0]);
546         let prev_last_line_width = last_line_width(&self.rewrites[0]);
547
548         // Total of all items excluding the last.
549         let almost_total = if extendable {
550             prev_last_line_width
551         } else {
552             self.rewrites.iter().fold(0, |a, b| a + b.len())
553         } + last.tries;
554         let one_line_budget = if self.child_count == 1 {
555             shape.width
556         } else {
557             min(shape.width, context.config.width_heuristics().chain_width)
558         }.saturating_sub(almost_total);
559
560         let all_in_one_line = !self.children.iter().any(ChainItem::is_comment)
561             && self.rewrites.iter().all(|s| !s.contains('\n'))
562             && one_line_budget > 0;
563         let last_shape = if all_in_one_line {
564             shape.sub_width(last.tries)?
565         } else if extendable {
566             child_shape.sub_width(last.tries)?
567         } else {
568             child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?
569         };
570
571         let mut last_subexpr_str = None;
572         if all_in_one_line || extendable {
573             // First we try to 'overflow' the last child and see if it looks better than using
574             // vertical layout.
575             if let Some(one_line_shape) = last_shape.offset_left(almost_total) {
576                 if let Some(rw) = last.rewrite(context, one_line_shape) {
577                     // We allow overflowing here only if both of the following conditions match:
578                     // 1. The entire chain fits in a single line except the last child.
579                     // 2. `last_child_str.lines().count() >= 5`.
580                     let line_count = rw.lines().count();
581                     let could_fit_single_line = first_line_width(&rw) <= one_line_budget;
582                     if could_fit_single_line && line_count >= 5 {
583                         last_subexpr_str = Some(rw);
584                         self.fits_single_line = all_in_one_line;
585                     } else {
586                         // We could not know whether overflowing is better than using vertical
587                         // layout, just by looking at the overflowed rewrite. Now we rewrite the
588                         // last child on its own line, and compare two rewrites to choose which is
589                         // better.
590                         let last_shape = child_shape
591                             .sub_width(shape.rhs_overhead(context.config) + last.tries)?;
592                         match last.rewrite(context, last_shape) {
593                             Some(ref new_rw) if !could_fit_single_line => {
594                                 last_subexpr_str = Some(new_rw.clone());
595                             }
596                             Some(ref new_rw) if new_rw.lines().count() >= line_count => {
597                                 last_subexpr_str = Some(rw);
598                                 self.fits_single_line = could_fit_single_line && all_in_one_line;
599                             }
600                             new_rw @ Some(..) => {
601                                 last_subexpr_str = new_rw;
602                             }
603                             _ => {
604                                 last_subexpr_str = Some(rw);
605                                 self.fits_single_line = could_fit_single_line && all_in_one_line;
606                             }
607                         }
608                     }
609                 }
610             }
611         }
612
613         last_subexpr_str = last_subexpr_str.or_else(|| last.rewrite(context, last_shape));
614         self.rewrites.push(last_subexpr_str?);
615         Some(())
616     }
617
618     fn join_rewrites(
619         &self,
620         context: &RewriteContext,
621         child_shape: Shape,
622         block_like_iter: impl Iterator<Item = bool>,
623     ) -> Option<String> {
624         let connector = if self.fits_single_line {
625             // Yay, we can put everything on one line.
626             Cow::from("")
627         } else {
628             // Use new lines.
629             if *context.force_one_line_chain.borrow() {
630                 return None;
631             }
632             child_shape.to_string_with_newline(context.config)
633         };
634
635         let mut rewrite_iter = self.rewrites.iter();
636         let mut result = rewrite_iter.next().unwrap().clone();
637         let children_iter = self.children.iter();
638         let iter = rewrite_iter.zip(block_like_iter).zip(children_iter);
639
640         for ((rewrite, prev_is_block_like), chain_item) in iter {
641             match chain_item.kind {
642                 ChainItemKind::Comment(_, CommentPosition::Back) => result.push(' '),
643                 ChainItemKind::Comment(_, CommentPosition::Top) => result.push_str(&connector),
644                 _ => {
645                     if !prev_is_block_like {
646                         result.push_str(&connector);
647                     }
648                 }
649             }
650             result.push_str(&rewrite);
651         }
652
653         Some(result)
654     }
655 }
656
657 // Formats a chain using block indent.
658 struct ChainFormatterBlock<'a> {
659     shared: ChainFormatterShared<'a>,
660     // For each rewrite, whether the corresponding item is block-like.
661     is_block_like: Vec<bool>,
662 }
663
664 impl<'a> ChainFormatterBlock<'a> {
665     fn new(chain: &'a Chain) -> ChainFormatterBlock<'a> {
666         ChainFormatterBlock {
667             shared: ChainFormatterShared::new(chain),
668             is_block_like: Vec::with_capacity(chain.children.len() + 1),
669         }
670     }
671 }
672
673 impl<'a> ChainFormatter for ChainFormatterBlock<'a> {
674     fn format_root(
675         &mut self,
676         parent: &ChainItem,
677         context: &RewriteContext,
678         shape: Shape,
679     ) -> Option<()> {
680         let mut root_rewrite: String = parent.rewrite(context, shape)?;
681
682         let mut root_ends_with_block = parent.kind.is_block_like(context, &root_rewrite);
683         let tab_width = context.config.tab_spaces().saturating_sub(shape.offset);
684
685         while root_rewrite.len() <= tab_width && !root_rewrite.contains('\n') {
686             let item = &self.shared.children[0];
687             if let ChainItemKind::Comment(..) = item.kind {
688                 break;
689             }
690             let shape = shape.offset_left(root_rewrite.len())?;
691             match &item.rewrite(context, shape) {
692                 Some(rewrite) => root_rewrite.push_str(rewrite),
693                 None => break,
694             }
695
696             root_ends_with_block = item.kind.is_block_like(context, &root_rewrite);
697
698             self.shared.children = &self.shared.children[1..];
699             if self.shared.children.is_empty() {
700                 break;
701             }
702         }
703         self.is_block_like.push(root_ends_with_block);
704         self.shared.rewrites.push(root_rewrite);
705         Some(())
706     }
707
708     fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape> {
709         Some(
710             if self.is_block_like[0] {
711                 shape.block_indent(0)
712             } else {
713                 shape.block_indent(context.config.tab_spaces())
714             }.with_max_width(context.config),
715         )
716     }
717
718     fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
719         for item in &self.shared.children[..self.shared.children.len() - 1] {
720             let rewrite = item.rewrite(context, child_shape)?;
721             self.is_block_like
722                 .push(item.kind.is_block_like(context, &rewrite));
723             self.shared.rewrites.push(rewrite);
724         }
725         Some(())
726     }
727
728     fn format_last_child(
729         &mut self,
730         context: &RewriteContext,
731         shape: Shape,
732         child_shape: Shape,
733     ) -> Option<()> {
734         self.shared
735             .format_last_child(true, context, shape, child_shape)
736     }
737
738     fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
739         self.shared
740             .join_rewrites(context, child_shape, self.is_block_like.iter().cloned())
741     }
742
743     fn pure_root(&mut self) -> Option<String> {
744         self.shared.pure_root()
745     }
746 }
747
748 // Format a chain using visual indent.
749 struct ChainFormatterVisual<'a> {
750     shared: ChainFormatterShared<'a>,
751     // The extra offset from the chain's shape to the position of the `.`
752     offset: usize,
753 }
754
755 impl<'a> ChainFormatterVisual<'a> {
756     fn new(chain: &'a Chain) -> ChainFormatterVisual<'a> {
757         ChainFormatterVisual {
758             shared: ChainFormatterShared::new(chain),
759             offset: 0,
760         }
761     }
762 }
763
764 impl<'a> ChainFormatter for ChainFormatterVisual<'a> {
765     fn format_root(
766         &mut self,
767         parent: &ChainItem,
768         context: &RewriteContext,
769         shape: Shape,
770     ) -> Option<()> {
771         let parent_shape = shape.visual_indent(0);
772         let mut root_rewrite = parent.rewrite(context, parent_shape)?;
773         let multiline = root_rewrite.contains('\n');
774         self.offset = if multiline {
775             last_line_width(&root_rewrite).saturating_sub(shape.used_width())
776         } else {
777             trimmed_last_line_width(&root_rewrite)
778         };
779
780         if !multiline || parent.kind.is_block_like(context, &root_rewrite) {
781             let item = &self.shared.children[0];
782             if let ChainItemKind::Comment(..) = item.kind {
783                 self.shared.rewrites.push(root_rewrite);
784                 return Some(());
785             }
786             let child_shape = parent_shape
787                 .visual_indent(self.offset)
788                 .sub_width(self.offset)?;
789             let rewrite = item.rewrite(context, child_shape)?;
790             match wrap_str(rewrite, context.config.max_width(), shape) {
791                 Some(rewrite) => root_rewrite.push_str(&rewrite),
792                 None => {
793                     // We couldn't fit in at the visual indent, try the last
794                     // indent.
795                     let rewrite = item.rewrite(context, parent_shape)?;
796                     root_rewrite.push_str(&rewrite);
797                     self.offset = 0;
798                 }
799             }
800
801             self.shared.children = &self.shared.children[1..];
802         }
803
804         self.shared.rewrites.push(root_rewrite);
805         Some(())
806     }
807
808     fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape> {
809         shape
810             .with_max_width(context.config)
811             .offset_left(self.offset)
812             .map(|s| s.visual_indent(0))
813     }
814
815     fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
816         for item in &self.shared.children[..self.shared.children.len() - 1] {
817             let rewrite = item.rewrite(context, child_shape)?;
818             self.shared.rewrites.push(rewrite);
819         }
820         Some(())
821     }
822
823     fn format_last_child(
824         &mut self,
825         context: &RewriteContext,
826         shape: Shape,
827         child_shape: Shape,
828     ) -> Option<()> {
829         self.shared
830             .format_last_child(false, context, shape, child_shape)
831     }
832
833     fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
834         self.shared
835             .join_rewrites(context, child_shape, iter::repeat(false))
836     }
837
838     fn pure_root(&mut self) -> Option<String> {
839         self.shared.pure_root()
840     }
841 }
842
843 // States whether an expression's last line exclusively consists of closing
844 // parens, braces, and brackets in its idiomatic formatting.
845 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
846     match expr.node {
847         ast::ExprKind::Mac(..)
848         | ast::ExprKind::Call(..)
849         | ast::ExprKind::MethodCall(..)
850         | ast::ExprKind::Struct(..)
851         | ast::ExprKind::While(..)
852         | ast::ExprKind::WhileLet(..)
853         | ast::ExprKind::If(..)
854         | ast::ExprKind::IfLet(..)
855         | ast::ExprKind::Block(..)
856         | ast::ExprKind::Loop(..)
857         | ast::ExprKind::ForLoop(..)
858         | ast::ExprKind::Match(..) => repr.contains('\n'),
859         ast::ExprKind::Paren(ref expr)
860         | ast::ExprKind::Binary(_, _, ref expr)
861         | ast::ExprKind::Index(_, ref expr)
862         | ast::ExprKind::Unary(_, ref expr)
863         | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
864         | ast::ExprKind::Try(ref expr)
865         | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
866         // This can only be a string lit
867         ast::ExprKind::Lit(_) => {
868             repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
869         }
870         _ => false,
871     }
872 }