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