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.
14 use syntax::parse::token::DelimToken;
15 use syntax::source_map::Span;
16 use syntax::{ast, ptr};
20 can_be_overflowed_expr, is_every_expr_simple, is_method_call, is_nested_call, is_simple_expr,
22 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator};
24 use patterns::{can_be_overflowed_pat, TuplePatField};
25 use rewrite::{Rewrite, RewriteContext};
27 use source_map::SpanUtils;
29 use types::{can_be_overflowed_type, SegmentParam};
30 use utils::{count_newlines, extra_offset, first_line_width, last_line_width, mk_sp};
34 const SHORT_ITEM_THRESHOLD: usize = 10;
36 /// A list of `format!`-like macros, that take a long format string and a list of arguments to
39 /// Organized as a list of `(&str, usize)` tuples, giving the name of the macro and the number of
40 /// arguments before the format string (none for `format!("format", ...)`, one for `assert!(result,
41 /// "format", ...)`, two for `assert_eq!(left, right, "format", ...)`).
42 const SPECIAL_MACRO_WHITELIST: &[(&str, usize)] = &[
43 // format! like macros
44 // From the Rust Standard Library.
53 // From the `log` crate.
63 // assert_eq! like macros
66 ("debug_assert_eq!", 2),
67 ("debug_assert_ne!", 2),
70 pub enum OverflowableItem<'a> {
72 GenericParam(&'a ast::GenericParam),
73 MacroArg(&'a MacroArg),
74 SegmentParam(&'a SegmentParam<'a>),
75 StructField(&'a ast::StructField),
76 TuplePatField(&'a TuplePatField<'a>),
80 impl<'a> Rewrite for OverflowableItem<'a> {
81 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
82 self.map(|item| item.rewrite(context, shape))
86 impl<'a> Spanned for OverflowableItem<'a> {
87 fn span(&self) -> Span {
88 self.map(|item| item.span())
92 impl<'a> OverflowableItem<'a> {
93 pub fn map<F, T>(&self, f: F) -> T
95 F: Fn(&IntoOverflowableItem<'a>) -> T,
98 OverflowableItem::Expr(expr) => f(*expr),
99 OverflowableItem::GenericParam(gp) => f(*gp),
100 OverflowableItem::MacroArg(macro_arg) => f(*macro_arg),
101 OverflowableItem::SegmentParam(sp) => f(*sp),
102 OverflowableItem::StructField(sf) => f(*sf),
103 OverflowableItem::TuplePatField(pat) => f(*pat),
104 OverflowableItem::Ty(ty) => f(*ty),
108 pub fn is_simple(&self) -> bool {
110 OverflowableItem::Expr(expr) => is_simple_expr(expr),
111 OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_simple_expr(expr),
116 pub fn is_expr(&self) -> bool {
118 OverflowableItem::Expr(..) => true,
119 OverflowableItem::MacroArg(MacroArg::Expr(..)) => true,
124 pub fn is_nested_call(&self) -> bool {
126 OverflowableItem::Expr(expr) => is_nested_call(expr),
127 OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_nested_call(expr),
132 pub fn to_expr(&self) -> Option<&'a ast::Expr> {
134 OverflowableItem::Expr(expr) => Some(expr),
135 OverflowableItem::MacroArg(macro_arg) => match macro_arg {
136 MacroArg::Expr(ref expr) => Some(expr),
143 pub fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
145 OverflowableItem::Expr(expr) => can_be_overflowed_expr(context, expr, len),
146 OverflowableItem::MacroArg(macro_arg) => match macro_arg {
147 MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
148 MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
149 MacroArg::Pat(..) => false,
150 MacroArg::Item(..) => len == 1,
152 OverflowableItem::SegmentParam(seg) => match seg {
153 SegmentParam::Type(ty) => can_be_overflowed_type(context, ty, len),
156 OverflowableItem::TuplePatField(pat) => can_be_overflowed_pat(context, pat, len),
157 OverflowableItem::Ty(ty) => can_be_overflowed_type(context, ty, len),
163 pub trait IntoOverflowableItem<'a>: Rewrite + Spanned {
164 fn into_overflowable_item(&'a self) -> OverflowableItem<'a>;
167 impl<'a, T: 'a + IntoOverflowableItem<'a>> IntoOverflowableItem<'a> for ptr::P<T> {
168 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
169 (**self).into_overflowable_item()
173 macro impl_into_overflowable_item_for_ast_node {
174 ($($ast_node:ident),*) => {
176 impl<'a> IntoOverflowableItem<'a> for ast::$ast_node {
177 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
178 OverflowableItem::$ast_node(self)
185 macro impl_into_overflowable_item_for_rustfmt_types {
186 ([$($ty:ident),*], [$($ty_with_lifetime:ident),*]) => {
188 impl<'a> IntoOverflowableItem<'a> for $ty {
189 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
190 OverflowableItem::$ty(self)
195 impl<'a> IntoOverflowableItem<'a> for $ty_with_lifetime<'a> {
196 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
197 OverflowableItem::$ty_with_lifetime(self)
204 impl_into_overflowable_item_for_ast_node!(Expr, GenericParam, StructField, Ty);
205 impl_into_overflowable_item_for_rustfmt_types!([MacroArg], [SegmentParam, TuplePatField]);
207 pub fn into_overflowable_list<'a, T>(
208 iter: impl Iterator<Item = &'a T>,
209 ) -> impl Iterator<Item = OverflowableItem<'a>>
211 T: 'a + IntoOverflowableItem<'a>,
213 iter.map(|x| IntoOverflowableItem::into_overflowable_item(x))
216 pub fn rewrite_with_parens<'a, T: 'a + IntoOverflowableItem<'a>>(
217 context: &'a RewriteContext,
219 items: impl Iterator<Item = &'a T>,
222 item_max_width: usize,
223 force_separator_tactic: Option<SeparatorTactic>,
224 ) -> Option<String> {
234 force_separator_tactic,
240 pub fn rewrite_with_angle_brackets<'a, T: 'a + IntoOverflowableItem<'a>>(
241 context: &'a RewriteContext,
243 items: impl Iterator<Item = &'a T>,
246 ) -> Option<String> {
255 context.config.max_width(),
262 pub fn rewrite_with_square_brackets<'a, T: 'a + IntoOverflowableItem<'a>>(
263 context: &'a RewriteContext,
265 items: impl Iterator<Item = &'a T>,
268 force_separator_tactic: Option<SeparatorTactic>,
269 delim_token: Option<DelimToken>,
270 ) -> Option<String> {
271 let (lhs, rhs) = match delim_token {
272 Some(DelimToken::Paren) => ("(", ")"),
273 Some(DelimToken::Brace) => ("{", "}"),
284 context.config.width_heuristics().array_width,
285 force_separator_tactic,
292 context: &'a RewriteContext<'a>,
293 items: Vec<OverflowableItem<'a>>,
295 prefix: &'static str,
296 suffix: &'static str,
297 one_line_shape: Shape,
300 item_max_width: usize,
301 one_line_width: usize,
302 force_separator_tactic: Option<SeparatorTactic>,
303 custom_delims: Option<(&'a str, &'a str)>,
306 impl<'a> Context<'a> {
307 pub fn new<T: 'a + IntoOverflowableItem<'a>>(
308 context: &'a RewriteContext,
309 items: impl Iterator<Item = &'a T>,
313 prefix: &'static str,
314 suffix: &'static str,
315 item_max_width: usize,
316 force_separator_tactic: Option<SeparatorTactic>,
317 custom_delims: Option<(&'a str, &'a str)>,
319 let used_width = extra_offset(ident, shape);
321 let one_line_width = shape.width.saturating_sub(used_width + 2);
324 let one_line_shape = shape
325 .offset_left(last_line_width(ident) + 1)
326 .and_then(|shape| shape.sub_width(1))
327 .unwrap_or(Shape { width: 0, ..shape });
328 let nested_shape = shape_from_indent_style(context, shape, used_width + 2, used_width + 1);
331 items: into_overflowable_list(items).collect(),
340 force_separator_tactic,
345 fn last_item(&self) -> Option<&OverflowableItem> {
349 fn items_span(&self) -> Span {
353 .span_after(self.span, self.prefix);
354 mk_sp(span_lo, self.span.hi())
357 fn rewrite_last_item_with_overflow(
359 last_list_item: &mut ListItem,
361 ) -> Option<String> {
362 let last_item = self.last_item()?;
363 let rewrite = match last_item {
364 OverflowableItem::Expr(ref expr) => {
366 // When overflowing the closure which consists of a single control flow
367 // expression, force to use block if its condition uses multi line.
368 ast::ExprKind::Closure(..) => {
369 // If the argument consists of multiple closures, we do not overflow
371 if closures::args_have_many_closure(&self.items) {
374 closures::rewrite_last_closure(self.context, expr, shape)
377 _ => expr.rewrite(self.context, shape),
380 item @ _ => item.rewrite(self.context, shape),
383 if let Some(rewrite) = rewrite {
384 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
385 last_list_item.item = rewrite_first_line;
392 fn default_tactic(&self, list_items: &[ListItem]) -> DefinitiveListTactic {
395 ListTactic::LimitedHorizontalVertical(self.item_max_width),
401 fn try_overflow_last_item(&self, list_items: &mut Vec<ListItem>) -> DefinitiveListTactic {
403 let combine_arg_with_callee = self.items.len() == 1
404 && self.items[0].is_expr()
405 && self.ident.len() < self.context.config.tab_spaces();
406 let overflow_last = combine_arg_with_callee || can_be_overflowed(self.context, &self.items);
408 // Replace the last item with its first line to see if it fits with
410 let placeholder = if overflow_last {
411 let old_value = *self.context.force_one_line_chain.borrow();
412 match self.last_item() {
413 Some(OverflowableItem::Expr(expr))
414 if !combine_arg_with_callee && is_method_call(expr) =>
416 self.context.force_one_line_chain.replace(true);
420 let result = last_item_shape(
426 .and_then(|arg_shape| {
427 self.rewrite_last_item_with_overflow(
428 &mut list_items[self.items.len() - 1],
432 self.context.force_one_line_chain.replace(old_value);
438 let mut tactic = definitive_tactic(
440 ListTactic::LimitedHorizontalVertical(self.item_max_width),
445 // Replace the stub with the full overflowing last argument if the rewrite
446 // succeeded and its first line fits with the other arguments.
447 match (overflow_last, tactic, placeholder) {
448 (true, DefinitiveListTactic::Horizontal, Some(ref overflowed))
449 if self.items.len() == 1 =>
451 // When we are rewriting a nested function call, we restrict the
452 // budget for the inner function to avoid them being deeply nested.
453 // However, when the inner function has a prefix or a suffix
454 // (e.g. `foo() as u32`), this budget reduction may produce poorly
455 // formatted code, where a prefix or a suffix being left on its own
456 // line. Here we explicitlly check those cases.
457 if count_newlines(overflowed) == 1 {
461 .and_then(|last_item| last_item.rewrite(self.context, self.nested_shape));
462 let no_newline = rw.as_ref().map_or(false, |s| !s.contains('\n'));
464 list_items[self.items.len() - 1].item = rw;
466 list_items[self.items.len() - 1].item = Some(overflowed.to_owned());
469 list_items[self.items.len() - 1].item = Some(overflowed.to_owned());
472 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
473 list_items[self.items.len() - 1].item = placeholder;
475 _ if !self.items.is_empty() => {
476 list_items[self.items.len() - 1].item = self
479 .and_then(|last_item| last_item.rewrite(self.context, self.nested_shape));
481 // Use horizontal layout for a function with a single argument as long as
482 // everything fits in a single line.
483 // `self.one_line_width == 0` means vertical layout is forced.
484 if self.items.len() == 1
485 && self.one_line_width != 0
486 && !list_items[0].has_comment()
487 && !list_items[0].inner_as_ref().contains('\n')
488 && ::lists::total_item_width(&list_items[0]) <= self.one_line_width
490 tactic = DefinitiveListTactic::Horizontal;
492 tactic = self.default_tactic(list_items);
494 if tactic == DefinitiveListTactic::Vertical {
495 if let Some((all_simple, num_args_before)) =
496 maybe_get_args_offset(self.ident, &self.items)
498 let one_line = all_simple
499 && definitive_tactic(
500 &list_items[..num_args_before],
501 ListTactic::HorizontalVertical,
503 self.nested_shape.width,
504 ) == DefinitiveListTactic::Horizontal
505 && definitive_tactic(
506 &list_items[num_args_before + 1..],
507 ListTactic::HorizontalVertical,
509 self.nested_shape.width,
510 ) == DefinitiveListTactic::Horizontal;
513 tactic = DefinitiveListTactic::SpecialMacro(num_args_before);
515 } else if is_every_expr_simple(&self.items) && no_long_items(list_items) {
516 tactic = DefinitiveListTactic::Mixed;
527 fn rewrite_items(&self) -> Option<(bool, String)> {
528 let span = self.items_span();
529 let items = itemize_list(
530 self.context.snippet_provider,
534 |item| item.span().lo(),
535 |item| item.span().hi(),
536 |item| item.rewrite(self.context, self.nested_shape),
541 let mut list_items: Vec<_> = items.collect();
543 // Try letting the last argument overflow to the next line with block
544 // indentation. If its first line fits on one line with the other arguments,
545 // we format the function arguments horizontally.
546 let tactic = self.try_overflow_last_item(&mut list_items);
547 let trailing_separator = if let Some(tactic) = self.force_separator_tactic {
549 } else if !self.context.use_block_indent() {
550 SeparatorTactic::Never
551 } else if tactic == DefinitiveListTactic::Mixed {
552 // We are using mixed layout because everything did not fit within a single line.
553 SeparatorTactic::Always
555 self.context.config.trailing_comma()
557 let ends_with_newline = match tactic {
558 DefinitiveListTactic::Vertical | DefinitiveListTactic::Mixed => {
559 self.context.use_block_indent()
564 let fmt = ListFormatting::new(self.nested_shape, self.context.config)
566 .trailing_separator(trailing_separator)
567 .ends_with_newline(ends_with_newline);
569 write_list(&list_items, &fmt)
570 .map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str))
573 fn wrap_items(&self, items_str: &str, shape: Shape, is_extendable: bool) -> String {
575 width: shape.width.saturating_sub(last_line_width(self.ident)),
579 let (prefix, suffix) = match self.custom_delims {
580 Some((lhs, rhs)) => (lhs, rhs),
581 _ => (self.prefix, self.suffix),
585 let fits_one_line = items_str.len() + 2 <= shape.width;
586 let extend_width = if items_str.is_empty() {
589 first_line_width(items_str) + 1
591 let nested_indent_str = self
594 .to_string_with_newline(self.context.config);
595 let indent_str = shape
598 .to_string_with_newline(self.context.config);
599 let mut result = String::with_capacity(
600 self.ident.len() + items_str.len() + 2 + indent_str.len() + nested_indent_str.len(),
602 result.push_str(self.ident);
603 result.push_str(prefix);
604 if !self.context.use_block_indent()
605 || (self.context.inside_macro() && !items_str.contains('\n') && fits_one_line)
606 || (is_extendable && extend_width <= shape.width)
608 result.push_str(items_str);
610 if !items_str.is_empty() {
611 result.push_str(&nested_indent_str);
612 result.push_str(items_str);
614 result.push_str(&indent_str);
616 result.push_str(suffix);
620 fn rewrite(&self, shape: Shape) -> Option<String> {
621 let (extendable, items_str) = self.rewrite_items()?;
623 // If we are using visual indent style and failed to format, retry with block indent.
624 if !self.context.use_block_indent()
625 && need_block_indent(&items_str, self.nested_shape)
628 self.context.use_block.replace(true);
629 let result = self.rewrite(shape);
630 self.context.use_block.replace(false);
634 Some(self.wrap_items(&items_str, shape, extendable))
638 fn need_block_indent(s: &str, shape: Shape) -> bool {
639 s.lines().skip(1).any(|s| {
640 s.find(|c| !char::is_whitespace(c))
641 .map_or(false, |w| w + 1 < shape.indent.width())
645 fn can_be_overflowed<'a>(context: &RewriteContext, items: &[OverflowableItem]) -> bool {
648 .map_or(false, |x| x.can_be_overflowed(context, items.len()))
651 /// Returns a shape for the last argument which is going to be overflowed.
653 lists: &[OverflowableItem],
656 args_max_width: usize,
658 if items.len() == 1 && !lists.iter().next()?.is_nested_call() {
661 let offset = items.iter().rev().skip(1).fold(0, |acc, i| {
663 acc + 2 + i.inner_as_ref().len()
666 width: min(args_max_width, shape.width),
672 fn shape_from_indent_style(
673 context: &RewriteContext,
678 let (shape, overhead) = if context.use_block_indent() {
681 .block_indent(context.config.tab_spaces())
682 .with_max_width(context.config);
683 (shape, 1) // 1 = ","
685 (shape.visual_indent(offset), overhead)
688 width: shape.width.saturating_sub(overhead),
693 fn no_long_items(list: &[ListItem]) -> bool {
695 .all(|item| item.inner_as_ref().len() <= SHORT_ITEM_THRESHOLD)
698 /// In case special-case style is required, returns an offset from which we start horizontal layout.
699 pub fn maybe_get_args_offset(callee_str: &str, args: &[OverflowableItem]) -> Option<(bool, usize)> {
700 if let Some(&(_, num_args_before)) = args
704 .find(|&&(s, _)| s == callee_str)
706 let all_simple = args.len() > num_args_before
707 && is_every_expr_simple(&args[0..num_args_before])
708 && is_every_expr_simple(&args[num_args_before + 1..]);
710 Some((all_simple, num_args_before))