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 const SPECIAL_ATTR_WHITELIST: &[(&str, usize)] = &[
71 // From the `failure` crate.
76 pub enum OverflowableItem<'a> {
78 GenericParam(&'a ast::GenericParam),
79 MacroArg(&'a MacroArg),
80 NestedMetaItem(&'a ast::NestedMetaItem),
81 SegmentParam(&'a SegmentParam<'a>),
82 StructField(&'a ast::StructField),
83 TuplePatField(&'a TuplePatField<'a>),
87 impl<'a> Rewrite for OverflowableItem<'a> {
88 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
89 self.map(|item| item.rewrite(context, shape))
93 impl<'a> Spanned for OverflowableItem<'a> {
94 fn span(&self) -> Span {
95 self.map(|item| item.span())
99 impl<'a> OverflowableItem<'a> {
100 pub fn map<F, T>(&self, f: F) -> T
102 F: Fn(&IntoOverflowableItem<'a>) -> T,
105 OverflowableItem::Expr(expr) => f(*expr),
106 OverflowableItem::GenericParam(gp) => f(*gp),
107 OverflowableItem::MacroArg(macro_arg) => f(*macro_arg),
108 OverflowableItem::NestedMetaItem(nmi) => f(*nmi),
109 OverflowableItem::SegmentParam(sp) => f(*sp),
110 OverflowableItem::StructField(sf) => f(*sf),
111 OverflowableItem::TuplePatField(pat) => f(*pat),
112 OverflowableItem::Ty(ty) => f(*ty),
116 pub fn is_simple(&self) -> bool {
118 OverflowableItem::Expr(expr) => is_simple_expr(expr),
119 OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_simple_expr(expr),
120 OverflowableItem::NestedMetaItem(nested_meta_item) => match nested_meta_item.node {
121 ast::NestedMetaItemKind::Literal(..) => true,
122 ast::NestedMetaItemKind::MetaItem(ref meta_item) => match meta_item.node {
123 ast::MetaItemKind::Word => true,
131 pub fn is_expr(&self) -> bool {
133 OverflowableItem::Expr(..) => true,
134 OverflowableItem::MacroArg(MacroArg::Expr(..)) => true,
139 pub fn is_nested_call(&self) -> bool {
141 OverflowableItem::Expr(expr) => is_nested_call(expr),
142 OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_nested_call(expr),
147 pub fn to_expr(&self) -> Option<&'a ast::Expr> {
149 OverflowableItem::Expr(expr) => Some(expr),
150 OverflowableItem::MacroArg(macro_arg) => match macro_arg {
151 MacroArg::Expr(ref expr) => Some(expr),
158 pub fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
160 OverflowableItem::Expr(expr) => can_be_overflowed_expr(context, expr, len),
161 OverflowableItem::MacroArg(macro_arg) => match macro_arg {
162 MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
163 MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
164 MacroArg::Pat(..) => false,
165 MacroArg::Item(..) => len == 1,
167 OverflowableItem::NestedMetaItem(nested_meta_item) if len == 1 => {
168 match nested_meta_item.node {
169 ast::NestedMetaItemKind::Literal(..) => false,
170 ast::NestedMetaItemKind::MetaItem(..) => true,
173 OverflowableItem::SegmentParam(seg) => match seg {
174 SegmentParam::Type(ty) => can_be_overflowed_type(context, ty, len),
177 OverflowableItem::TuplePatField(pat) => can_be_overflowed_pat(context, pat, len),
178 OverflowableItem::Ty(ty) => can_be_overflowed_type(context, ty, len),
183 fn whitelist(&self) -> &'static [(&'static str, usize)] {
185 OverflowableItem::MacroArg(..) => SPECIAL_MACRO_WHITELIST,
186 OverflowableItem::NestedMetaItem(..) => SPECIAL_ATTR_WHITELIST,
192 pub trait IntoOverflowableItem<'a>: Rewrite + Spanned {
193 fn into_overflowable_item(&'a self) -> OverflowableItem<'a>;
196 impl<'a, T: 'a + IntoOverflowableItem<'a>> IntoOverflowableItem<'a> for ptr::P<T> {
197 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
198 (**self).into_overflowable_item()
202 macro impl_into_overflowable_item_for_ast_node {
203 ($($ast_node:ident),*) => {
205 impl<'a> IntoOverflowableItem<'a> for ast::$ast_node {
206 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
207 OverflowableItem::$ast_node(self)
214 macro impl_into_overflowable_item_for_rustfmt_types {
215 ([$($ty:ident),*], [$($ty_with_lifetime:ident),*]) => {
217 impl<'a> IntoOverflowableItem<'a> for $ty {
218 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
219 OverflowableItem::$ty(self)
224 impl<'a> IntoOverflowableItem<'a> for $ty_with_lifetime<'a> {
225 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
226 OverflowableItem::$ty_with_lifetime(self)
233 impl_into_overflowable_item_for_ast_node!(Expr, GenericParam, NestedMetaItem, StructField, Ty);
234 impl_into_overflowable_item_for_rustfmt_types!([MacroArg], [SegmentParam, TuplePatField]);
236 pub fn into_overflowable_list<'a, T>(
237 iter: impl Iterator<Item = &'a T>,
238 ) -> impl Iterator<Item = OverflowableItem<'a>>
240 T: 'a + IntoOverflowableItem<'a>,
242 iter.map(|x| IntoOverflowableItem::into_overflowable_item(x))
245 pub fn rewrite_with_parens<'a, T: 'a + IntoOverflowableItem<'a>>(
246 context: &'a RewriteContext,
248 items: impl Iterator<Item = &'a T>,
251 item_max_width: usize,
252 force_separator_tactic: Option<SeparatorTactic>,
253 ) -> Option<String> {
263 force_separator_tactic,
269 pub fn rewrite_with_angle_brackets<'a, T: 'a + IntoOverflowableItem<'a>>(
270 context: &'a RewriteContext,
272 items: impl Iterator<Item = &'a T>,
275 ) -> Option<String> {
284 context.config.max_width(),
291 pub fn rewrite_with_square_brackets<'a, T: 'a + IntoOverflowableItem<'a>>(
292 context: &'a RewriteContext,
294 items: impl Iterator<Item = &'a T>,
297 force_separator_tactic: Option<SeparatorTactic>,
298 delim_token: Option<DelimToken>,
299 ) -> Option<String> {
300 let (lhs, rhs) = match delim_token {
301 Some(DelimToken::Paren) => ("(", ")"),
302 Some(DelimToken::Brace) => ("{", "}"),
313 context.config.width_heuristics().array_width,
314 force_separator_tactic,
321 context: &'a RewriteContext<'a>,
322 items: Vec<OverflowableItem<'a>>,
324 prefix: &'static str,
325 suffix: &'static str,
326 one_line_shape: Shape,
329 item_max_width: usize,
330 one_line_width: usize,
331 force_separator_tactic: Option<SeparatorTactic>,
332 custom_delims: Option<(&'a str, &'a str)>,
335 impl<'a> Context<'a> {
336 pub fn new<T: 'a + IntoOverflowableItem<'a>>(
337 context: &'a RewriteContext,
338 items: impl Iterator<Item = &'a T>,
342 prefix: &'static str,
343 suffix: &'static str,
344 item_max_width: usize,
345 force_separator_tactic: Option<SeparatorTactic>,
346 custom_delims: Option<(&'a str, &'a str)>,
348 let used_width = extra_offset(ident, shape);
350 let one_line_width = shape.width.saturating_sub(used_width + 2);
353 let one_line_shape = shape
354 .offset_left(last_line_width(ident) + 1)
355 .and_then(|shape| shape.sub_width(1))
356 .unwrap_or(Shape { width: 0, ..shape });
357 let nested_shape = shape_from_indent_style(context, shape, used_width + 2, used_width + 1);
360 items: into_overflowable_list(items).collect(),
369 force_separator_tactic,
374 fn last_item(&self) -> Option<&OverflowableItem> {
378 fn items_span(&self) -> Span {
382 .span_after(self.span, self.prefix);
383 mk_sp(span_lo, self.span.hi())
386 fn rewrite_last_item_with_overflow(
388 last_list_item: &mut ListItem,
390 ) -> Option<String> {
391 let last_item = self.last_item()?;
392 let rewrite = match last_item {
393 OverflowableItem::Expr(ref expr) => {
395 // When overflowing the closure which consists of a single control flow
396 // expression, force to use block if its condition uses multi line.
397 ast::ExprKind::Closure(..) => {
398 // If the argument consists of multiple closures, we do not overflow
400 if closures::args_have_many_closure(&self.items) {
403 closures::rewrite_last_closure(self.context, expr, shape)
406 _ => expr.rewrite(self.context, shape),
409 item @ _ => item.rewrite(self.context, shape),
412 if let Some(rewrite) = rewrite {
413 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
414 last_list_item.item = rewrite_first_line;
421 fn default_tactic(&self, list_items: &[ListItem]) -> DefinitiveListTactic {
424 ListTactic::LimitedHorizontalVertical(self.item_max_width),
430 fn try_overflow_last_item(&self, list_items: &mut Vec<ListItem>) -> DefinitiveListTactic {
432 let combine_arg_with_callee = self.items.len() == 1
433 && self.items[0].is_expr()
434 && self.ident.len() < self.context.config.tab_spaces();
435 let overflow_last = combine_arg_with_callee || can_be_overflowed(self.context, &self.items);
437 // Replace the last item with its first line to see if it fits with
439 let placeholder = if overflow_last {
440 let old_value = *self.context.force_one_line_chain.borrow();
441 match self.last_item() {
442 Some(OverflowableItem::Expr(expr))
443 if !combine_arg_with_callee && is_method_call(expr) =>
445 self.context.force_one_line_chain.replace(true);
449 let result = last_item_shape(
455 .and_then(|arg_shape| {
456 self.rewrite_last_item_with_overflow(
457 &mut list_items[self.items.len() - 1],
461 self.context.force_one_line_chain.replace(old_value);
467 let mut tactic = definitive_tactic(
469 ListTactic::LimitedHorizontalVertical(self.item_max_width),
474 // Replace the stub with the full overflowing last argument if the rewrite
475 // succeeded and its first line fits with the other arguments.
476 match (overflow_last, tactic, placeholder) {
477 (true, DefinitiveListTactic::Horizontal, Some(ref overflowed))
478 if self.items.len() == 1 =>
480 // When we are rewriting a nested function call, we restrict the
481 // budget for the inner function to avoid them being deeply nested.
482 // However, when the inner function has a prefix or a suffix
483 // (e.g. `foo() as u32`), this budget reduction may produce poorly
484 // formatted code, where a prefix or a suffix being left on its own
485 // line. Here we explicitlly check those cases.
486 if count_newlines(overflowed) == 1 {
490 .and_then(|last_item| last_item.rewrite(self.context, self.nested_shape));
491 let no_newline = rw.as_ref().map_or(false, |s| !s.contains('\n'));
493 list_items[self.items.len() - 1].item = rw;
495 list_items[self.items.len() - 1].item = Some(overflowed.to_owned());
498 list_items[self.items.len() - 1].item = Some(overflowed.to_owned());
501 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
502 list_items[self.items.len() - 1].item = placeholder;
504 _ if !self.items.is_empty() => {
505 list_items[self.items.len() - 1].item = self
508 .and_then(|last_item| last_item.rewrite(self.context, self.nested_shape));
510 // Use horizontal layout for a function with a single argument as long as
511 // everything fits in a single line.
512 // `self.one_line_width == 0` means vertical layout is forced.
513 if self.items.len() == 1
514 && self.one_line_width != 0
515 && !list_items[0].has_comment()
516 && !list_items[0].inner_as_ref().contains('\n')
517 && ::lists::total_item_width(&list_items[0]) <= self.one_line_width
519 tactic = DefinitiveListTactic::Horizontal;
521 tactic = self.default_tactic(list_items);
523 if tactic == DefinitiveListTactic::Vertical {
524 if let Some((all_simple, num_args_before)) =
525 maybe_get_args_offset(self.ident, &self.items)
527 let one_line = all_simple
528 && definitive_tactic(
529 &list_items[..num_args_before],
530 ListTactic::HorizontalVertical,
532 self.nested_shape.width,
533 ) == DefinitiveListTactic::Horizontal
534 && definitive_tactic(
535 &list_items[num_args_before + 1..],
536 ListTactic::HorizontalVertical,
538 self.nested_shape.width,
539 ) == DefinitiveListTactic::Horizontal;
542 tactic = DefinitiveListTactic::SpecialMacro(num_args_before);
544 } else if is_every_expr_simple(&self.items) && no_long_items(list_items) {
545 tactic = DefinitiveListTactic::Mixed;
556 fn rewrite_items(&self) -> Option<(bool, String)> {
557 let span = self.items_span();
558 let items = itemize_list(
559 self.context.snippet_provider,
563 |item| item.span().lo(),
564 |item| item.span().hi(),
565 |item| item.rewrite(self.context, self.nested_shape),
570 let mut list_items: Vec<_> = items.collect();
572 // Try letting the last argument overflow to the next line with block
573 // indentation. If its first line fits on one line with the other arguments,
574 // we format the function arguments horizontally.
575 let tactic = self.try_overflow_last_item(&mut list_items);
576 let trailing_separator = if let Some(tactic) = self.force_separator_tactic {
578 } else if !self.context.use_block_indent() {
579 SeparatorTactic::Never
580 } else if tactic == DefinitiveListTactic::Mixed {
581 // We are using mixed layout because everything did not fit within a single line.
582 SeparatorTactic::Always
584 self.context.config.trailing_comma()
586 let ends_with_newline = match tactic {
587 DefinitiveListTactic::Vertical | DefinitiveListTactic::Mixed => {
588 self.context.use_block_indent()
593 let fmt = ListFormatting::new(self.nested_shape, self.context.config)
595 .trailing_separator(trailing_separator)
596 .ends_with_newline(ends_with_newline);
598 write_list(&list_items, &fmt)
599 .map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str))
602 fn wrap_items(&self, items_str: &str, shape: Shape, is_extendable: bool) -> String {
604 width: shape.width.saturating_sub(last_line_width(self.ident)),
608 let (prefix, suffix) = match self.custom_delims {
609 Some((lhs, rhs)) => (lhs, rhs),
610 _ => (self.prefix, self.suffix),
614 let fits_one_line = items_str.len() + 2 <= shape.width;
615 let extend_width = if items_str.is_empty() {
618 first_line_width(items_str) + 1
620 let nested_indent_str = self
623 .to_string_with_newline(self.context.config);
624 let indent_str = shape
627 .to_string_with_newline(self.context.config);
628 let mut result = String::with_capacity(
629 self.ident.len() + items_str.len() + 2 + indent_str.len() + nested_indent_str.len(),
631 result.push_str(self.ident);
632 result.push_str(prefix);
633 if !self.context.use_block_indent()
634 || (self.context.inside_macro() && !items_str.contains('\n') && fits_one_line)
635 || (is_extendable && extend_width <= shape.width)
637 result.push_str(items_str);
639 if !items_str.is_empty() {
640 result.push_str(&nested_indent_str);
641 result.push_str(items_str);
643 result.push_str(&indent_str);
645 result.push_str(suffix);
649 fn rewrite(&self, shape: Shape) -> Option<String> {
650 let (extendable, items_str) = self.rewrite_items()?;
652 // If we are using visual indent style and failed to format, retry with block indent.
653 if !self.context.use_block_indent()
654 && need_block_indent(&items_str, self.nested_shape)
657 self.context.use_block.replace(true);
658 let result = self.rewrite(shape);
659 self.context.use_block.replace(false);
663 Some(self.wrap_items(&items_str, shape, extendable))
667 fn need_block_indent(s: &str, shape: Shape) -> bool {
668 s.lines().skip(1).any(|s| {
669 s.find(|c| !char::is_whitespace(c))
670 .map_or(false, |w| w + 1 < shape.indent.width())
674 fn can_be_overflowed<'a>(context: &RewriteContext, items: &[OverflowableItem]) -> bool {
677 .map_or(false, |x| x.can_be_overflowed(context, items.len()))
680 /// Returns a shape for the last argument which is going to be overflowed.
682 lists: &[OverflowableItem],
685 args_max_width: usize,
687 if items.len() == 1 && !lists.get(0)?.is_nested_call() {
690 let offset = items.iter().rev().skip(1).fold(0, |acc, i| {
692 acc + 2 + i.inner_as_ref().len()
695 width: min(args_max_width, shape.width),
701 fn shape_from_indent_style(
702 context: &RewriteContext,
707 let (shape, overhead) = if context.use_block_indent() {
710 .block_indent(context.config.tab_spaces())
711 .with_max_width(context.config);
712 (shape, 1) // 1 = ","
714 (shape.visual_indent(offset), overhead)
717 width: shape.width.saturating_sub(overhead),
722 fn no_long_items(list: &[ListItem]) -> bool {
724 .all(|item| item.inner_as_ref().len() <= SHORT_ITEM_THRESHOLD)
727 /// In case special-case style is required, returns an offset from which we start horizontal layout.
728 pub fn maybe_get_args_offset(callee_str: &str, args: &[OverflowableItem]) -> Option<(bool, usize)> {
729 if let Some(&(_, num_args_before)) = args
733 .find(|&&(s, _)| s == callee_str)
735 let all_simple = args.len() > num_args_before
736 && is_every_expr_simple(&args[0..num_args_before])
737 && is_every_expr_simple(&args[num_args_before + 1..]);
739 Some((all_simple, num_args_before))