]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
Fix most recenty nightly breakage due to removed await! support (#3722)
[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(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(ref subexpr) => Some(Self::convert_try(subexpr, context)),
400             _ => None,
401         }
402     }
403
404     fn convert_try(expr: &ast::Expr, context: &RewriteContext<'_>) -> ast::Expr {
405         match expr.node {
406             ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
407                 if let Some(subexpr) = convert_try_mac(mac, context) {
408                     subexpr
409                 } else {
410                     expr.clone()
411                 }
412             }
413             _ => expr.clone(),
414         }
415     }
416 }
417
418 impl Rewrite for Chain {
419     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
420         debug!("rewrite chain {:?} {:?}", self, shape);
421
422         let mut formatter = match context.config.indent_style() {
423             IndentStyle::Block => {
424                 Box::new(ChainFormatterBlock::new(self)) as Box<dyn ChainFormatter>
425             }
426             IndentStyle::Visual => {
427                 Box::new(ChainFormatterVisual::new(self)) as Box<dyn ChainFormatter>
428             }
429         };
430
431         formatter.format_root(&self.parent, context, shape)?;
432         if let Some(result) = formatter.pure_root() {
433             return wrap_str(result, context.config.max_width(), shape);
434         }
435
436         // Decide how to layout the rest of the chain.
437         let child_shape = formatter.child_shape(context, shape)?;
438
439         formatter.format_children(context, child_shape)?;
440         formatter.format_last_child(context, shape, child_shape)?;
441
442         let result = formatter.join_rewrites(context, child_shape)?;
443         wrap_str(result, context.config.max_width(), shape)
444     }
445 }
446
447 // There are a few types for formatting chains. This is because there is a lot
448 // in common between formatting with block vs visual indent, but they are
449 // different enough that branching on the indent all over the place gets ugly.
450 // Anything that can format a chain is a ChainFormatter.
451 trait ChainFormatter {
452     // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
453     // Root is the parent plus any other chain items placed on the first line to
454     // avoid an orphan. E.g.,
455     // ```text
456     // foo.bar
457     //     .baz()
458     // ```
459     // If `bar` were not part of the root, then foo would be orphaned and 'float'.
460     fn format_root(
461         &mut self,
462         parent: &ChainItem,
463         context: &RewriteContext<'_>,
464         shape: Shape,
465     ) -> Option<()>;
466     fn child_shape(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<Shape>;
467     fn format_children(&mut self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<()>;
468     fn format_last_child(
469         &mut self,
470         context: &RewriteContext<'_>,
471         shape: Shape,
472         child_shape: Shape,
473     ) -> Option<()>;
474     fn join_rewrites(&self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<String>;
475     // Returns `Some` if the chain is only a root, None otherwise.
476     fn pure_root(&mut self) -> Option<String>;
477 }
478
479 // Data and behaviour that is shared by both chain formatters. The concrete
480 // formatters can delegate much behaviour to `ChainFormatterShared`.
481 struct ChainFormatterShared<'a> {
482     // The current working set of child items.
483     children: &'a [ChainItem],
484     // The current rewrites of items (includes trailing `?`s, but not any way to
485     // connect the rewrites together).
486     rewrites: Vec<String>,
487     // Whether the chain can fit on one line.
488     fits_single_line: bool,
489     // The number of children in the chain. This is not equal to `self.children.len()`
490     // because `self.children` will change size as we process the chain.
491     child_count: usize,
492 }
493
494 impl<'a> ChainFormatterShared<'a> {
495     fn new(chain: &'a Chain) -> ChainFormatterShared<'a> {
496         ChainFormatterShared {
497             children: &chain.children,
498             rewrites: Vec::with_capacity(chain.children.len() + 1),
499             fits_single_line: false,
500             child_count: chain.children.len(),
501         }
502     }
503
504     fn pure_root(&mut self) -> Option<String> {
505         if self.children.is_empty() {
506             assert_eq!(self.rewrites.len(), 1);
507             Some(self.rewrites.pop().unwrap())
508         } else {
509             None
510         }
511     }
512
513     // Rewrite the last child. The last child of a chain requires special treatment. We need to
514     // know whether 'overflowing' the last child make a better formatting:
515     //
516     // A chain with overflowing the last child:
517     // ```text
518     // parent.child1.child2.last_child(
519     //     a,
520     //     b,
521     //     c,
522     // )
523     // ```
524     //
525     // A chain without overflowing the last child (in vertical layout):
526     // ```text
527     // parent
528     //     .child1
529     //     .child2
530     //     .last_child(a, b, c)
531     // ```
532     //
533     // In particular, overflowing is effective when the last child is a method with a multi-lined
534     // block-like argument (e.g., closure):
535     // ```text
536     // parent.child1.child2.last_child(|a, b, c| {
537     //     let x = foo(a, b, c);
538     //     let y = bar(a, b, c);
539     //
540     //     // ...
541     //
542     //     result
543     // })
544     // ```
545     fn format_last_child(
546         &mut self,
547         may_extend: bool,
548         context: &RewriteContext<'_>,
549         shape: Shape,
550         child_shape: Shape,
551     ) -> Option<()> {
552         let last = self.children.last()?;
553         let extendable = may_extend && last_line_extendable(&self.rewrites[0]);
554         let prev_last_line_width = last_line_width(&self.rewrites[0]);
555
556         // Total of all items excluding the last.
557         let almost_total = if extendable {
558             prev_last_line_width
559         } else {
560             self.rewrites
561                 .iter()
562                 .map(|rw| utils::unicode_str_width(&rw))
563                 .sum()
564         } + last.tries;
565         let one_line_budget = if self.child_count == 1 {
566             shape.width
567         } else {
568             min(shape.width, context.config.width_heuristics().chain_width)
569         }
570         .saturating_sub(almost_total);
571
572         let all_in_one_line = !self.children.iter().any(ChainItem::is_comment)
573             && self.rewrites.iter().all(|s| !s.contains('\n'))
574             && one_line_budget > 0;
575         let last_shape = if all_in_one_line {
576             shape.sub_width(last.tries)?
577         } else if extendable {
578             child_shape.sub_width(last.tries)?
579         } else {
580             child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?
581         };
582
583         let mut last_subexpr_str = None;
584         if all_in_one_line || extendable {
585             // First we try to 'overflow' the last child and see if it looks better than using
586             // vertical layout.
587             let one_line_shape = if context.use_block_indent() {
588                 last_shape.offset_left(almost_total)
589             } else {
590                 last_shape
591                     .visual_indent(almost_total)
592                     .sub_width(almost_total)
593             };
594
595             if let Some(one_line_shape) = one_line_shape {
596                 if let Some(rw) = last.rewrite(context, one_line_shape) {
597                     // We allow overflowing here only if both of the following conditions match:
598                     // 1. The entire chain fits in a single line except the last child.
599                     // 2. `last_child_str.lines().count() >= 5`.
600                     let line_count = rw.lines().count();
601                     let could_fit_single_line = first_line_width(&rw) <= one_line_budget;
602                     if could_fit_single_line && line_count >= 5 {
603                         last_subexpr_str = Some(rw);
604                         self.fits_single_line = all_in_one_line;
605                     } else {
606                         // We could not know whether overflowing is better than using vertical
607                         // layout, just by looking at the overflowed rewrite. Now we rewrite the
608                         // last child on its own line, and compare two rewrites to choose which is
609                         // better.
610                         let last_shape = child_shape
611                             .sub_width(shape.rhs_overhead(context.config) + last.tries)?;
612                         match last.rewrite(context, last_shape) {
613                             Some(ref new_rw) if !could_fit_single_line => {
614                                 last_subexpr_str = Some(new_rw.clone());
615                             }
616                             Some(ref new_rw) if new_rw.lines().count() >= line_count => {
617                                 last_subexpr_str = Some(rw);
618                                 self.fits_single_line = could_fit_single_line && all_in_one_line;
619                             }
620                             new_rw @ Some(..) => {
621                                 last_subexpr_str = new_rw;
622                             }
623                             _ => {
624                                 last_subexpr_str = Some(rw);
625                                 self.fits_single_line = could_fit_single_line && all_in_one_line;
626                             }
627                         }
628                     }
629                 }
630             }
631         }
632
633         let last_shape = if context.use_block_indent() {
634             last_shape
635         } else {
636             child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?
637         };
638
639         last_subexpr_str = last_subexpr_str.or_else(|| last.rewrite(context, last_shape));
640         self.rewrites.push(last_subexpr_str?);
641         Some(())
642     }
643
644     fn join_rewrites(&self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<String> {
645         let connector = if self.fits_single_line {
646             // Yay, we can put everything on one line.
647             Cow::from("")
648         } else {
649             // Use new lines.
650             if *context.force_one_line_chain.borrow() {
651                 return None;
652             }
653             child_shape.to_string_with_newline(context.config)
654         };
655
656         let mut rewrite_iter = self.rewrites.iter();
657         let mut result = rewrite_iter.next().unwrap().clone();
658         let children_iter = self.children.iter();
659         let iter = rewrite_iter.zip(children_iter);
660
661         for (rewrite, chain_item) in iter {
662             match chain_item.kind {
663                 ChainItemKind::Comment(_, CommentPosition::Back) => result.push(' '),
664                 ChainItemKind::Comment(_, CommentPosition::Top) => result.push_str(&connector),
665                 _ => result.push_str(&connector),
666             }
667             result.push_str(&rewrite);
668         }
669
670         Some(result)
671     }
672 }
673
674 // Formats a chain using block indent.
675 struct ChainFormatterBlock<'a> {
676     shared: ChainFormatterShared<'a>,
677     root_ends_with_block: bool,
678 }
679
680 impl<'a> ChainFormatterBlock<'a> {
681     fn new(chain: &'a Chain) -> ChainFormatterBlock<'a> {
682         ChainFormatterBlock {
683             shared: ChainFormatterShared::new(chain),
684             root_ends_with_block: false,
685         }
686     }
687 }
688
689 impl<'a> ChainFormatter for ChainFormatterBlock<'a> {
690     fn format_root(
691         &mut self,
692         parent: &ChainItem,
693         context: &RewriteContext<'_>,
694         shape: Shape,
695     ) -> Option<()> {
696         let mut root_rewrite: String = parent.rewrite(context, shape)?;
697
698         let mut root_ends_with_block = parent.kind.is_block_like(context, &root_rewrite);
699         let tab_width = context.config.tab_spaces().saturating_sub(shape.offset);
700
701         while root_rewrite.len() <= tab_width && !root_rewrite.contains('\n') {
702             let item = &self.shared.children[0];
703             if let ChainItemKind::Comment(..) = item.kind {
704                 break;
705             }
706             let shape = shape.offset_left(root_rewrite.len())?;
707             match &item.rewrite(context, shape) {
708                 Some(rewrite) => root_rewrite.push_str(rewrite),
709                 None => break,
710             }
711
712             root_ends_with_block = last_line_extendable(&root_rewrite);
713
714             self.shared.children = &self.shared.children[1..];
715             if self.shared.children.is_empty() {
716                 break;
717             }
718         }
719         self.shared.rewrites.push(root_rewrite);
720         self.root_ends_with_block = root_ends_with_block;
721         Some(())
722     }
723
724     fn child_shape(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<Shape> {
725         Some(
726             if self.root_ends_with_block {
727                 shape.block_indent(0)
728             } else {
729                 shape.block_indent(context.config.tab_spaces())
730             }
731             .with_max_width(context.config),
732         )
733     }
734
735     fn format_children(&mut self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<()> {
736         for item in &self.shared.children[..self.shared.children.len() - 1] {
737             let rewrite = item.rewrite(context, child_shape)?;
738             self.shared.rewrites.push(rewrite);
739         }
740         Some(())
741     }
742
743     fn format_last_child(
744         &mut self,
745         context: &RewriteContext<'_>,
746         shape: Shape,
747         child_shape: Shape,
748     ) -> Option<()> {
749         self.shared
750             .format_last_child(true, context, shape, child_shape)
751     }
752
753     fn join_rewrites(&self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<String> {
754         self.shared.join_rewrites(context, child_shape)
755     }
756
757     fn pure_root(&mut self) -> Option<String> {
758         self.shared.pure_root()
759     }
760 }
761
762 // Format a chain using visual indent.
763 struct ChainFormatterVisual<'a> {
764     shared: ChainFormatterShared<'a>,
765     // The extra offset from the chain's shape to the position of the `.`
766     offset: usize,
767 }
768
769 impl<'a> ChainFormatterVisual<'a> {
770     fn new(chain: &'a Chain) -> ChainFormatterVisual<'a> {
771         ChainFormatterVisual {
772             shared: ChainFormatterShared::new(chain),
773             offset: 0,
774         }
775     }
776 }
777
778 impl<'a> ChainFormatter for ChainFormatterVisual<'a> {
779     fn format_root(
780         &mut self,
781         parent: &ChainItem,
782         context: &RewriteContext<'_>,
783         shape: Shape,
784     ) -> Option<()> {
785         let parent_shape = shape.visual_indent(0);
786         let mut root_rewrite = parent.rewrite(context, parent_shape)?;
787         let multiline = root_rewrite.contains('\n');
788         self.offset = if multiline {
789             last_line_width(&root_rewrite).saturating_sub(shape.used_width())
790         } else {
791             trimmed_last_line_width(&root_rewrite)
792         };
793
794         if !multiline || parent.kind.is_block_like(context, &root_rewrite) {
795             let item = &self.shared.children[0];
796             if let ChainItemKind::Comment(..) = item.kind {
797                 self.shared.rewrites.push(root_rewrite);
798                 return Some(());
799             }
800             let child_shape = parent_shape
801                 .visual_indent(self.offset)
802                 .sub_width(self.offset)?;
803             let rewrite = item.rewrite(context, child_shape)?;
804             match wrap_str(rewrite, context.config.max_width(), shape) {
805                 Some(rewrite) => root_rewrite.push_str(&rewrite),
806                 None => {
807                     // We couldn't fit in at the visual indent, try the last
808                     // indent.
809                     let rewrite = item.rewrite(context, parent_shape)?;
810                     root_rewrite.push_str(&rewrite);
811                     self.offset = 0;
812                 }
813             }
814
815             self.shared.children = &self.shared.children[1..];
816         }
817
818         self.shared.rewrites.push(root_rewrite);
819         Some(())
820     }
821
822     fn child_shape(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<Shape> {
823         shape
824             .with_max_width(context.config)
825             .offset_left(self.offset)
826             .map(|s| s.visual_indent(0))
827     }
828
829     fn format_children(&mut self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<()> {
830         for item in &self.shared.children[..self.shared.children.len() - 1] {
831             let rewrite = item.rewrite(context, child_shape)?;
832             self.shared.rewrites.push(rewrite);
833         }
834         Some(())
835     }
836
837     fn format_last_child(
838         &mut self,
839         context: &RewriteContext<'_>,
840         shape: Shape,
841         child_shape: Shape,
842     ) -> Option<()> {
843         self.shared
844             .format_last_child(false, context, shape, child_shape)
845     }
846
847     fn join_rewrites(&self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<String> {
848         self.shared.join_rewrites(context, child_shape)
849     }
850
851     fn pure_root(&mut self) -> Option<String> {
852         self.shared.pure_root()
853     }
854 }
855
856 /// Removes try operators (`?`s) that appear in the given string. If removing
857 /// them leaves an empty line, remove that line as well unless it is the first
858 /// line (we need the first newline for detecting pre/post comment).
859 fn trim_tries(s: &str) -> String {
860     let mut result = String::with_capacity(s.len());
861     let mut line_buffer = String::with_capacity(s.len());
862     for (kind, rich_char) in CharClasses::new(s.chars()) {
863         match rich_char.get_char() {
864             '\n' => {
865                 if result.is_empty() || !line_buffer.trim().is_empty() {
866                     result.push_str(&line_buffer);
867                     result.push('\n')
868                 }
869                 line_buffer.clear();
870             }
871             '?' if kind == FullCodeCharKind::Normal => continue,
872             c => line_buffer.push(c),
873         }
874     }
875     if !line_buffer.trim().is_empty() {
876         result.push_str(&line_buffer);
877     }
878     result
879 }