]> git.lizzy.rs Git - rust.git/blob - src/overflow.rs
Cargo fmt
[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 // FIXME: Replace `ToExpr` with some enum.
13
14 use config::lists::*;
15 use syntax::ast;
16 use syntax::codemap::Span;
17 use syntax::parse::token::DelimToken;
18
19 use closures;
20 use codemap::SpanUtils;
21 use expr::{is_every_expr_simple, is_nested_call, maybe_get_args_offset, ToExpr};
22 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator};
23 use rewrite::{Rewrite, RewriteContext};
24 use shape::Shape;
25 use spanned::Spanned;
26 use utils::{
27     count_newlines, extra_offset, first_line_width, last_line_width, mk_sp, paren_overhead,
28 };
29
30 use std::cmp::min;
31
32 const SHORT_ITEM_THRESHOLD: usize = 10;
33
34 pub fn rewrite_with_parens<T>(
35     context: &RewriteContext,
36     ident: &str,
37     items: &[&T],
38     shape: Shape,
39     span: Span,
40     item_max_width: usize,
41     force_separator_tactic: Option<SeparatorTactic>,
42 ) -> Option<String>
43 where
44     T: Rewrite + ToExpr + Spanned,
45 {
46     Context::new(
47         context,
48         items,
49         ident,
50         shape,
51         span,
52         "(",
53         ")",
54         item_max_width,
55         force_separator_tactic,
56         None,
57     ).rewrite(shape)
58 }
59
60 pub fn rewrite_with_angle_brackets<T>(
61     context: &RewriteContext,
62     ident: &str,
63     items: &[&T],
64     shape: Shape,
65     span: Span,
66 ) -> Option<String>
67 where
68     T: Rewrite + ToExpr + Spanned,
69 {
70     Context::new(
71         context,
72         items,
73         ident,
74         shape,
75         span,
76         "<",
77         ">",
78         context.config.max_width(),
79         None,
80         None,
81     ).rewrite(shape)
82 }
83
84 pub fn rewrite_with_square_brackets<T>(
85     context: &RewriteContext,
86     name: &str,
87     items: &[&T],
88     shape: Shape,
89     span: Span,
90     force_separator_tactic: Option<SeparatorTactic>,
91     delim_token: Option<DelimToken>,
92 ) -> Option<String>
93 where
94     T: Rewrite + ToExpr + Spanned,
95 {
96     let (lhs, rhs) = match delim_token {
97         Some(DelimToken::Paren) => ("(", ")"),
98         Some(DelimToken::Brace) => ("{", "}"),
99         _ => ("[", "]"),
100     };
101     Context::new(
102         context,
103         items,
104         name,
105         shape,
106         span,
107         lhs,
108         rhs,
109         context.config.width_heuristics().array_width,
110         force_separator_tactic,
111         Some(("[", "]")),
112     ).rewrite(shape)
113 }
114
115 struct Context<'a, T: 'a> {
116     context: &'a RewriteContext<'a>,
117     items: &'a [&'a T],
118     ident: &'a str,
119     prefix: &'static str,
120     suffix: &'static str,
121     one_line_shape: Shape,
122     nested_shape: Shape,
123     span: Span,
124     item_max_width: usize,
125     one_line_width: usize,
126     force_separator_tactic: Option<SeparatorTactic>,
127     custom_delims: Option<(&'a str, &'a str)>,
128 }
129
130 impl<'a, T: 'a + Rewrite + ToExpr + Spanned> Context<'a, T> {
131     pub fn new(
132         context: &'a RewriteContext,
133         items: &'a [&'a T],
134         ident: &'a str,
135         shape: Shape,
136         span: Span,
137         prefix: &'static str,
138         suffix: &'static str,
139         item_max_width: usize,
140         force_separator_tactic: Option<SeparatorTactic>,
141         custom_delims: Option<(&'a str, &'a str)>,
142     ) -> Context<'a, T> {
143         // 2 = `( `, 1 = `(`
144         let paren_overhead = if context.config.spaces_within_parens_and_brackets() {
145             2
146         } else {
147             1
148         };
149         let used_width = extra_offset(ident, shape);
150         let one_line_width = shape
151             .width
152             .checked_sub(used_width + 2 * paren_overhead)
153             .unwrap_or(0);
154
155         // 1 = "(" or ")"
156         let one_line_shape = shape
157             .offset_left(last_line_width(ident) + 1)
158             .and_then(|shape| shape.sub_width(1))
159             .unwrap_or(Shape { width: 0, ..shape });
160         let nested_shape = shape_from_indent_style(
161             context,
162             shape,
163             used_width + 2 * paren_overhead,
164             used_width + paren_overhead,
165         );
166         Context {
167             context,
168             items,
169             ident,
170             one_line_shape,
171             nested_shape,
172             span,
173             prefix,
174             suffix,
175             item_max_width,
176             one_line_width,
177             force_separator_tactic,
178             custom_delims,
179         }
180     }
181
182     fn last_item(&self) -> Option<&&T> {
183         self.items.last()
184     }
185
186     fn items_span(&self) -> Span {
187         let span_lo = self
188             .context
189             .snippet_provider
190             .span_after(self.span, self.prefix);
191         mk_sp(span_lo, self.span.hi())
192     }
193
194     fn rewrite_last_item_with_overflow(
195         &self,
196         last_list_item: &mut ListItem,
197         shape: Shape,
198     ) -> Option<String> {
199         let last_item = self.last_item()?;
200         let rewrite = if let Some(expr) = last_item.to_expr() {
201             match expr.node {
202                 // When overflowing the closure which consists of a single control flow expression,
203                 // force to use block if its condition uses multi line.
204                 ast::ExprKind::Closure(..) => {
205                     // If the argument consists of multiple closures, we do not overflow
206                     // the last closure.
207                     if closures::args_have_many_closure(self.items) {
208                         None
209                     } else {
210                         closures::rewrite_last_closure(self.context, expr, shape)
211                     }
212                 }
213                 _ => expr.rewrite(self.context, shape),
214             }
215         } else {
216             last_item.rewrite(self.context, shape)
217         };
218
219         if let Some(rewrite) = rewrite {
220             let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
221             last_list_item.item = rewrite_first_line;
222             Some(rewrite)
223         } else {
224             None
225         }
226     }
227
228     fn default_tactic(&self, list_items: &[ListItem]) -> DefinitiveListTactic {
229         definitive_tactic(
230             list_items,
231             ListTactic::LimitedHorizontalVertical(self.item_max_width),
232             Separator::Comma,
233             self.one_line_width,
234         )
235     }
236
237     fn try_overflow_last_item(&self, list_items: &mut Vec<ListItem>) -> DefinitiveListTactic {
238         // 1 = "("
239         let combine_arg_with_callee = self.items.len() == 1
240             && self.items[0].to_expr().is_some()
241             && self.ident.len() + 1 <= self.context.config.tab_spaces();
242         let overflow_last = combine_arg_with_callee || can_be_overflowed(self.context, self.items);
243
244         // Replace the last item with its first line to see if it fits with
245         // first arguments.
246         let placeholder = if overflow_last {
247             let old_value = *self.context.force_one_line_chain.borrow();
248             if !combine_arg_with_callee {
249                 if let Some(expr) = self.last_item().and_then(|item| item.to_expr()) {
250                     if let ast::ExprKind::MethodCall(..) = expr.node {
251                         self.context.force_one_line_chain.replace(true);
252                     }
253                 }
254             }
255             let result = last_item_shape(
256                 self.items,
257                 list_items,
258                 self.one_line_shape,
259                 self.item_max_width,
260             ).and_then(|arg_shape| {
261                 self.rewrite_last_item_with_overflow(
262                     &mut list_items[self.items.len() - 1],
263                     arg_shape,
264                 )
265             });
266             self.context.force_one_line_chain.replace(old_value);
267             result
268         } else {
269             None
270         };
271
272         let mut tactic = definitive_tactic(
273             &*list_items,
274             ListTactic::LimitedHorizontalVertical(self.item_max_width),
275             Separator::Comma,
276             self.one_line_width,
277         );
278
279         // Replace the stub with the full overflowing last argument if the rewrite
280         // succeeded and its first line fits with the other arguments.
281         match (overflow_last, tactic, placeholder) {
282             (true, DefinitiveListTactic::Horizontal, Some(ref overflowed))
283                 if self.items.len() == 1 =>
284             {
285                 // When we are rewriting a nested function call, we restrict the
286                 // budget for the inner function to avoid them being deeply nested.
287                 // However, when the inner function has a prefix or a suffix
288                 // (e.g. `foo() as u32`), this budget reduction may produce poorly
289                 // formatted code, where a prefix or a suffix being left on its own
290                 // line. Here we explicitlly check those cases.
291                 if count_newlines(overflowed) == 1 {
292                     let rw = self
293                         .items
294                         .last()
295                         .and_then(|last_item| last_item.rewrite(self.context, self.nested_shape));
296                     let no_newline = rw.as_ref().map_or(false, |s| !s.contains('\n'));
297                     if no_newline {
298                         list_items[self.items.len() - 1].item = rw;
299                     } else {
300                         list_items[self.items.len() - 1].item = Some(overflowed.to_owned());
301                     }
302                 } else {
303                     list_items[self.items.len() - 1].item = Some(overflowed.to_owned());
304                 }
305             }
306             (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
307                 list_items[self.items.len() - 1].item = placeholder;
308             }
309             _ if self.items.len() >= 1 => {
310                 list_items[self.items.len() - 1].item = self
311                     .items
312                     .last()
313                     .and_then(|last_item| last_item.rewrite(self.context, self.nested_shape));
314
315                 // Use horizontal layout for a function with a single argument as long as
316                 // everything fits in a single line.
317                 // `self.one_line_width == 0` means vertical layout is forced.
318                 if self.items.len() == 1
319                     && self.one_line_width != 0
320                     && !list_items[0].has_comment()
321                     && !list_items[0].inner_as_ref().contains('\n')
322                     && ::lists::total_item_width(&list_items[0]) <= self.one_line_width
323                 {
324                     tactic = DefinitiveListTactic::Horizontal;
325                 } else {
326                     tactic = self.default_tactic(list_items);
327
328                     if tactic == DefinitiveListTactic::Vertical {
329                         if let Some((all_simple, num_args_before)) =
330                             maybe_get_args_offset(self.ident, self.items)
331                         {
332                             let one_line = all_simple
333                                 && definitive_tactic(
334                                     &list_items[..num_args_before],
335                                     ListTactic::HorizontalVertical,
336                                     Separator::Comma,
337                                     self.nested_shape.width,
338                                 )
339                                     == DefinitiveListTactic::Horizontal
340                                 && definitive_tactic(
341                                     &list_items[num_args_before + 1..],
342                                     ListTactic::HorizontalVertical,
343                                     Separator::Comma,
344                                     self.nested_shape.width,
345                                 )
346                                     == DefinitiveListTactic::Horizontal;
347
348                             if one_line {
349                                 tactic = DefinitiveListTactic::SpecialMacro(num_args_before);
350                             };
351                         } else if is_every_expr_simple(self.items) && no_long_items(list_items) {
352                             tactic = DefinitiveListTactic::Mixed;
353                         }
354                     }
355                 }
356             }
357             _ => (),
358         }
359
360         tactic
361     }
362
363     fn rewrite_items(&self) -> Option<(bool, String)> {
364         let span = self.items_span();
365         let items = itemize_list(
366             self.context.snippet_provider,
367             self.items.iter(),
368             self.suffix,
369             ",",
370             |item| item.span().lo(),
371             |item| item.span().hi(),
372             |item| item.rewrite(self.context, self.nested_shape),
373             span.lo(),
374             span.hi(),
375             true,
376         );
377         let mut list_items: Vec<_> = items.collect();
378
379         // Try letting the last argument overflow to the next line with block
380         // indentation. If its first line fits on one line with the other arguments,
381         // we format the function arguments horizontally.
382         let tactic = self.try_overflow_last_item(&mut list_items);
383
384         let fmt = ListFormatting {
385             tactic,
386             separator: ",",
387             trailing_separator: if let Some(tactic) = self.force_separator_tactic {
388                 tactic
389             } else if !self.context.use_block_indent() {
390                 SeparatorTactic::Never
391             } else if tactic == DefinitiveListTactic::Mixed {
392                 // We are using mixed layout because everything did not fit within a single line.
393                 SeparatorTactic::Always
394             } else {
395                 self.context.config.trailing_comma()
396             },
397             separator_place: SeparatorPlace::Back,
398             shape: self.nested_shape,
399             ends_with_newline: match tactic {
400                 DefinitiveListTactic::Vertical | DefinitiveListTactic::Mixed => {
401                     self.context.use_block_indent()
402                 }
403                 _ => false,
404             },
405             preserve_newline: false,
406             config: self.context.config,
407         };
408
409         write_list(&list_items, &fmt)
410             .map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str))
411     }
412
413     fn wrap_items(&self, items_str: &str, shape: Shape, is_extendable: bool) -> String {
414         let shape = Shape {
415             width: shape
416                 .width
417                 .checked_sub(last_line_width(self.ident))
418                 .unwrap_or(0),
419             ..shape
420         };
421
422         let (prefix, suffix) = match self.custom_delims {
423             Some((lhs, rhs)) => (lhs, rhs),
424             _ => (self.prefix, self.suffix),
425         };
426         let paren_overhead = paren_overhead(self.context);
427         let fits_one_line = items_str.len() + paren_overhead <= shape.width;
428         let extend_width = if items_str.is_empty() {
429             paren_overhead
430         } else {
431             first_line_width(items_str) + (paren_overhead / 2)
432         };
433         let nested_indent_str = self
434             .nested_shape
435             .indent
436             .to_string_with_newline(self.context.config);
437         let indent_str = shape
438             .block()
439             .indent
440             .to_string_with_newline(self.context.config);
441         let mut result = String::with_capacity(
442             self.ident.len() + items_str.len() + 2 + indent_str.len() + nested_indent_str.len(),
443         );
444         result.push_str(self.ident);
445         result.push_str(prefix);
446         if !self.context.use_block_indent()
447             || (self.context.inside_macro() && !items_str.contains('\n') && fits_one_line)
448             || (is_extendable && extend_width <= shape.width)
449         {
450             if self.context.config.spaces_within_parens_and_brackets() && !items_str.is_empty() {
451                 result.push(' ');
452                 result.push_str(items_str);
453                 result.push(' ');
454             } else {
455                 result.push_str(items_str);
456             }
457         } else {
458             if !items_str.is_empty() {
459                 result.push_str(&nested_indent_str);
460                 result.push_str(items_str);
461             }
462             result.push_str(&indent_str);
463         }
464         result.push_str(suffix);
465         result
466     }
467
468     fn rewrite(&self, shape: Shape) -> Option<String> {
469         let (extendable, items_str) = self.rewrite_items()?;
470
471         // If we are using visual indent style and failed to format, retry with block indent.
472         if !self.context.use_block_indent()
473             && need_block_indent(&items_str, self.nested_shape)
474             && !extendable
475         {
476             self.context.use_block.replace(true);
477             let result = self.rewrite(shape);
478             self.context.use_block.replace(false);
479             return result;
480         }
481
482         Some(self.wrap_items(&items_str, shape, extendable))
483     }
484 }
485
486 fn need_block_indent(s: &str, shape: Shape) -> bool {
487     s.lines().skip(1).any(|s| {
488         s.find(|c| !char::is_whitespace(c))
489             .map_or(false, |w| w + 1 < shape.indent.width())
490     })
491 }
492
493 fn can_be_overflowed<'a, T>(context: &RewriteContext, items: &[&T]) -> bool
494 where
495     T: Rewrite + Spanned + ToExpr + 'a,
496 {
497     items
498         .last()
499         .map_or(false, |x| x.can_be_overflowed(context, items.len()))
500 }
501
502 /// Returns a shape for the last argument which is going to be overflowed.
503 fn last_item_shape<T>(
504     lists: &[&T],
505     items: &[ListItem],
506     shape: Shape,
507     args_max_width: usize,
508 ) -> Option<Shape>
509 where
510     T: Rewrite + Spanned + ToExpr,
511 {
512     let is_nested_call = lists
513         .iter()
514         .next()
515         .and_then(|item| item.to_expr())
516         .map_or(false, is_nested_call);
517     if items.len() == 1 && !is_nested_call {
518         return Some(shape);
519     }
520     let offset = items.iter().rev().skip(1).fold(0, |acc, i| {
521         // 2 = ", "
522         acc + 2 + i.inner_as_ref().len()
523     });
524     Shape {
525         width: min(args_max_width, shape.width),
526         ..shape
527     }.offset_left(offset)
528 }
529
530 fn shape_from_indent_style(
531     context: &RewriteContext,
532     shape: Shape,
533     overhead: usize,
534     offset: usize,
535 ) -> Shape {
536     if context.use_block_indent() {
537         // 1 = ","
538         shape
539             .block()
540             .block_indent(context.config.tab_spaces())
541             .with_max_width(context.config)
542             .sub_width(1)
543             .unwrap()
544     } else {
545         let shape = shape.visual_indent(offset);
546         if let Some(shape) = shape.sub_width(overhead) {
547             shape
548         } else {
549             Shape { width: 0, ..shape }
550         }
551     }
552 }
553
554 fn no_long_items(list: &[ListItem]) -> bool {
555     list.iter()
556         .all(|item| !item.has_comment() && item.inner_as_ref().len() <= SHORT_ITEM_THRESHOLD)
557 }