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