]> git.lizzy.rs Git - rust.git/blob - src/overflow.rs
Prioritize single_line_fn and empty_item_single_line over brace_style
[rust.git] / src / overflow.rs
1 // Copyright 2018 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 //! Rewrite a list some items with overflow.
12
13 use config::lists::*;
14 use config::Version;
15 use syntax::parse::token::DelimToken;
16 use syntax::source_map::Span;
17 use syntax::{ast, ptr};
18
19 use closures;
20 use expr::{
21     can_be_overflowed_expr, is_every_expr_simple, is_method_call, is_nested_call, is_simple_expr,
22     rewrite_cond,
23 };
24 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator};
25 use macros::MacroArg;
26 use patterns::{can_be_overflowed_pat, TuplePatField};
27 use rewrite::{Rewrite, RewriteContext};
28 use shape::Shape;
29 use source_map::SpanUtils;
30 use spanned::Spanned;
31 use types::{can_be_overflowed_type, SegmentParam};
32 use utils::{count_newlines, extra_offset, first_line_width, last_line_width, mk_sp};
33
34 use std::cmp::min;
35
36 const SHORT_ITEM_THRESHOLD: usize = 10;
37
38 /// A list of `format!`-like macros, that take a long format string and a list of arguments to
39 /// format.
40 ///
41 /// Organized as a list of `(&str, usize)` tuples, giving the name of the macro and the number of
42 /// arguments before the format string (none for `format!("format", ...)`, one for `assert!(result,
43 /// "format", ...)`, two for `assert_eq!(left, right, "format", ...)`).
44 const SPECIAL_MACRO_WHITELIST: &[(&str, usize)] = &[
45     // format! like macros
46     // From the Rust Standard Library.
47     ("eprint!", 0),
48     ("eprintln!", 0),
49     ("format!", 0),
50     ("format_args!", 0),
51     ("print!", 0),
52     ("println!", 0),
53     ("panic!", 0),
54     ("unreachable!", 0),
55     // From the `log` crate.
56     ("debug!", 0),
57     ("error!", 0),
58     ("info!", 0),
59     ("warn!", 0),
60     // write! like macros
61     ("assert!", 1),
62     ("debug_assert!", 1),
63     ("write!", 1),
64     ("writeln!", 1),
65     // assert_eq! like macros
66     ("assert_eq!", 2),
67     ("assert_ne!", 2),
68     ("debug_assert_eq!", 2),
69     ("debug_assert_ne!", 2),
70 ];
71
72 const SPECIAL_ATTR_WHITELIST: &[(&str, usize)] = &[
73     // From the `failure` crate.
74     ("fail", 0),
75 ];
76
77 #[derive(Debug)]
78 pub enum OverflowableItem<'a> {
79     Expr(&'a ast::Expr),
80     GenericParam(&'a ast::GenericParam),
81     MacroArg(&'a MacroArg),
82     NestedMetaItem(&'a ast::NestedMetaItem),
83     SegmentParam(&'a SegmentParam<'a>),
84     StructField(&'a ast::StructField),
85     TuplePatField(&'a TuplePatField<'a>),
86     Ty(&'a ast::Ty),
87 }
88
89 impl<'a> Rewrite for OverflowableItem<'a> {
90     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
91         self.map(|item| item.rewrite(context, shape))
92     }
93 }
94
95 impl<'a> Spanned for OverflowableItem<'a> {
96     fn span(&self) -> Span {
97         self.map(|item| item.span())
98     }
99 }
100
101 impl<'a> OverflowableItem<'a> {
102     pub fn map<F, T>(&self, f: F) -> T
103     where
104         F: Fn(&IntoOverflowableItem<'a>) -> T,
105     {
106         match self {
107             OverflowableItem::Expr(expr) => f(*expr),
108             OverflowableItem::GenericParam(gp) => f(*gp),
109             OverflowableItem::MacroArg(macro_arg) => f(*macro_arg),
110             OverflowableItem::NestedMetaItem(nmi) => f(*nmi),
111             OverflowableItem::SegmentParam(sp) => f(*sp),
112             OverflowableItem::StructField(sf) => f(*sf),
113             OverflowableItem::TuplePatField(pat) => f(*pat),
114             OverflowableItem::Ty(ty) => f(*ty),
115         }
116     }
117
118     pub fn is_simple(&self) -> bool {
119         match self {
120             OverflowableItem::Expr(expr) => is_simple_expr(expr),
121             OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_simple_expr(expr),
122             OverflowableItem::NestedMetaItem(nested_meta_item) => match nested_meta_item.node {
123                 ast::NestedMetaItemKind::Literal(..) => true,
124                 ast::NestedMetaItemKind::MetaItem(ref meta_item) => match meta_item.node {
125                     ast::MetaItemKind::Word => true,
126                     _ => false,
127                 },
128             },
129             _ => false,
130         }
131     }
132
133     pub fn is_expr(&self) -> bool {
134         match self {
135             OverflowableItem::Expr(..) => true,
136             OverflowableItem::MacroArg(MacroArg::Expr(..)) => true,
137             _ => false,
138         }
139     }
140
141     pub fn is_nested_call(&self) -> bool {
142         match self {
143             OverflowableItem::Expr(expr) => is_nested_call(expr),
144             OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_nested_call(expr),
145             _ => false,
146         }
147     }
148
149     pub fn to_expr(&self) -> Option<&'a ast::Expr> {
150         match self {
151             OverflowableItem::Expr(expr) => Some(expr),
152             OverflowableItem::MacroArg(macro_arg) => match macro_arg {
153                 MacroArg::Expr(ref expr) => Some(expr),
154                 _ => None,
155             },
156             _ => None,
157         }
158     }
159
160     pub fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
161         match self {
162             OverflowableItem::Expr(expr) => can_be_overflowed_expr(context, expr, len),
163             OverflowableItem::MacroArg(macro_arg) => match macro_arg {
164                 MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
165                 MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
166                 MacroArg::Pat(..) => false,
167                 MacroArg::Item(..) => len == 1,
168             },
169             OverflowableItem::NestedMetaItem(nested_meta_item) if len == 1 => {
170                 match nested_meta_item.node {
171                     ast::NestedMetaItemKind::Literal(..) => false,
172                     ast::NestedMetaItemKind::MetaItem(..) => true,
173                 }
174             }
175             OverflowableItem::SegmentParam(seg) => match seg {
176                 SegmentParam::Type(ty) => can_be_overflowed_type(context, ty, len),
177                 _ => false,
178             },
179             OverflowableItem::TuplePatField(pat) => can_be_overflowed_pat(context, pat, len),
180             OverflowableItem::Ty(ty) => can_be_overflowed_type(context, ty, len),
181             _ => false,
182         }
183     }
184
185     fn whitelist(&self) -> &'static [(&'static str, usize)] {
186         match self {
187             OverflowableItem::MacroArg(..) => SPECIAL_MACRO_WHITELIST,
188             OverflowableItem::NestedMetaItem(..) => SPECIAL_ATTR_WHITELIST,
189             _ => &[],
190         }
191     }
192 }
193
194 pub trait IntoOverflowableItem<'a>: Rewrite + Spanned {
195     fn into_overflowable_item(&'a self) -> OverflowableItem<'a>;
196 }
197
198 impl<'a, T: 'a + IntoOverflowableItem<'a>> IntoOverflowableItem<'a> for ptr::P<T> {
199     fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
200         (**self).into_overflowable_item()
201     }
202 }
203
204 macro_rules! impl_into_overflowable_item_for_ast_node {
205     ($($ast_node:ident),*) => {
206         $(
207             impl<'a> IntoOverflowableItem<'a> for ast::$ast_node {
208                 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
209                     OverflowableItem::$ast_node(self)
210                 }
211             }
212         )*
213     }
214 }
215
216 macro_rules! impl_into_overflowable_item_for_rustfmt_types {
217     ([$($ty:ident),*], [$($ty_with_lifetime:ident),*]) => {
218         $(
219             impl<'a> IntoOverflowableItem<'a> for $ty {
220                 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
221                     OverflowableItem::$ty(self)
222                 }
223             }
224         )*
225         $(
226             impl<'a> IntoOverflowableItem<'a> for $ty_with_lifetime<'a> {
227                 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
228                     OverflowableItem::$ty_with_lifetime(self)
229                 }
230             }
231         )*
232     }
233 }
234
235 impl_into_overflowable_item_for_ast_node!(Expr, GenericParam, NestedMetaItem, StructField, Ty);
236 impl_into_overflowable_item_for_rustfmt_types!([MacroArg], [SegmentParam, TuplePatField]);
237
238 pub fn into_overflowable_list<'a, T>(
239     iter: impl Iterator<Item = &'a T>,
240 ) -> impl Iterator<Item = OverflowableItem<'a>>
241 where
242     T: 'a + IntoOverflowableItem<'a>,
243 {
244     iter.map(|x| IntoOverflowableItem::into_overflowable_item(x))
245 }
246
247 pub fn rewrite_with_parens<'a, T: 'a + IntoOverflowableItem<'a>>(
248     context: &'a RewriteContext,
249     ident: &'a str,
250     items: impl Iterator<Item = &'a T>,
251     shape: Shape,
252     span: Span,
253     item_max_width: usize,
254     force_separator_tactic: Option<SeparatorTactic>,
255 ) -> Option<String> {
256     Context::new(
257         context,
258         items,
259         ident,
260         shape,
261         span,
262         "(",
263         ")",
264         item_max_width,
265         force_separator_tactic,
266         None,
267     )
268     .rewrite(shape)
269 }
270
271 pub fn rewrite_with_angle_brackets<'a, T: 'a + IntoOverflowableItem<'a>>(
272     context: &'a RewriteContext,
273     ident: &'a str,
274     items: impl Iterator<Item = &'a T>,
275     shape: Shape,
276     span: Span,
277 ) -> Option<String> {
278     Context::new(
279         context,
280         items,
281         ident,
282         shape,
283         span,
284         "<",
285         ">",
286         context.config.max_width(),
287         None,
288         None,
289     )
290     .rewrite(shape)
291 }
292
293 pub fn rewrite_with_square_brackets<'a, T: 'a + IntoOverflowableItem<'a>>(
294     context: &'a RewriteContext,
295     name: &'a str,
296     items: impl Iterator<Item = &'a T>,
297     shape: Shape,
298     span: Span,
299     force_separator_tactic: Option<SeparatorTactic>,
300     delim_token: Option<DelimToken>,
301 ) -> Option<String> {
302     let (lhs, rhs) = match delim_token {
303         Some(DelimToken::Paren) => ("(", ")"),
304         Some(DelimToken::Brace) => ("{", "}"),
305         _ => ("[", "]"),
306     };
307     Context::new(
308         context,
309         items,
310         name,
311         shape,
312         span,
313         lhs,
314         rhs,
315         context.config.width_heuristics().array_width,
316         force_separator_tactic,
317         Some(("[", "]")),
318     )
319     .rewrite(shape)
320 }
321
322 struct Context<'a> {
323     context: &'a RewriteContext<'a>,
324     items: Vec<OverflowableItem<'a>>,
325     ident: &'a str,
326     prefix: &'static str,
327     suffix: &'static str,
328     one_line_shape: Shape,
329     nested_shape: Shape,
330     span: Span,
331     item_max_width: usize,
332     one_line_width: usize,
333     force_separator_tactic: Option<SeparatorTactic>,
334     custom_delims: Option<(&'a str, &'a str)>,
335 }
336
337 impl<'a> Context<'a> {
338     pub fn new<T: 'a + IntoOverflowableItem<'a>>(
339         context: &'a RewriteContext,
340         items: impl Iterator<Item = &'a T>,
341         ident: &'a str,
342         shape: Shape,
343         span: Span,
344         prefix: &'static str,
345         suffix: &'static str,
346         item_max_width: usize,
347         force_separator_tactic: Option<SeparatorTactic>,
348         custom_delims: Option<(&'a str, &'a str)>,
349     ) -> Context<'a> {
350         let used_width = extra_offset(ident, shape);
351         // 1 = `()`
352         let one_line_width = shape.width.saturating_sub(used_width + 2);
353
354         // 1 = "(" or ")"
355         let one_line_shape = shape
356             .offset_left(last_line_width(ident) + 1)
357             .and_then(|shape| shape.sub_width(1))
358             .unwrap_or(Shape { width: 0, ..shape });
359         let nested_shape = shape_from_indent_style(context, shape, used_width + 2, used_width + 1);
360         Context {
361             context,
362             items: into_overflowable_list(items).collect(),
363             ident,
364             one_line_shape,
365             nested_shape,
366             span,
367             prefix,
368             suffix,
369             item_max_width,
370             one_line_width,
371             force_separator_tactic,
372             custom_delims,
373         }
374     }
375
376     fn last_item(&self) -> Option<&OverflowableItem> {
377         self.items.last()
378     }
379
380     fn items_span(&self) -> Span {
381         let span_lo = self
382             .context
383             .snippet_provider
384             .span_after(self.span, self.prefix);
385         mk_sp(span_lo, self.span.hi())
386     }
387
388     fn rewrite_last_item_with_overflow(
389         &self,
390         last_list_item: &mut ListItem,
391         shape: Shape,
392     ) -> Option<String> {
393         let last_item = self.last_item()?;
394         let rewrite = match last_item {
395             OverflowableItem::Expr(ref expr) => {
396                 match expr.node {
397                     // When overflowing the closure which consists of a single control flow
398                     // expression, force to use block if its condition uses multi line.
399                     ast::ExprKind::Closure(..) => {
400                         // If the argument consists of multiple closures, we do not overflow
401                         // the last closure.
402                         if closures::args_have_many_closure(&self.items) {
403                             None
404                         } else {
405                             closures::rewrite_last_closure(self.context, expr, shape)
406                         }
407                     }
408
409                     // When overflowing the expressions which consists of a control flow
410                     // expression, avoid condition to use multi line.
411                     ast::ExprKind::If(..)
412                     | ast::ExprKind::IfLet(..)
413                     | ast::ExprKind::ForLoop(..)
414                     | ast::ExprKind::Loop(..)
415                     | ast::ExprKind::While(..)
416                     | ast::ExprKind::WhileLet(..)
417                     | ast::ExprKind::Match(..) => {
418                         let multi_line = rewrite_cond(self.context, expr, shape)
419                             .map_or(false, |cond| cond.contains('\n'));
420
421                         if multi_line {
422                             None
423                         } else {
424                             expr.rewrite(self.context, shape)
425                         }
426                     }
427
428                     _ => expr.rewrite(self.context, shape),
429                 }
430             }
431             item => item.rewrite(self.context, shape),
432         };
433
434         if let Some(rewrite) = rewrite {
435             // splitn(2, *).next().unwrap() is always safe.
436             let rewrite_first_line = Some(rewrite.splitn(2, '\n').next().unwrap().to_owned());
437             last_list_item.item = rewrite_first_line;
438             Some(rewrite)
439         } else {
440             None
441         }
442     }
443
444     fn default_tactic(&self, list_items: &[ListItem]) -> DefinitiveListTactic {
445         definitive_tactic(
446             list_items,
447             ListTactic::LimitedHorizontalVertical(self.item_max_width),
448             Separator::Comma,
449             self.one_line_width,
450         )
451     }
452
453     fn try_overflow_last_item(&self, list_items: &mut Vec<ListItem>) -> DefinitiveListTactic {
454         // 1 = "("
455         let combine_arg_with_callee = self.items.len() == 1
456             && self.items[0].is_expr()
457             && self.ident.len() < self.context.config.tab_spaces();
458         let overflow_last = combine_arg_with_callee || can_be_overflowed(self.context, &self.items);
459
460         // Replace the last item with its first line to see if it fits with
461         // first arguments.
462         let placeholder = if overflow_last {
463             let old_value = *self.context.force_one_line_chain.borrow();
464             match self.last_item() {
465                 Some(OverflowableItem::Expr(expr))
466                     if !combine_arg_with_callee && is_method_call(expr) =>
467                 {
468                     self.context.force_one_line_chain.replace(true);
469                 }
470                 Some(OverflowableItem::MacroArg(MacroArg::Expr(expr)))
471                     if !combine_arg_with_callee
472                         && is_method_call(expr)
473                         && self.context.config.version() == Version::Two =>
474                 {
475                     self.context.force_one_line_chain.replace(true);
476                 }
477                 _ => (),
478             }
479             let result = last_item_shape(
480                 &self.items,
481                 list_items,
482                 self.one_line_shape,
483                 self.item_max_width,
484             )
485             .and_then(|arg_shape| {
486                 self.rewrite_last_item_with_overflow(
487                     &mut list_items[self.items.len() - 1],
488                     arg_shape,
489                 )
490             });
491             self.context.force_one_line_chain.replace(old_value);
492             result
493         } else {
494             None
495         };
496
497         let mut tactic = definitive_tactic(
498             &*list_items,
499             ListTactic::LimitedHorizontalVertical(self.item_max_width),
500             Separator::Comma,
501             self.one_line_width,
502         );
503
504         // Replace the stub with the full overflowing last argument if the rewrite
505         // succeeded and its first line fits with the other arguments.
506         match (overflow_last, tactic, placeholder) {
507             (true, DefinitiveListTactic::Horizontal, Some(ref overflowed))
508                 if self.items.len() == 1 =>
509             {
510                 // When we are rewriting a nested function call, we restrict the
511                 // budget for the inner function to avoid them being deeply nested.
512                 // However, when the inner function has a prefix or a suffix
513                 // (e.g. `foo() as u32`), this budget reduction may produce poorly
514                 // formatted code, where a prefix or a suffix being left on its own
515                 // line. Here we explicitlly check those cases.
516                 if count_newlines(overflowed) == 1 {
517                     let rw = self
518                         .items
519                         .last()
520                         .and_then(|last_item| last_item.rewrite(self.context, self.nested_shape));
521                     let no_newline = rw.as_ref().map_or(false, |s| !s.contains('\n'));
522                     if no_newline {
523                         list_items[self.items.len() - 1].item = rw;
524                     } else {
525                         list_items[self.items.len() - 1].item = Some(overflowed.to_owned());
526                     }
527                 } else {
528                     list_items[self.items.len() - 1].item = Some(overflowed.to_owned());
529                 }
530             }
531             (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
532                 list_items[self.items.len() - 1].item = placeholder;
533             }
534             _ if !self.items.is_empty() => {
535                 list_items[self.items.len() - 1].item = self
536                     .items
537                     .last()
538                     .and_then(|last_item| last_item.rewrite(self.context, self.nested_shape));
539
540                 // Use horizontal layout for a function with a single argument as long as
541                 // everything fits in a single line.
542                 // `self.one_line_width == 0` means vertical layout is forced.
543                 if self.items.len() == 1
544                     && self.one_line_width != 0
545                     && !list_items[0].has_comment()
546                     && !list_items[0].inner_as_ref().contains('\n')
547                     && ::lists::total_item_width(&list_items[0]) <= self.one_line_width
548                 {
549                     tactic = DefinitiveListTactic::Horizontal;
550                 } else {
551                     tactic = self.default_tactic(list_items);
552
553                     if tactic == DefinitiveListTactic::Vertical {
554                         if let Some((all_simple, num_args_before)) =
555                             maybe_get_args_offset(self.ident, &self.items)
556                         {
557                             let one_line = all_simple
558                                 && definitive_tactic(
559                                     &list_items[..num_args_before],
560                                     ListTactic::HorizontalVertical,
561                                     Separator::Comma,
562                                     self.nested_shape.width,
563                                 ) == DefinitiveListTactic::Horizontal
564                                 && definitive_tactic(
565                                     &list_items[num_args_before + 1..],
566                                     ListTactic::HorizontalVertical,
567                                     Separator::Comma,
568                                     self.nested_shape.width,
569                                 ) == DefinitiveListTactic::Horizontal;
570
571                             if one_line {
572                                 tactic = DefinitiveListTactic::SpecialMacro(num_args_before);
573                             };
574                         } else if is_every_expr_simple(&self.items) && no_long_items(list_items) {
575                             tactic = DefinitiveListTactic::Mixed;
576                         }
577                     }
578                 }
579             }
580             _ => (),
581         }
582
583         tactic
584     }
585
586     fn rewrite_items(&self) -> Option<(bool, String)> {
587         let span = self.items_span();
588         let items = itemize_list(
589             self.context.snippet_provider,
590             self.items.iter(),
591             self.suffix,
592             ",",
593             |item| item.span().lo(),
594             |item| item.span().hi(),
595             |item| item.rewrite(self.context, self.nested_shape),
596             span.lo(),
597             span.hi(),
598             true,
599         );
600         let mut list_items: Vec<_> = items.collect();
601
602         // Try letting the last argument overflow to the next line with block
603         // indentation. If its first line fits on one line with the other arguments,
604         // we format the function arguments horizontally.
605         let tactic = self.try_overflow_last_item(&mut list_items);
606         let trailing_separator = if let Some(tactic) = self.force_separator_tactic {
607             tactic
608         } else if !self.context.use_block_indent() {
609             SeparatorTactic::Never
610         } else {
611             self.context.config.trailing_comma()
612         };
613         let ends_with_newline = match tactic {
614             DefinitiveListTactic::Vertical | DefinitiveListTactic::Mixed => {
615                 self.context.use_block_indent()
616             }
617             _ => false,
618         };
619
620         let fmt = ListFormatting::new(self.nested_shape, self.context.config)
621             .tactic(tactic)
622             .trailing_separator(trailing_separator)
623             .ends_with_newline(ends_with_newline);
624
625         write_list(&list_items, &fmt)
626             .map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str))
627     }
628
629     fn wrap_items(&self, items_str: &str, shape: Shape, is_extendable: bool) -> String {
630         let shape = Shape {
631             width: shape.width.saturating_sub(last_line_width(self.ident)),
632             ..shape
633         };
634
635         let (prefix, suffix) = match self.custom_delims {
636             Some((lhs, rhs)) => (lhs, rhs),
637             _ => (self.prefix, self.suffix),
638         };
639
640         let extend_width = if items_str.is_empty() {
641             2
642         } else {
643             first_line_width(items_str) + 1
644         };
645         let nested_indent_str = self
646             .nested_shape
647             .indent
648             .to_string_with_newline(self.context.config);
649         let indent_str = shape
650             .block()
651             .indent
652             .to_string_with_newline(self.context.config);
653         let mut result = String::with_capacity(
654             self.ident.len() + items_str.len() + 2 + indent_str.len() + nested_indent_str.len(),
655         );
656         result.push_str(self.ident);
657         result.push_str(prefix);
658         let force_single_line = if self.context.config.version() == Version::Two {
659             !self.context.use_block_indent() || (is_extendable && extend_width <= shape.width)
660         } else {
661             // 2 = `()`
662             let fits_one_line = items_str.len() + 2 <= shape.width;
663             !self.context.use_block_indent()
664                 || (self.context.inside_macro() && !items_str.contains('\n') && fits_one_line)
665                 || (is_extendable && extend_width <= shape.width)
666         };
667         if force_single_line {
668             result.push_str(items_str);
669         } else {
670             if !items_str.is_empty() {
671                 result.push_str(&nested_indent_str);
672                 result.push_str(items_str);
673             }
674             result.push_str(&indent_str);
675         }
676         result.push_str(suffix);
677         result
678     }
679
680     fn rewrite(&self, shape: Shape) -> Option<String> {
681         let (extendable, items_str) = self.rewrite_items()?;
682
683         // If we are using visual indent style and failed to format, retry with block indent.
684         if !self.context.use_block_indent()
685             && need_block_indent(&items_str, self.nested_shape)
686             && !extendable
687         {
688             self.context.use_block.replace(true);
689             let result = self.rewrite(shape);
690             self.context.use_block.replace(false);
691             return result;
692         }
693
694         Some(self.wrap_items(&items_str, shape, extendable))
695     }
696 }
697
698 fn need_block_indent(s: &str, shape: Shape) -> bool {
699     s.lines().skip(1).any(|s| {
700         s.find(|c| !char::is_whitespace(c))
701             .map_or(false, |w| w + 1 < shape.indent.width())
702     })
703 }
704
705 fn can_be_overflowed(context: &RewriteContext, items: &[OverflowableItem]) -> bool {
706     items
707         .last()
708         .map_or(false, |x| x.can_be_overflowed(context, items.len()))
709 }
710
711 /// Returns a shape for the last argument which is going to be overflowed.
712 fn last_item_shape(
713     lists: &[OverflowableItem],
714     items: &[ListItem],
715     shape: Shape,
716     args_max_width: usize,
717 ) -> Option<Shape> {
718     if items.len() == 1 && !lists.get(0)?.is_nested_call() {
719         return Some(shape);
720     }
721     let offset = items.iter().rev().skip(1).fold(0, |acc, i| {
722         // 2 = ", "
723         acc + 2 + i.inner_as_ref().len()
724     });
725     Shape {
726         width: min(args_max_width, shape.width),
727         ..shape
728     }
729     .offset_left(offset)
730 }
731
732 fn shape_from_indent_style(
733     context: &RewriteContext,
734     shape: Shape,
735     overhead: usize,
736     offset: usize,
737 ) -> Shape {
738     let (shape, overhead) = if context.use_block_indent() {
739         let shape = shape
740             .block()
741             .block_indent(context.config.tab_spaces())
742             .with_max_width(context.config);
743         (shape, 1) // 1 = ","
744     } else {
745         (shape.visual_indent(offset), overhead)
746     };
747     Shape {
748         width: shape.width.saturating_sub(overhead),
749         ..shape
750     }
751 }
752
753 fn no_long_items(list: &[ListItem]) -> bool {
754     list.iter()
755         .all(|item| item.inner_as_ref().len() <= SHORT_ITEM_THRESHOLD)
756 }
757
758 /// In case special-case style is required, returns an offset from which we start horizontal layout.
759 pub fn maybe_get_args_offset(callee_str: &str, args: &[OverflowableItem]) -> Option<(bool, usize)> {
760     if let Some(&(_, num_args_before)) = args
761         .get(0)?
762         .whitelist()
763         .iter()
764         .find(|&&(s, _)| s == callee_str)
765     {
766         let all_simple = args.len() > num_args_before
767             && is_every_expr_simple(&args[0..num_args_before])
768             && is_every_expr_simple(&args[num_args_before + 1..]);
769
770         Some((all_simple, num_args_before))
771     } else {
772         None
773     }
774 }