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