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