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