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