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