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