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