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