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.
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.
11 //! Rewrite a list some items with overflow.
12 // FIXME: Replace `ToExpr` with some enum.
16 use syntax::parse::token::DelimToken;
17 use syntax::source_map::Span;
20 use expr::{is_every_expr_simple, is_method_call, is_nested_call, maybe_get_args_offset, ToExpr};
21 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator};
22 use rewrite::{Rewrite, RewriteContext};
24 use source_map::SpanUtils;
26 use utils::{count_newlines, extra_offset, first_line_width, last_line_width, mk_sp};
30 const SHORT_ITEM_THRESHOLD: usize = 10;
32 pub fn rewrite_with_parens<T>(
33 context: &RewriteContext,
38 item_max_width: usize,
39 force_separator_tactic: Option<SeparatorTactic>,
42 T: Rewrite + ToExpr + Spanned,
53 force_separator_tactic,
58 pub fn rewrite_with_angle_brackets<T>(
59 context: &RewriteContext,
66 T: Rewrite + ToExpr + Spanned,
76 context.config.max_width(),
82 pub fn rewrite_with_square_brackets<T>(
83 context: &RewriteContext,
88 force_separator_tactic: Option<SeparatorTactic>,
89 delim_token: Option<DelimToken>,
92 T: Rewrite + ToExpr + Spanned,
94 let (lhs, rhs) = match delim_token {
95 Some(DelimToken::Paren) => ("(", ")"),
96 Some(DelimToken::Brace) => ("{", "}"),
107 context.config.width_heuristics().array_width,
108 force_separator_tactic,
113 struct Context<'a, T: 'a> {
114 context: &'a RewriteContext<'a>,
117 prefix: &'static str,
118 suffix: &'static str,
119 one_line_shape: Shape,
122 item_max_width: usize,
123 one_line_width: usize,
124 force_separator_tactic: Option<SeparatorTactic>,
125 custom_delims: Option<(&'a str, &'a str)>,
128 impl<'a, T: 'a + Rewrite + ToExpr + Spanned> Context<'a, T> {
130 context: &'a RewriteContext,
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);
143 let one_line_width = shape.width.saturating_sub(used_width + 2);
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);
162 force_separator_tactic,
167 fn last_item(&self) -> Option<&&T> {
171 fn items_span(&self) -> Span {
175 .span_after(self.span, self.prefix);
176 mk_sp(span_lo, self.span.hi())
179 fn rewrite_last_item_with_overflow(
181 last_list_item: &mut ListItem,
183 ) -> Option<String> {
184 let last_item = self.last_item()?;
185 let rewrite = if let Some(expr) = last_item.to_expr() {
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
192 if closures::args_have_many_closure(self.items) {
195 closures::rewrite_last_closure(self.context, expr, shape)
198 _ => expr.rewrite(self.context, shape),
201 last_item.rewrite(self.context, shape)
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;
213 fn default_tactic(&self, list_items: &[ListItem]) -> DefinitiveListTactic {
216 ListTactic::LimitedHorizontalVertical(self.item_max_width),
222 fn try_overflow_last_item(&self, list_items: &mut Vec<ListItem>) -> DefinitiveListTactic {
224 let combine_arg_with_callee = self.items.len() == 1
225 && self.items[0].to_expr().is_some()
226 && self.ident.len() < self.context.config.tab_spaces();
227 let overflow_last = combine_arg_with_callee || can_be_overflowed(self.context, self.items);
229 // Replace the last item with its first line to see if it fits with
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);
240 let result = last_item_shape(
245 ).and_then(|arg_shape| {
246 self.rewrite_last_item_with_overflow(
247 &mut list_items[self.items.len() - 1],
251 self.context.force_one_line_chain.replace(old_value);
257 let mut tactic = definitive_tactic(
259 ListTactic::LimitedHorizontalVertical(self.item_max_width),
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 =>
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 {
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'));
283 list_items[self.items.len() - 1].item = rw;
285 list_items[self.items.len() - 1].item = Some(overflowed.to_owned());
288 list_items[self.items.len() - 1].item = Some(overflowed.to_owned());
291 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
292 list_items[self.items.len() - 1].item = placeholder;
294 _ if !self.items.is_empty() => {
295 list_items[self.items.len() - 1].item = self
298 .and_then(|last_item| last_item.rewrite(self.context, self.nested_shape));
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
309 tactic = DefinitiveListTactic::Horizontal;
311 tactic = self.default_tactic(list_items);
313 if tactic == DefinitiveListTactic::Vertical {
314 if let Some((all_simple, num_args_before)) =
315 maybe_get_args_offset(self.ident, self.items)
317 let one_line = all_simple
318 && definitive_tactic(
319 &list_items[..num_args_before],
320 ListTactic::HorizontalVertical,
322 self.nested_shape.width,
323 ) == DefinitiveListTactic::Horizontal
324 && definitive_tactic(
325 &list_items[num_args_before + 1..],
326 ListTactic::HorizontalVertical,
328 self.nested_shape.width,
329 ) == DefinitiveListTactic::Horizontal;
332 tactic = DefinitiveListTactic::SpecialMacro(num_args_before);
334 } else if is_every_expr_simple(self.items) && no_long_items(list_items) {
335 tactic = DefinitiveListTactic::Mixed;
346 fn rewrite_items(&self) -> Option<(bool, String)> {
347 let span = self.items_span();
348 let items = itemize_list(
349 self.context.snippet_provider,
353 |item| item.span().lo(),
354 |item| item.span().hi(),
355 |item| item.rewrite(self.context, self.nested_shape),
360 let mut list_items: Vec<_> = items.collect();
362 // Try letting the last argument overflow to the next line with block
363 // indentation. If its first line fits on one line with the other arguments,
364 // we format the function arguments horizontally.
365 let tactic = self.try_overflow_last_item(&mut list_items);
366 let trailing_separator = if let Some(tactic) = self.force_separator_tactic {
368 } else if !self.context.use_block_indent() {
369 SeparatorTactic::Never
370 } else if tactic == DefinitiveListTactic::Mixed {
371 // We are using mixed layout because everything did not fit within a single line.
372 SeparatorTactic::Always
374 self.context.config.trailing_comma()
376 let ends_with_newline = match tactic {
377 DefinitiveListTactic::Vertical | DefinitiveListTactic::Mixed => {
378 self.context.use_block_indent()
383 let fmt = ListFormatting::new(self.nested_shape, self.context.config)
385 .trailing_separator(trailing_separator)
386 .ends_with_newline(ends_with_newline);
388 write_list(&list_items, &fmt)
389 .map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str))
392 fn wrap_items(&self, items_str: &str, shape: Shape, is_extendable: bool) -> String {
394 width: shape.width.saturating_sub(last_line_width(self.ident)),
398 let (prefix, suffix) = match self.custom_delims {
399 Some((lhs, rhs)) => (lhs, rhs),
400 _ => (self.prefix, self.suffix),
404 let fits_one_line = items_str.len() + 2 <= shape.width;
405 let extend_width = if items_str.is_empty() {
408 first_line_width(items_str) + 1
410 let nested_indent_str = self
413 .to_string_with_newline(self.context.config);
414 let indent_str = shape
417 .to_string_with_newline(self.context.config);
418 let mut result = String::with_capacity(
419 self.ident.len() + items_str.len() + 2 + indent_str.len() + nested_indent_str.len(),
421 result.push_str(self.ident);
422 result.push_str(prefix);
423 if !self.context.use_block_indent()
424 || (self.context.inside_macro() && !items_str.contains('\n') && fits_one_line)
425 || (is_extendable && extend_width <= shape.width)
427 result.push_str(items_str);
429 if !items_str.is_empty() {
430 result.push_str(&nested_indent_str);
431 result.push_str(items_str);
433 result.push_str(&indent_str);
435 result.push_str(suffix);
439 fn rewrite(&self, shape: Shape) -> Option<String> {
440 let (extendable, items_str) = self.rewrite_items()?;
442 // If we are using visual indent style and failed to format, retry with block indent.
443 if !self.context.use_block_indent()
444 && need_block_indent(&items_str, self.nested_shape)
447 self.context.use_block.replace(true);
448 let result = self.rewrite(shape);
449 self.context.use_block.replace(false);
453 Some(self.wrap_items(&items_str, shape, extendable))
457 fn need_block_indent(s: &str, shape: Shape) -> bool {
458 s.lines().skip(1).any(|s| {
459 s.find(|c| !char::is_whitespace(c))
460 .map_or(false, |w| w + 1 < shape.indent.width())
464 fn can_be_overflowed<'a, T>(context: &RewriteContext, items: &[&T]) -> bool
466 T: Rewrite + Spanned + ToExpr + 'a,
470 .map_or(false, |x| x.can_be_overflowed(context, items.len()))
473 /// Returns a shape for the last argument which is going to be overflowed.
474 fn last_item_shape<T>(
478 args_max_width: usize,
481 T: Rewrite + Spanned + ToExpr,
483 let is_nested_call = lists
486 .and_then(|item| item.to_expr())
487 .map_or(false, is_nested_call);
488 if items.len() == 1 && !is_nested_call {
491 let offset = items.iter().rev().skip(1).fold(0, |acc, i| {
493 acc + 2 + i.inner_as_ref().len()
496 width: min(args_max_width, shape.width),
498 }.offset_left(offset)
501 fn shape_from_indent_style(
502 context: &RewriteContext,
507 let (shape, overhead) = if context.use_block_indent() {
510 .block_indent(context.config.tab_spaces())
511 .with_max_width(context.config);
512 (shape, 1) // 1 = ","
514 (shape.visual_indent(offset), overhead)
517 width: shape.width.saturating_sub(overhead),
522 fn no_long_items(list: &[ListItem]) -> bool {
524 .all(|item| item.inner_as_ref().len() <= SHORT_ITEM_THRESHOLD)