]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
Add a space before comment that comes after a block-like chain item
[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 codemap::SpanUtils;
69 use comment::rewrite_comment;
70 use config::IndentStyle;
71 use expr::rewrite_call;
72 use macros::convert_try_mac;
73 use rewrite::{Rewrite, RewriteContext};
74 use shape::Shape;
75 use utils::{
76     first_line_width, last_line_extendable, last_line_width, mk_sp, trimmed_last_line_width,
77     wrap_str,
78 };
79
80 use std::borrow::Cow;
81 use std::cmp::min;
82 use std::iter;
83
84 use syntax::codemap::Span;
85 use syntax::{ast, ptr};
86
87 pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -> Option<String> {
88     let chain = Chain::from_ast(expr, context);
89     debug!("rewrite_chain {:?} {:?}", chain, shape);
90
91     // If this is just an expression with some `?`s, then format it trivially and
92     // return early.
93     if chain.children.is_empty() {
94         return chain.parent.rewrite(context, shape);
95     }
96
97     chain.rewrite(context, shape)
98 }
99
100 // An expression plus trailing `?`s to be formatted together.
101 #[derive(Debug)]
102 struct ChainItem {
103     kind: ChainItemKind,
104     tries: usize,
105     span: Span,
106 }
107
108 // FIXME: we can't use a reference here because to convert `try!` to `?` we
109 // synthesise the AST node. However, I think we could use `Cow` and that
110 // would remove a lot of cloning.
111 #[derive(Debug)]
112 enum ChainItemKind {
113     Parent(ast::Expr),
114     MethodCall(
115         ast::PathSegment,
116         Vec<ast::GenericArg>,
117         Vec<ptr::P<ast::Expr>>,
118     ),
119     StructField(ast::Ident),
120     TupleField(ast::Ident, bool),
121     Comment,
122 }
123
124 impl ChainItemKind {
125     fn is_block_like(&self, context: &RewriteContext, reps: &str) -> bool {
126         match self {
127             ChainItemKind::Parent(ref expr) => is_block_expr(context, expr, reps),
128             ChainItemKind::MethodCall(..) => reps.contains('\n'),
129             ChainItemKind::StructField(..)
130             | ChainItemKind::TupleField(..)
131             | ChainItemKind::Comment => false,
132         }
133     }
134
135     fn is_tup_field_access(expr: &ast::Expr) -> bool {
136         match expr.node {
137             ast::ExprKind::Field(_, ref field) => {
138                 field.name.to_string().chars().all(|c| c.is_digit(10))
139             }
140             _ => false,
141         }
142     }
143
144     fn from_ast(context: &RewriteContext, expr: &ast::Expr) -> (ChainItemKind, Span) {
145         let (kind, span) = match expr.node {
146             ast::ExprKind::MethodCall(ref segment, ref expressions) => {
147                 let types = if let Some(ref generic_args) = segment.args {
148                     if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
149                         data.args.clone()
150                     } else {
151                         vec![]
152                     }
153                 } else {
154                     vec![]
155                 };
156                 let span = mk_sp(expressions[0].span.hi(), expr.span.hi());
157                 let kind = ChainItemKind::MethodCall(segment.clone(), types, expressions.clone());
158                 (kind, span)
159             }
160             ast::ExprKind::Field(ref nested, field) => {
161                 let kind = if Self::is_tup_field_access(expr) {
162                     ChainItemKind::TupleField(field, Self::is_tup_field_access(nested))
163                 } else {
164                     ChainItemKind::StructField(field)
165                 };
166                 let span = mk_sp(nested.span.hi(), field.span.hi());
167                 (kind, span)
168             }
169             _ => return (ChainItemKind::Parent(expr.clone()), expr.span),
170         };
171
172         // Remove comments from the span.
173         let lo = context.snippet_provider.span_before(span, ".");
174         (kind, mk_sp(lo, span.hi()))
175     }
176 }
177
178 impl Rewrite for ChainItem {
179     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
180         let shape = shape.sub_width(self.tries)?;
181         let rewrite = match self.kind {
182             ChainItemKind::Parent(ref expr) => expr.rewrite(context, shape)?,
183             ChainItemKind::MethodCall(ref segment, ref types, ref exprs) => {
184                 Self::rewrite_method_call(segment.ident, types, exprs, self.span, context, shape)?
185             }
186             ChainItemKind::StructField(ident) => format!(".{}", ident.name),
187             ChainItemKind::TupleField(ident, nested) => {
188                 format!("{}.{}", if nested { " " } else { "" }, ident.name)
189             }
190             ChainItemKind::Comment => {
191                 rewrite_comment(context.snippet(self.span).trim(), false, shape, context.config)?
192             }
193         };
194         Some(format!("{}{}", rewrite, "?".repeat(self.tries)))
195     }
196 }
197
198 impl ChainItem {
199     fn new(context: &RewriteContext, expr: &ast::Expr, tries: usize) -> ChainItem {
200         let (kind, span) = ChainItemKind::from_ast(context, expr);
201         ChainItem { kind, tries, span }
202     }
203
204     fn comment(span: Span) -> ChainItem {
205         ChainItem {
206             kind: ChainItemKind::Comment,
207             tries: 0,
208             span,
209         }
210     }
211
212     fn is_comment(&self) -> bool {
213         match self.kind {
214             ChainItemKind::Comment => true,
215             _ => false,
216         }
217     }
218
219     fn rewrite_method_call(
220         method_name: ast::Ident,
221         types: &[ast::GenericArg],
222         args: &[ptr::P<ast::Expr>],
223         span: Span,
224         context: &RewriteContext,
225         shape: Shape,
226     ) -> Option<String> {
227         let type_str = if types.is_empty() {
228             String::new()
229         } else {
230             let type_list = types
231                 .iter()
232                 .map(|ty| ty.rewrite(context, shape))
233                 .collect::<Option<Vec<_>>>()?;
234
235             format!("::<{}>", type_list.join(", "))
236         };
237         let callee_str = format!(".{}{}", method_name, type_str);
238         rewrite_call(context, &callee_str, &args[1..], span, shape)
239     }
240 }
241
242 #[derive(Debug)]
243 struct Chain {
244     parent: ChainItem,
245     children: Vec<ChainItem>,
246 }
247
248 impl Chain {
249     fn from_ast(expr: &ast::Expr, context: &RewriteContext) -> Chain {
250         let subexpr_list = Self::make_subexpr_list(expr, context);
251
252         // Un-parse the expression tree into ChainItems
253         let mut rev_children = vec![];
254         let mut sub_tries = 0;
255         for subexpr in &subexpr_list {
256             match subexpr.node {
257                 ast::ExprKind::Try(_) => sub_tries += 1,
258                 _ => {
259                     rev_children.push(ChainItem::new(context, subexpr, sub_tries));
260                     sub_tries = 0;
261                 }
262             }
263         }
264
265         let parent = rev_children.pop().unwrap();
266         let mut children = vec![];
267         let mut prev_hi = parent.span.hi();
268         for chain_item in rev_children.into_iter().rev() {
269             let comment_span = mk_sp(prev_hi, chain_item.span.lo());
270             let comment_snippet = context.snippet(comment_span);
271             if !comment_snippet.trim().is_empty() {
272                 children.push(ChainItem::comment(comment_span));
273             }
274             prev_hi = chain_item.span.hi();
275             children.push(chain_item);
276         }
277
278         Chain { parent, children }
279     }
280
281     // Returns a Vec of the prefixes of the chain.
282     // E.g., for input `a.b.c` we return [`a.b.c`, `a.b`, 'a']
283     fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> Vec<ast::Expr> {
284         let mut subexpr_list = vec![expr.clone()];
285
286         while let Some(subexpr) = Self::pop_expr_chain(subexpr_list.last().unwrap(), context) {
287             subexpr_list.push(subexpr.clone());
288         }
289
290         subexpr_list
291     }
292
293     // Returns the expression's subexpression, if it exists. When the subexpr
294     // is a try! macro, we'll convert it to shorthand when the option is set.
295     fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
296         match expr.node {
297             ast::ExprKind::MethodCall(_, ref expressions) => {
298                 Some(Self::convert_try(&expressions[0], context))
299             }
300             ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) => {
301                 Some(Self::convert_try(subexpr, context))
302             }
303             _ => None,
304         }
305     }
306
307     fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
308         match expr.node {
309             ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
310                 if let Some(subexpr) = convert_try_mac(mac, context) {
311                     subexpr
312                 } else {
313                     expr.clone()
314                 }
315             }
316             _ => expr.clone(),
317         }
318     }
319 }
320
321 impl Rewrite for Chain {
322     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
323         debug!("rewrite chain {:?} {:?}", self, shape);
324
325         let mut formatter = match context.config.indent_style() {
326             IndentStyle::Block => Box::new(ChainFormatterBlock::new(self)) as Box<ChainFormatter>,
327             IndentStyle::Visual => Box::new(ChainFormatterVisual::new(self)) as Box<ChainFormatter>,
328         };
329
330         formatter.format_root(&self.parent, context, shape)?;
331         if let Some(result) = formatter.pure_root() {
332             return wrap_str(result, context.config.max_width(), shape);
333         }
334
335         // Decide how to layout the rest of the chain.
336         let child_shape = formatter.child_shape(context, shape)?;
337
338         formatter.format_children(context, child_shape)?;
339         formatter.format_last_child(context, shape, child_shape)?;
340
341         let result = formatter.join_rewrites(context, child_shape)?;
342         wrap_str(result, context.config.max_width(), shape)
343     }
344 }
345
346 // There are a few types for formatting chains. This is because there is a lot
347 // in common between formatting with block vs visual indent, but they are
348 // different enough that branching on the indent all over the place gets ugly.
349 // Anything that can format a chain is a ChainFormatter.
350 trait ChainFormatter {
351     // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
352     // Root is the parent plus any other chain items placed on the first line to
353     // avoid an orphan. E.g.,
354     // ```
355     // foo.bar
356     //     .baz()
357     // ```
358     // If `bar` were not part of the root, then foo would be orphaned and 'float'.
359     fn format_root(
360         &mut self,
361         parent: &ChainItem,
362         context: &RewriteContext,
363         shape: Shape,
364     ) -> Option<()>;
365     fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape>;
366     fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()>;
367     fn format_last_child(
368         &mut self,
369         context: &RewriteContext,
370         shape: Shape,
371         child_shape: Shape,
372     ) -> Option<()>;
373     fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String>;
374     // Returns `Some` if the chain is only a root, None otherwise.
375     fn pure_root(&mut self) -> Option<String>;
376 }
377
378 // Data and behaviour that is shared by both chain formatters. The concrete
379 // formatters can delegate much behaviour to `ChainFormatterShared`.
380 struct ChainFormatterShared<'a> {
381     // The current working set of child items.
382     children: &'a [ChainItem],
383     // The current rewrites of items (includes trailing `?`s, but not any way to
384     // connect the rewrites together).
385     rewrites: Vec<String>,
386     // Whether the chain can fit on one line.
387     fits_single_line: bool,
388     // The number of children in the chain. This is not equal to `self.children.len()`
389     // because `self.children` will change size as we process the chain.
390     child_count: usize,
391 }
392
393 impl<'a> ChainFormatterShared<'a> {
394     fn new(chain: &'a Chain) -> ChainFormatterShared<'a> {
395         ChainFormatterShared {
396             children: &chain.children,
397             rewrites: Vec::with_capacity(chain.children.len() + 1),
398             fits_single_line: false,
399             child_count: chain.children.len(),
400         }
401     }
402
403     fn pure_root(&mut self) -> Option<String> {
404         if self.children.is_empty() {
405             assert_eq!(self.rewrites.len(), 1);
406             Some(self.rewrites.pop().unwrap())
407         } else {
408             None
409         }
410     }
411
412     // Rewrite the last child. The last child of a chain requires special treatment. We need to
413     // know whether 'overflowing' the last child make a better formatting:
414     //
415     // A chain with overflowing the last child:
416     // ```
417     // parent.child1.child2.last_child(
418     //     a,
419     //     b,
420     //     c,
421     // )
422     // ```
423     //
424     // A chain without overflowing the last child (in vertical layout):
425     // ```
426     // parent
427     //     .child1
428     //     .child2
429     //     .last_child(a, b, c)
430     // ```
431     //
432     // In particular, overflowing is effective when the last child is a method with a multi-lined
433     // block-like argument (e.g. closure):
434     // ```
435     // parent.child1.child2.last_child(|a, b, c| {
436     //     let x = foo(a, b, c);
437     //     let y = bar(a, b, c);
438     //
439     //     // ...
440     //
441     //     result
442     // })
443     // ```
444     fn format_last_child(
445         &mut self,
446         may_extend: bool,
447         context: &RewriteContext,
448         shape: Shape,
449         child_shape: Shape,
450     ) -> Option<()> {
451         let last = self.children.last()?;
452         let extendable = may_extend && last_line_extendable(&self.rewrites[0]);
453         let prev_last_line_width = last_line_width(&self.rewrites[0]);
454
455         // Total of all items excluding the last.
456         let almost_total = if extendable {
457             prev_last_line_width
458         } else {
459             self.rewrites.iter().fold(0, |a, b| a + b.len())
460         } + last.tries;
461         let one_line_budget = if self.child_count == 1 {
462             shape.width
463         } else {
464             min(shape.width, context.config.width_heuristics().chain_width)
465         }.saturating_sub(almost_total);
466
467         let all_in_one_line =
468             !self.children.iter().any(ChainItem::is_comment)
469             && self.rewrites.iter().all(|s| !s.contains('\n'))
470             && one_line_budget > 0;
471         let last_shape = if all_in_one_line {
472             shape.sub_width(last.tries)?
473         } else if extendable {
474             child_shape.sub_width(last.tries)?
475         } else {
476             child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?
477         };
478
479         let mut last_subexpr_str = None;
480         if all_in_one_line || extendable {
481             // First we try to 'overflow' the last child and see if it looks better than using
482             // vertical layout.
483             if let Some(one_line_shape) = last_shape.offset_left(almost_total) {
484                 if let Some(rw) = last.rewrite(context, one_line_shape) {
485                     // We allow overflowing here only if both of the following conditions match:
486                     // 1. The entire chain fits in a single line except the last child.
487                     // 2. `last_child_str.lines().count() >= 5`.
488                     let line_count = rw.lines().count();
489                     let could_fit_single_line = first_line_width(&rw) <= one_line_budget;
490                     if could_fit_single_line && line_count >= 5 {
491                         last_subexpr_str = Some(rw);
492                         self.fits_single_line = all_in_one_line;
493                     } else {
494                         // We could not know whether overflowing is better than using vertical
495                         // layout, just by looking at the overflowed rewrite. Now we rewrite the
496                         // last child on its own line, and compare two rewrites to choose which is
497                         // better.
498                         let last_shape = child_shape
499                             .sub_width(shape.rhs_overhead(context.config) + last.tries)?;
500                         match last.rewrite(context, last_shape) {
501                             Some(ref new_rw) if !could_fit_single_line => {
502                                 last_subexpr_str = Some(new_rw.clone());
503                             }
504                             Some(ref new_rw) if new_rw.lines().count() >= line_count => {
505                                 last_subexpr_str = Some(rw);
506                                 self.fits_single_line = could_fit_single_line && all_in_one_line;
507                             }
508                             new_rw @ Some(..) => {
509                                 last_subexpr_str = new_rw;
510                             }
511                             _ => {
512                                 last_subexpr_str = Some(rw);
513                                 self.fits_single_line = could_fit_single_line && all_in_one_line;
514                             }
515                         }
516                     }
517                 }
518             }
519         }
520
521         last_subexpr_str = last_subexpr_str.or_else(|| last.rewrite(context, last_shape));
522         self.rewrites.push(last_subexpr_str?);
523         Some(())
524     }
525
526     fn join_rewrites(
527         &self,
528         context: &RewriteContext,
529         child_shape: Shape,
530         block_like_iter: impl Iterator<Item = bool>,
531     ) -> Option<String> {
532         let connector = if self.fits_single_line {
533             // Yay, we can put everything on one line.
534             Cow::from("")
535         } else {
536             // Use new lines.
537             if *context.force_one_line_chain.borrow() {
538                 return None;
539             }
540             child_shape.to_string_with_newline(context.config)
541         };
542
543         let mut rewrite_iter = self.rewrites.iter();
544         let mut result = rewrite_iter.next().unwrap().clone();
545
546         for (rewrite, prev_is_block_like) in rewrite_iter.zip(block_like_iter) {
547             if !prev_is_block_like {
548                 result.push_str(&connector);
549             } else if rewrite.starts_with('/') {
550                 // This is comment, add a space before it.
551                 result.push(' ');
552             }
553             result.push_str(&rewrite);
554         }
555
556         Some(result)
557     }
558 }
559
560 // Formats a chain using block indent.
561 struct ChainFormatterBlock<'a> {
562     shared: ChainFormatterShared<'a>,
563     // For each rewrite, whether the corresponding item is block-like.
564     is_block_like: Vec<bool>,
565 }
566
567 impl<'a> ChainFormatterBlock<'a> {
568     fn new(chain: &'a Chain) -> ChainFormatterBlock<'a> {
569         ChainFormatterBlock {
570             shared: ChainFormatterShared::new(chain),
571             is_block_like: Vec::with_capacity(chain.children.len() + 1),
572         }
573     }
574 }
575
576 impl<'a> ChainFormatter for ChainFormatterBlock<'a> {
577     fn format_root(
578         &mut self,
579         parent: &ChainItem,
580         context: &RewriteContext,
581         shape: Shape,
582     ) -> Option<()> {
583         let mut root_rewrite: String = parent.rewrite(context, shape)?;
584
585         let mut root_ends_with_block = parent.kind.is_block_like(context, &root_rewrite);
586         let tab_width = context.config.tab_spaces().saturating_sub(shape.offset);
587
588         while root_rewrite.len() <= tab_width && !root_rewrite.contains('\n') {
589             let item = &self.shared.children[0];
590             if let ChainItemKind::Comment = item.kind {
591                 break;
592             }
593             let shape = shape.offset_left(root_rewrite.len())?;
594             match &item.rewrite(context, shape) {
595                 Some(rewrite) => root_rewrite.push_str(rewrite),
596                 None => break,
597             }
598
599             root_ends_with_block = item.kind.is_block_like(context, &root_rewrite);
600
601             self.shared.children = &self.shared.children[1..];
602             if self.shared.children.is_empty() {
603                 break;
604             }
605         }
606         self.is_block_like.push(root_ends_with_block);
607         self.shared.rewrites.push(root_rewrite);
608         Some(())
609     }
610
611     fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape> {
612         Some(
613             if self.is_block_like[0] {
614                 shape.block_indent(0)
615             } else {
616                 shape.block_indent(context.config.tab_spaces())
617             }.with_max_width(context.config),
618         )
619     }
620
621     fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
622         for item in &self.shared.children[..self.shared.children.len() - 1] {
623             let rewrite = item.rewrite(context, child_shape)?;
624             self.is_block_like
625                 .push(item.kind.is_block_like(context, &rewrite));
626             self.shared.rewrites.push(rewrite);
627         }
628         Some(())
629     }
630
631     fn format_last_child(
632         &mut self,
633         context: &RewriteContext,
634         shape: Shape,
635         child_shape: Shape,
636     ) -> Option<()> {
637         self.shared
638             .format_last_child(true, context, shape, child_shape)
639     }
640
641     fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
642         self.shared
643             .join_rewrites(context, child_shape, self.is_block_like.iter().cloned())
644     }
645
646     fn pure_root(&mut self) -> Option<String> {
647         self.shared.pure_root()
648     }
649 }
650
651 // Format a chain using visual indent.
652 struct ChainFormatterVisual<'a> {
653     shared: ChainFormatterShared<'a>,
654     // The extra offset from the chain's shape to the position of the `.`
655     offset: usize,
656 }
657
658 impl<'a> ChainFormatterVisual<'a> {
659     fn new(chain: &'a Chain) -> ChainFormatterVisual<'a> {
660         ChainFormatterVisual {
661             shared: ChainFormatterShared::new(chain),
662             offset: 0,
663         }
664     }
665 }
666
667 impl<'a> ChainFormatter for ChainFormatterVisual<'a> {
668     fn format_root(
669         &mut self,
670         parent: &ChainItem,
671         context: &RewriteContext,
672         shape: Shape,
673     ) -> Option<()> {
674         let parent_shape = shape.visual_indent(0);
675         let mut root_rewrite = parent.rewrite(context, parent_shape)?;
676         let multiline = root_rewrite.contains('\n');
677         self.offset = if multiline {
678             last_line_width(&root_rewrite).saturating_sub(shape.used_width())
679         } else {
680             trimmed_last_line_width(&root_rewrite)
681         };
682
683         if !multiline || parent.kind.is_block_like(context, &root_rewrite) {
684             let item = &self.shared.children[0];
685             if let ChainItemKind::Comment = item.kind {
686                 self.shared.rewrites.push(root_rewrite);
687                 return Some(());
688             }
689             let child_shape = parent_shape
690                 .visual_indent(self.offset)
691                 .sub_width(self.offset)?;
692             let rewrite = item.rewrite(context, child_shape)?;
693             match wrap_str(rewrite, context.config.max_width(), shape) {
694                 Some(rewrite) => root_rewrite.push_str(&rewrite),
695                 None => {
696                     // We couldn't fit in at the visual indent, try the last
697                     // indent.
698                     let rewrite = item.rewrite(context, parent_shape)?;
699                     root_rewrite.push_str(&rewrite);
700                     self.offset = 0;
701                 }
702             }
703
704             self.shared.children = &self.shared.children[1..];
705         }
706
707         self.shared.rewrites.push(root_rewrite);
708         Some(())
709     }
710
711     fn child_shape(&self, context: &RewriteContext, shape: Shape) -> Option<Shape> {
712         shape
713             .with_max_width(context.config)
714             .offset_left(self.offset)
715             .map(|s| s.visual_indent(0))
716     }
717
718     fn format_children(&mut self, context: &RewriteContext, child_shape: Shape) -> Option<()> {
719         for item in &self.shared.children[..self.shared.children.len() - 1] {
720             let rewrite = item.rewrite(context, child_shape)?;
721             self.shared.rewrites.push(rewrite);
722         }
723         Some(())
724     }
725
726     fn format_last_child(
727         &mut self,
728         context: &RewriteContext,
729         shape: Shape,
730         child_shape: Shape,
731     ) -> Option<()> {
732         self.shared
733             .format_last_child(false, context, shape, child_shape)
734     }
735
736     fn join_rewrites(&self, context: &RewriteContext, child_shape: Shape) -> Option<String> {
737         self.shared
738             .join_rewrites(context, child_shape, iter::repeat(false))
739     }
740
741     fn pure_root(&mut self) -> Option<String> {
742         self.shared.pure_root()
743     }
744 }
745
746 // States whether an expression's last line exclusively consists of closing
747 // parens, braces, and brackets in its idiomatic formatting.
748 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
749     match expr.node {
750         ast::ExprKind::Mac(..)
751         | ast::ExprKind::Call(..)
752         | ast::ExprKind::MethodCall(..)
753         | ast::ExprKind::Struct(..)
754         | ast::ExprKind::While(..)
755         | ast::ExprKind::WhileLet(..)
756         | ast::ExprKind::If(..)
757         | ast::ExprKind::IfLet(..)
758         | ast::ExprKind::Block(..)
759         | ast::ExprKind::Loop(..)
760         | ast::ExprKind::ForLoop(..)
761         | ast::ExprKind::Match(..) => repr.contains('\n'),
762         ast::ExprKind::Paren(ref expr)
763         | ast::ExprKind::Binary(_, _, ref expr)
764         | ast::ExprKind::Index(_, ref expr)
765         | ast::ExprKind::Unary(_, ref expr)
766         | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
767         | ast::ExprKind::Try(ref expr)
768         | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
769         // This can only be a string lit
770         ast::ExprKind::Lit(_) => {
771             repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
772         }
773         _ => false,
774     }
775 }