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