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