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