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