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