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