]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
Use trim_tries to extract pre-comments over simple trim_matches
[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_post_comment, extract_pre_comment, get_comment_end};
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, trimmed_last_line_width,
78     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!(".{}", ident.name),
194             ChainItemKind::TupleField(ident, nested) => {
195                 format!("{}.{}", if nested { " " } else { "" }, ident.name)
196             }
197             ChainItemKind::Comment(ref comment, _) => {
198                 rewrite_comment(comment, false, shape, context.config)?
199             }
200         };
201         Some(format!("{}{}", rewrite, "?".repeat(self.tries)))
202     }
203 }
204
205 impl ChainItem {
206     fn new(context: &RewriteContext, expr: &ast::Expr, tries: usize) -> ChainItem {
207         let (kind, span) = ChainItemKind::from_ast(context, expr);
208         ChainItem { kind, tries, span }
209     }
210
211     fn comment(span: Span, comment: String, pos: CommentPosition) -> ChainItem {
212         ChainItem {
213             kind: ChainItemKind::Comment(comment, pos),
214             tries: 0,
215             span,
216         }
217     }
218
219     fn is_comment(&self) -> bool {
220         match self.kind {
221             ChainItemKind::Comment(..) => true,
222             _ => false,
223         }
224     }
225
226     fn rewrite_method_call(
227         method_name: ast::Ident,
228         types: &[ast::GenericArg],
229         args: &[ptr::P<ast::Expr>],
230         span: Span,
231         context: &RewriteContext,
232         shape: Shape,
233     ) -> Option<String> {
234         let type_str = if types.is_empty() {
235             String::new()
236         } else {
237             let type_list = types
238                 .iter()
239                 .map(|ty| ty.rewrite(context, shape))
240                 .collect::<Option<Vec<_>>>()?;
241
242             format!("::<{}>", type_list.join(", "))
243         };
244         let callee_str = format!(".{}{}", method_name, type_str);
245         rewrite_call(context, &callee_str, &args[1..], span, shape)
246     }
247 }
248
249 #[derive(Debug)]
250 struct Chain {
251     parent: ChainItem,
252     children: Vec<ChainItem>,
253 }
254
255 impl Chain {
256     fn from_ast(expr: &ast::Expr, context: &RewriteContext) -> Chain {
257         let subexpr_list = Self::make_subexpr_list(expr, context);
258
259         // Un-parse the expression tree into ChainItems
260         let mut rev_children = vec![];
261         let mut sub_tries = 0;
262         for subexpr in &subexpr_list {
263             match subexpr.node {
264                 ast::ExprKind::Try(_) => sub_tries += 1,
265                 _ => {
266                     rev_children.push(ChainItem::new(context, subexpr, sub_tries));
267                     sub_tries = 0;
268                 }
269             }
270         }
271
272         fn is_tries(s: &str) -> bool {
273             s.chars().all(|c| c == '?')
274         }
275
276         fn handle_post_comment(
277             post_comment_span: Span,
278             post_comment_snippet: &str,
279             prev_span_end: &mut BytePos,
280             children: &mut Vec<ChainItem>,
281         ) {
282             let white_spaces: &[_] = &[' ', '\t'];
283             if post_comment_snippet
284                 .trim_matches(white_spaces)
285                 .starts_with('\n')
286             {
287                 // No post comment.
288                 return;
289             }
290             // HACK: Treat `?`s as separators.
291             let trimmed_snippet = post_comment_snippet.trim_matches('?');
292             let comment_end = get_comment_end(trimmed_snippet, "?", "", false);
293             let maybe_post_comment = extract_post_comment(trimmed_snippet, comment_end, "?")
294                 .and_then(|comment| {
295                     if comment.is_empty() {
296                         None
297                     } else {
298                         Some((comment, comment_end))
299                     }
300                 });
301
302             if let Some((post_comment, comment_end)) = maybe_post_comment {
303                 children.push(ChainItem::comment(
304                     post_comment_span,
305                     post_comment,
306                     CommentPosition::Back,
307                 ));
308                 *prev_span_end = *prev_span_end + BytePos(comment_end as u32);
309             }
310         }
311
312         let parent = rev_children.pop().unwrap();
313         let mut children = vec![];
314         let mut prev_span_end = parent.span.hi();
315         let mut iter = rev_children.into_iter().rev().peekable();
316         if let Some(first_chain_item) = iter.peek() {
317             let comment_span = mk_sp(prev_span_end, first_chain_item.span.lo());
318             let comment_snippet = context.snippet(comment_span);
319             if !is_tries(comment_snippet.trim()) {
320                 handle_post_comment(
321                     comment_span,
322                     comment_snippet,
323                     &mut prev_span_end,
324                     &mut children,
325                 );
326             }
327         }
328         while let Some(chain_item) = iter.next() {
329             let comment_snippet = context.snippet(chain_item.span);
330             // FIXME: Figure out the way to get a correct span when converting `try!` to `?`.
331             let handle_comment =
332                 !(context.config.use_try_shorthand() || is_tries(comment_snippet.trim()));
333
334             // Pre-comment
335             if handle_comment {
336                 let pre_comment_span = mk_sp(prev_span_end, chain_item.span.lo());
337                 let pre_comment_snippet = trim_tries(context.snippet(pre_comment_span));
338                 let (pre_comment, _) = extract_pre_comment(&pre_comment_snippet);
339                 match pre_comment {
340                     Some(ref comment) if !comment.is_empty() => {
341                         children.push(ChainItem::comment(
342                             pre_comment_span,
343                             comment.to_owned(),
344                             CommentPosition::Top,
345                         ));
346                     }
347                     _ => (),
348                 }
349             }
350
351             prev_span_end = chain_item.span.hi();
352             children.push(chain_item);
353
354             // Post-comment
355             if !handle_comment || iter.peek().is_none() {
356                 continue;
357             }
358
359             let next_lo = iter.peek().unwrap().span.lo();
360             let post_comment_span = mk_sp(prev_span_end, next_lo);
361             let post_comment_snippet = context.snippet(post_comment_span);
362             handle_post_comment(
363                 post_comment_span,
364                 post_comment_snippet,
365                 &mut prev_span_end,
366                 &mut children,
367             );
368         }
369
370         Chain { parent, children }
371     }
372
373     // Returns a Vec of the prefixes of the chain.
374     // E.g., for input `a.b.c` we return [`a.b.c`, `a.b`, 'a']
375     fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> Vec<ast::Expr> {
376         let mut subexpr_list = vec![expr.clone()];
377
378         while let Some(subexpr) = Self::pop_expr_chain(subexpr_list.last().unwrap(), context) {
379             subexpr_list.push(subexpr.clone());
380         }
381
382         subexpr_list
383     }
384
385     // Returns the expression's subexpression, if it exists. When the subexpr
386     // is a try! macro, we'll convert it to shorthand when the option is set.
387     fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
388         match expr.node {
389             ast::ExprKind::MethodCall(_, ref expressions) => {
390                 Some(Self::convert_try(&expressions[0], context))
391             }
392             ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) => {
393                 Some(Self::convert_try(subexpr, context))
394             }
395             _ => None,
396         }
397     }
398
399     fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
400         match expr.node {
401             ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
402                 if let Some(subexpr) = convert_try_mac(mac, context) {
403                     subexpr
404                 } else {
405                     expr.clone()
406                 }
407             }
408             _ => expr.clone(),
409         }
410     }
411 }
412
413 impl Rewrite for Chain {
414     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
415         debug!("rewrite chain {:?} {:?}", self, shape);
416
417         let mut formatter = match context.config.indent_style() {
418             IndentStyle::Block => Box::new(ChainFormatterBlock::new(self)) as Box<ChainFormatter>,
419             IndentStyle::Visual => Box::new(ChainFormatterVisual::new(self)) as Box<ChainFormatter>,
420         };
421
422         formatter.format_root(&self.parent, context, shape)?;
423         if let Some(result) = formatter.pure_root() {
424             return wrap_str(result, context.config.max_width(), shape);
425         }
426
427         // Decide how to layout the rest of the chain.
428         let child_shape = formatter.child_shape(context, shape)?;
429
430         formatter.format_children(context, child_shape)?;
431         formatter.format_last_child(context, shape, child_shape)?;
432
433         let result = formatter.join_rewrites(context, child_shape)?;
434         wrap_str(result, context.config.max_width(), shape)
435     }
436 }
437
438 // There are a few types for formatting chains. This is because there is a lot
439 // in common between formatting with block vs visual indent, but they are
440 // different enough that branching on the indent all over the place gets ugly.
441 // Anything that can format a chain is a ChainFormatter.
442 trait ChainFormatter {
443     // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
444     // Root is the parent plus any other chain items placed on the first line to
445     // avoid an orphan. E.g.,
446     // ```
447     // foo.bar
448     //     .baz()
449     // ```
450     // If `bar` were not part of the root, then foo would be orphaned and 'float'.
451     fn format_root(
452         &mut self,
453         parent: &ChainItem,
454         context: &RewriteContext,
455         shape: Shape,
456     ) -> Option<()>;
457     fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape>;
458     fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()>;
459     fn format_last_child(
460         &mut self,
461         context: &RewriteContext,
462         shape: Shape,
463         child_shape: Shape,
464     ) -> Option<()>;
465     fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String>;
466     // Returns `Some` if the chain is only a root, None otherwise.
467     fn pure_root(&mut self) -> Option<String>;
468 }
469
470 // Data and behaviour that is shared by both chain formatters. The concrete
471 // formatters can delegate much behaviour to `ChainFormatterShared`.
472 struct ChainFormatterShared<'a> {
473     // The current working set of child items.
474     children: &'a [ChainItem],
475     // The current rewrites of items (includes trailing `?`s, but not any way to
476     // connect the rewrites together).
477     rewrites: Vec<String>,
478     // Whether the chain can fit on one line.
479     fits_single_line: bool,
480     // The number of children in the chain. This is not equal to `self.children.len()`
481     // because `self.children` will change size as we process the chain.
482     child_count: usize,
483 }
484
485 impl<'a> ChainFormatterShared<'a> {
486     fn new(chain: &'a Chain) -> ChainFormatterShared<'a> {
487         ChainFormatterShared {
488             children: &chain.children,
489             rewrites: Vec::with_capacity(chain.children.len() + 1),
490             fits_single_line: false,
491             child_count: chain.children.len(),
492         }
493     }
494
495     fn pure_root(&mut self) -> Option<String> {
496         if self.children.is_empty() {
497             assert_eq!(self.rewrites.len(), 1);
498             Some(self.rewrites.pop().unwrap())
499         } else {
500             None
501         }
502     }
503
504     // Rewrite the last child. The last child of a chain requires special treatment. We need to
505     // know whether 'overflowing' the last child make a better formatting:
506     //
507     // A chain with overflowing the last child:
508     // ```
509     // parent.child1.child2.last_child(
510     //     a,
511     //     b,
512     //     c,
513     // )
514     // ```
515     //
516     // A chain without overflowing the last child (in vertical layout):
517     // ```
518     // parent
519     //     .child1
520     //     .child2
521     //     .last_child(a, b, c)
522     // ```
523     //
524     // In particular, overflowing is effective when the last child is a method with a multi-lined
525     // block-like argument (e.g. closure):
526     // ```
527     // parent.child1.child2.last_child(|a, b, c| {
528     //     let x = foo(a, b, c);
529     //     let y = bar(a, b, c);
530     //
531     //     // ...
532     //
533     //     result
534     // })
535     // ```
536     fn format_last_child(
537         &mut self,
538         may_extend: bool,
539         context: &RewriteContext,
540         shape: Shape,
541         child_shape: Shape,
542     ) -> Option<()> {
543         let last = self.children.last()?;
544         let extendable = may_extend && last_line_extendable(&self.rewrites[0]);
545         let prev_last_line_width = last_line_width(&self.rewrites[0]);
546
547         // Total of all items excluding the last.
548         let almost_total = if extendable {
549             prev_last_line_width
550         } else {
551             self.rewrites.iter().fold(0, |a, b| a + b.len())
552         } + last.tries;
553         let one_line_budget = if self.child_count == 1 {
554             shape.width
555         } else {
556             min(shape.width, context.config.width_heuristics().chain_width)
557         }.saturating_sub(almost_total);
558
559         let all_in_one_line = !self.children.iter().any(ChainItem::is_comment)
560             && self.rewrites.iter().all(|s| !s.contains('\n'))
561             && one_line_budget > 0;
562         let last_shape = if all_in_one_line {
563             shape.sub_width(last.tries)?
564         } else if extendable {
565             child_shape.sub_width(last.tries)?
566         } else {
567             child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?
568         };
569
570         let mut last_subexpr_str = None;
571         if all_in_one_line || extendable {
572             // First we try to 'overflow' the last child and see if it looks better than using
573             // vertical layout.
574             if let Some(one_line_shape) = last_shape.offset_left(almost_total) {
575                 if let Some(rw) = last.rewrite(context, one_line_shape) {
576                     // We allow overflowing here only if both of the following conditions match:
577                     // 1. The entire chain fits in a single line except the last child.
578                     // 2. `last_child_str.lines().count() >= 5`.
579                     let line_count = rw.lines().count();
580                     let could_fit_single_line = first_line_width(&rw) <= one_line_budget;
581                     if could_fit_single_line && line_count >= 5 {
582                         last_subexpr_str = Some(rw);
583                         self.fits_single_line = all_in_one_line;
584                     } else {
585                         // We could not know whether overflowing is better than using vertical
586                         // layout, just by looking at the overflowed rewrite. Now we rewrite the
587                         // last child on its own line, and compare two rewrites to choose which is
588                         // better.
589                         let last_shape = child_shape
590                             .sub_width(shape.rhs_overhead(context.config) + last.tries)?;
591                         match last.rewrite(context, last_shape) {
592                             Some(ref new_rw) if !could_fit_single_line => {
593                                 last_subexpr_str = Some(new_rw.clone());
594                             }
595                             Some(ref new_rw) if new_rw.lines().count() >= line_count => {
596                                 last_subexpr_str = Some(rw);
597                                 self.fits_single_line = could_fit_single_line && all_in_one_line;
598                             }
599                             new_rw @ Some(..) => {
600                                 last_subexpr_str = new_rw;
601                             }
602                             _ => {
603                                 last_subexpr_str = Some(rw);
604                                 self.fits_single_line = could_fit_single_line && all_in_one_line;
605                             }
606                         }
607                     }
608                 }
609             }
610         }
611
612         last_subexpr_str = last_subexpr_str.or_else(|| last.rewrite(context, last_shape));
613         self.rewrites.push(last_subexpr_str?);
614         Some(())
615     }
616
617     fn join_rewrites(
618         &self,
619         context: &RewriteContext,
620         child_shape: Shape,
621         block_like_iter: impl Iterator<Item = bool>,
622     ) -> Option<String> {
623         let connector = if self.fits_single_line {
624             // Yay, we can put everything on one line.
625             Cow::from("")
626         } else {
627             // Use new lines.
628             if *context.force_one_line_chain.borrow() {
629                 return None;
630             }
631             child_shape.to_string_with_newline(context.config)
632         };
633
634         let mut rewrite_iter = self.rewrites.iter();
635         let mut result = rewrite_iter.next().unwrap().clone();
636         let children_iter = self.children.iter();
637         let iter = rewrite_iter.zip(block_like_iter).zip(children_iter);
638
639         for ((rewrite, prev_is_block_like), chain_item) in iter {
640             match chain_item.kind {
641                 ChainItemKind::Comment(_, CommentPosition::Back) => result.push(' '),
642                 ChainItemKind::Comment(_, CommentPosition::Top) => result.push_str(&connector),
643                 _ => {
644                     if !prev_is_block_like {
645                         result.push_str(&connector);
646                     }
647                 }
648             }
649             result.push_str(&rewrite);
650         }
651
652         Some(result)
653     }
654 }
655
656 // Formats a chain using block indent.
657 struct ChainFormatterBlock<'a> {
658     shared: ChainFormatterShared<'a>,
659     // For each rewrite, whether the corresponding item is block-like.
660     is_block_like: Vec<bool>,
661 }
662
663 impl<'a> ChainFormatterBlock<'a> {
664     fn new(chain: &'a Chain) -> ChainFormatterBlock<'a> {
665         ChainFormatterBlock {
666             shared: ChainFormatterShared::new(chain),
667             is_block_like: Vec::with_capacity(chain.children.len() + 1),
668         }
669     }
670 }
671
672 impl<'a> ChainFormatter for ChainFormatterBlock<'a> {
673     fn format_root(
674         &mut self,
675         parent: &ChainItem,
676         context: &RewriteContext,
677         shape: Shape,
678     ) -> Option<()> {
679         let mut root_rewrite: String = parent.rewrite(context, shape)?;
680
681         let mut root_ends_with_block = parent.kind.is_block_like(context, &root_rewrite);
682         let tab_width = context.config.tab_spaces().saturating_sub(shape.offset);
683
684         while root_rewrite.len() <= tab_width && !root_rewrite.contains('\n') {
685             let item = &self.shared.children[0];
686             if let ChainItemKind::Comment(..) = item.kind {
687                 break;
688             }
689             let shape = shape.offset_left(root_rewrite.len())?;
690             match &item.rewrite(context, shape) {
691                 Some(rewrite) => root_rewrite.push_str(rewrite),
692                 None => break,
693             }
694
695             root_ends_with_block = item.kind.is_block_like(context, &root_rewrite);
696
697             self.shared.children = &self.shared.children[1..];
698             if self.shared.children.is_empty() {
699                 break;
700             }
701         }
702         self.is_block_like.push(root_ends_with_block);
703         self.shared.rewrites.push(root_rewrite);
704         Some(())
705     }
706
707     fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape> {
708         Some(
709             if self.is_block_like[0] {
710                 shape.block_indent(0)
711             } else {
712                 shape.block_indent(context.config.tab_spaces())
713             }.with_max_width(context.config),
714         )
715     }
716
717     fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
718         for item in &self.shared.children[..self.shared.children.len() - 1] {
719             let rewrite = item.rewrite(context, child_shape)?;
720             self.is_block_like
721                 .push(item.kind.is_block_like(context, &rewrite));
722             self.shared.rewrites.push(rewrite);
723         }
724         Some(())
725     }
726
727     fn format_last_child(
728         &mut self,
729         context: &RewriteContext,
730         shape: Shape,
731         child_shape: Shape,
732     ) -> Option<()> {
733         self.shared
734             .format_last_child(true, context, shape, child_shape)
735     }
736
737     fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
738         self.shared
739             .join_rewrites(context, child_shape, self.is_block_like.iter().cloned())
740     }
741
742     fn pure_root(&mut self) -> Option<String> {
743         self.shared.pure_root()
744     }
745 }
746
747 // Format a chain using visual indent.
748 struct ChainFormatterVisual<'a> {
749     shared: ChainFormatterShared<'a>,
750     // The extra offset from the chain's shape to the position of the `.`
751     offset: usize,
752 }
753
754 impl<'a> ChainFormatterVisual<'a> {
755     fn new(chain: &'a Chain) -> ChainFormatterVisual<'a> {
756         ChainFormatterVisual {
757             shared: ChainFormatterShared::new(chain),
758             offset: 0,
759         }
760     }
761 }
762
763 impl<'a> ChainFormatter for ChainFormatterVisual<'a> {
764     fn format_root(
765         &mut self,
766         parent: &ChainItem,
767         context: &RewriteContext,
768         shape: Shape,
769     ) -> Option<()> {
770         let parent_shape = shape.visual_indent(0);
771         let mut root_rewrite = parent.rewrite(context, parent_shape)?;
772         let multiline = root_rewrite.contains('\n');
773         self.offset = if multiline {
774             last_line_width(&root_rewrite).saturating_sub(shape.used_width())
775         } else {
776             trimmed_last_line_width(&root_rewrite)
777         };
778
779         if !multiline || parent.kind.is_block_like(context, &root_rewrite) {
780             let item = &self.shared.children[0];
781             if let ChainItemKind::Comment(..) = item.kind {
782                 self.shared.rewrites.push(root_rewrite);
783                 return Some(());
784             }
785             let child_shape = parent_shape
786                 .visual_indent(self.offset)
787                 .sub_width(self.offset)?;
788             let rewrite = item.rewrite(context, child_shape)?;
789             match wrap_str(rewrite, context.config.max_width(), shape) {
790                 Some(rewrite) => root_rewrite.push_str(&rewrite),
791                 None => {
792                     // We couldn't fit in at the visual indent, try the last
793                     // indent.
794                     let rewrite = item.rewrite(context, parent_shape)?;
795                     root_rewrite.push_str(&rewrite);
796                     self.offset = 0;
797                 }
798             }
799
800             self.shared.children = &self.shared.children[1..];
801         }
802
803         self.shared.rewrites.push(root_rewrite);
804         Some(())
805     }
806
807     fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape> {
808         shape
809             .with_max_width(context.config)
810             .offset_left(self.offset)
811             .map(|s| s.visual_indent(0))
812     }
813
814     fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
815         for item in &self.shared.children[..self.shared.children.len() - 1] {
816             let rewrite = item.rewrite(context, child_shape)?;
817             self.shared.rewrites.push(rewrite);
818         }
819         Some(())
820     }
821
822     fn format_last_child(
823         &mut self,
824         context: &RewriteContext,
825         shape: Shape,
826         child_shape: Shape,
827     ) -> Option<()> {
828         self.shared
829             .format_last_child(false, context, shape, child_shape)
830     }
831
832     fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
833         self.shared
834             .join_rewrites(context, child_shape, iter::repeat(false))
835     }
836
837     fn pure_root(&mut self) -> Option<String> {
838         self.shared.pure_root()
839     }
840 }
841
842 // States whether an expression's last line exclusively consists of closing
843 // parens, braces, and brackets in its idiomatic formatting.
844 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
845     match expr.node {
846         ast::ExprKind::Mac(..)
847         | ast::ExprKind::Call(..)
848         | ast::ExprKind::MethodCall(..)
849         | ast::ExprKind::Struct(..)
850         | ast::ExprKind::While(..)
851         | ast::ExprKind::WhileLet(..)
852         | ast::ExprKind::If(..)
853         | ast::ExprKind::IfLet(..)
854         | ast::ExprKind::Block(..)
855         | ast::ExprKind::Loop(..)
856         | ast::ExprKind::ForLoop(..)
857         | ast::ExprKind::Match(..) => repr.contains('\n'),
858         ast::ExprKind::Paren(ref expr)
859         | ast::ExprKind::Binary(_, _, ref expr)
860         | ast::ExprKind::Index(_, ref expr)
861         | ast::ExprKind::Unary(_, ref expr)
862         | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
863         | ast::ExprKind::Try(ref expr)
864         | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
865         // This can only be a string lit
866         ast::ExprKind::Lit(_) => {
867             repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
868         }
869         _ => false,
870     }
871 }
872
873 /// Remove try operators (`?`s) that appear in the given string. If removing
874 /// them leaves an empty line, remove that line as well unless it is the first
875 /// line (we need the first newline for detecting pre/post comment).
876 fn trim_tries(s: &str) -> String {
877     let mut result = String::with_capacity(s.len());
878     let mut line_buffer = String::with_capacity(s.len());
879     for (kind, rich_char) in CharClasses::new(s.chars()) {
880         match rich_char.get_char() {
881             '\n' => {
882                 if result.is_empty() || !line_buffer.trim().is_empty() {
883                     result.push_str(&line_buffer);
884                     result.push('\n')
885                 }
886                 line_buffer.clear();
887             }
888             '?' if kind == FullCodeCharKind::Normal => continue,
889             c => line_buffer.push(c),
890         }
891     }
892     if !line_buffer.trim().is_empty() {
893         result.push_str(&line_buffer);
894     }
895     result
896 }