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