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.
15 use syntax::parse::token::DelimToken;
16 use syntax::source_map::Span;
17 use syntax::{ast, ptr};
20 use crate::config::lists::*;
21 use crate::config::Version;
23 can_be_overflowed_expr, is_every_expr_simple, is_method_call, is_nested_call, is_simple_expr,
27 definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator,
29 use crate::macros::MacroArg;
30 use crate::patterns::{can_be_overflowed_pat, TuplePatField};
31 use crate::rewrite::{Rewrite, RewriteContext};
32 use crate::shape::Shape;
33 use crate::source_map::SpanUtils;
34 use crate::spanned::Spanned;
35 use crate::types::{can_be_overflowed_type, SegmentParam};
36 use crate::utils::{count_newlines, extra_offset, first_line_width, last_line_width, mk_sp};
38 const SHORT_ITEM_THRESHOLD: usize = 10;
40 /// A list of `format!`-like macros, that take a long format string and a list of arguments to
43 /// Organized as a list of `(&str, usize)` tuples, giving the name of the macro and the number of
44 /// arguments before the format string (none for `format!("format", ...)`, one for `assert!(result,
45 /// "format", ...)`, two for `assert_eq!(left, right, "format", ...)`).
46 const SPECIAL_MACRO_WHITELIST: &[(&str, usize)] = &[
47 // format! like macros
48 // From the Rust Standard Library.
57 // From the `log` crate.
67 // assert_eq! like macros
70 ("debug_assert_eq!", 2),
71 ("debug_assert_ne!", 2),
74 const SPECIAL_ATTR_WHITELIST: &[(&str, usize)] = &[
75 // From the `failure` crate.
80 pub enum OverflowableItem<'a> {
82 GenericParam(&'a ast::GenericParam),
83 MacroArg(&'a MacroArg),
84 NestedMetaItem(&'a ast::NestedMetaItem),
85 SegmentParam(&'a SegmentParam<'a>),
86 StructField(&'a ast::StructField),
87 TuplePatField(&'a TuplePatField<'a>),
91 impl<'a> Rewrite for OverflowableItem<'a> {
92 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
93 self.map(|item| item.rewrite(context, shape))
97 impl<'a> Spanned for OverflowableItem<'a> {
98 fn span(&self) -> Span {
99 self.map(|item| item.span())
103 impl<'a> OverflowableItem<'a> {
104 pub fn map<F, T>(&self, f: F) -> T
106 F: Fn(&IntoOverflowableItem<'a>) -> T,
109 OverflowableItem::Expr(expr) => f(*expr),
110 OverflowableItem::GenericParam(gp) => f(*gp),
111 OverflowableItem::MacroArg(macro_arg) => f(*macro_arg),
112 OverflowableItem::NestedMetaItem(nmi) => f(*nmi),
113 OverflowableItem::SegmentParam(sp) => f(*sp),
114 OverflowableItem::StructField(sf) => f(*sf),
115 OverflowableItem::TuplePatField(pat) => f(*pat),
116 OverflowableItem::Ty(ty) => f(*ty),
120 pub fn is_simple(&self) -> bool {
122 OverflowableItem::Expr(expr) => is_simple_expr(expr),
123 OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_simple_expr(expr),
124 OverflowableItem::NestedMetaItem(nested_meta_item) => match nested_meta_item.node {
125 ast::NestedMetaItemKind::Literal(..) => true,
126 ast::NestedMetaItemKind::MetaItem(ref meta_item) => match meta_item.node {
127 ast::MetaItemKind::Word => true,
135 pub fn is_expr(&self) -> bool {
137 OverflowableItem::Expr(..) => true,
138 OverflowableItem::MacroArg(MacroArg::Expr(..)) => true,
143 pub fn is_nested_call(&self) -> bool {
145 OverflowableItem::Expr(expr) => is_nested_call(expr),
146 OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_nested_call(expr),
151 pub fn to_expr(&self) -> Option<&'a ast::Expr> {
153 OverflowableItem::Expr(expr) => Some(expr),
154 OverflowableItem::MacroArg(macro_arg) => match macro_arg {
155 MacroArg::Expr(ref expr) => Some(expr),
162 pub fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
164 OverflowableItem::Expr(expr) => can_be_overflowed_expr(context, expr, len),
165 OverflowableItem::MacroArg(macro_arg) => match macro_arg {
166 MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
167 MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
168 MacroArg::Pat(..) => false,
169 MacroArg::Item(..) => len == 1,
171 OverflowableItem::NestedMetaItem(nested_meta_item) if len == 1 => {
172 match nested_meta_item.node {
173 ast::NestedMetaItemKind::Literal(..) => false,
174 ast::NestedMetaItemKind::MetaItem(..) => true,
177 OverflowableItem::SegmentParam(seg) => match seg {
178 SegmentParam::Type(ty) => can_be_overflowed_type(context, ty, len),
181 OverflowableItem::TuplePatField(pat) => can_be_overflowed_pat(context, pat, len),
182 OverflowableItem::Ty(ty) => can_be_overflowed_type(context, ty, len),
187 fn whitelist(&self) -> &'static [(&'static str, usize)] {
189 OverflowableItem::MacroArg(..) => SPECIAL_MACRO_WHITELIST,
190 OverflowableItem::NestedMetaItem(..) => SPECIAL_ATTR_WHITELIST,
196 pub trait IntoOverflowableItem<'a>: Rewrite + Spanned {
197 fn into_overflowable_item(&'a self) -> OverflowableItem<'a>;
200 impl<'a, T: 'a + IntoOverflowableItem<'a>> IntoOverflowableItem<'a> for ptr::P<T> {
201 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
202 (**self).into_overflowable_item()
206 macro_rules! impl_into_overflowable_item_for_ast_node {
207 ($($ast_node:ident),*) => {
209 impl<'a> IntoOverflowableItem<'a> for ast::$ast_node {
210 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
211 OverflowableItem::$ast_node(self)
218 macro_rules! impl_into_overflowable_item_for_rustfmt_types {
219 ([$($ty:ident),*], [$($ty_with_lifetime:ident),*]) => {
221 impl<'a> IntoOverflowableItem<'a> for $ty {
222 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
223 OverflowableItem::$ty(self)
228 impl<'a> IntoOverflowableItem<'a> for $ty_with_lifetime<'a> {
229 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
230 OverflowableItem::$ty_with_lifetime(self)
237 impl_into_overflowable_item_for_ast_node!(Expr, GenericParam, NestedMetaItem, StructField, Ty);
238 impl_into_overflowable_item_for_rustfmt_types!([MacroArg], [SegmentParam, TuplePatField]);
240 pub fn into_overflowable_list<'a, T>(
241 iter: impl Iterator<Item = &'a T>,
242 ) -> impl Iterator<Item = OverflowableItem<'a>>
244 T: 'a + IntoOverflowableItem<'a>,
246 iter.map(|x| IntoOverflowableItem::into_overflowable_item(x))
249 pub fn rewrite_with_parens<'a, T: 'a + IntoOverflowableItem<'a>>(
250 context: &'a RewriteContext,
252 items: impl Iterator<Item = &'a T>,
255 item_max_width: usize,
256 force_separator_tactic: Option<SeparatorTactic>,
257 ) -> Option<String> {
267 force_separator_tactic,
273 pub fn rewrite_with_angle_brackets<'a, T: 'a + IntoOverflowableItem<'a>>(
274 context: &'a RewriteContext,
276 items: impl Iterator<Item = &'a T>,
279 ) -> Option<String> {
288 context.config.max_width(),
295 pub fn rewrite_with_square_brackets<'a, T: 'a + IntoOverflowableItem<'a>>(
296 context: &'a RewriteContext,
298 items: impl Iterator<Item = &'a T>,
301 force_separator_tactic: Option<SeparatorTactic>,
302 delim_token: Option<DelimToken>,
303 ) -> Option<String> {
304 let (lhs, rhs) = match delim_token {
305 Some(DelimToken::Paren) => ("(", ")"),
306 Some(DelimToken::Brace) => ("{", "}"),
317 context.config.width_heuristics().array_width,
318 force_separator_tactic,
325 context: &'a RewriteContext<'a>,
326 items: Vec<OverflowableItem<'a>>,
328 prefix: &'static str,
329 suffix: &'static str,
330 one_line_shape: Shape,
333 item_max_width: usize,
334 one_line_width: usize,
335 force_separator_tactic: Option<SeparatorTactic>,
336 custom_delims: Option<(&'a str, &'a str)>,
339 impl<'a> Context<'a> {
340 pub fn new<T: 'a + IntoOverflowableItem<'a>>(
341 context: &'a RewriteContext,
342 items: impl Iterator<Item = &'a T>,
346 prefix: &'static str,
347 suffix: &'static str,
348 item_max_width: usize,
349 force_separator_tactic: Option<SeparatorTactic>,
350 custom_delims: Option<(&'a str, &'a str)>,
352 let used_width = extra_offset(ident, shape);
354 let one_line_width = shape.width.saturating_sub(used_width + 2);
357 let one_line_shape = shape
358 .offset_left(last_line_width(ident) + 1)
359 .and_then(|shape| shape.sub_width(1))
360 .unwrap_or(Shape { width: 0, ..shape });
361 let nested_shape = shape_from_indent_style(context, shape, used_width + 2, used_width + 1);
364 items: into_overflowable_list(items).collect(),
373 force_separator_tactic,
378 fn last_item(&self) -> Option<&OverflowableItem> {
382 fn items_span(&self) -> Span {
386 .span_after(self.span, self.prefix);
387 mk_sp(span_lo, self.span.hi())
390 fn rewrite_last_item_with_overflow(
392 last_list_item: &mut ListItem,
394 ) -> Option<String> {
395 let last_item = self.last_item()?;
396 let rewrite = match last_item {
397 OverflowableItem::Expr(ref expr) => {
399 // When overflowing the closure which consists of a single control flow
400 // expression, force to use block if its condition uses multi line.
401 ast::ExprKind::Closure(..) => {
402 // If the argument consists of multiple closures, we do not overflow
404 if closures::args_have_many_closure(&self.items) {
407 closures::rewrite_last_closure(self.context, expr, shape)
411 // When overflowing the expressions which consists of a control flow
412 // expression, avoid condition to use multi line.
413 ast::ExprKind::If(..)
414 | ast::ExprKind::IfLet(..)
415 | ast::ExprKind::ForLoop(..)
416 | ast::ExprKind::Loop(..)
417 | ast::ExprKind::While(..)
418 | ast::ExprKind::WhileLet(..)
419 | ast::ExprKind::Match(..) => {
420 let multi_line = rewrite_cond(self.context, expr, shape)
421 .map_or(false, |cond| cond.contains('\n'));
426 expr.rewrite(self.context, shape)
430 _ => expr.rewrite(self.context, shape),
433 item => item.rewrite(self.context, shape),
436 if let Some(rewrite) = rewrite {
437 // splitn(2, *).next().unwrap() is always safe.
438 let rewrite_first_line = Some(rewrite.splitn(2, '\n').next().unwrap().to_owned());
439 last_list_item.item = rewrite_first_line;
446 fn default_tactic(&self, list_items: &[ListItem]) -> DefinitiveListTactic {
449 ListTactic::LimitedHorizontalVertical(self.item_max_width),
455 fn try_overflow_last_item(&self, list_items: &mut Vec<ListItem>) -> DefinitiveListTactic {
457 let combine_arg_with_callee = self.items.len() == 1
458 && self.items[0].is_expr()
459 && self.ident.len() < self.context.config.tab_spaces();
460 let overflow_last = combine_arg_with_callee || can_be_overflowed(self.context, &self.items);
462 // Replace the last item with its first line to see if it fits with
464 let placeholder = if overflow_last {
465 let old_value = *self.context.force_one_line_chain.borrow();
466 match self.last_item() {
467 Some(OverflowableItem::Expr(expr))
468 if !combine_arg_with_callee && is_method_call(expr) =>
470 self.context.force_one_line_chain.replace(true);
472 Some(OverflowableItem::MacroArg(MacroArg::Expr(expr)))
473 if !combine_arg_with_callee
474 && is_method_call(expr)
475 && self.context.config.version() == Version::Two =>
477 self.context.force_one_line_chain.replace(true);
481 let result = last_item_shape(
487 .and_then(|arg_shape| {
488 self.rewrite_last_item_with_overflow(
489 &mut list_items[self.items.len() - 1],
493 self.context.force_one_line_chain.replace(old_value);
499 let mut tactic = definitive_tactic(
501 ListTactic::LimitedHorizontalVertical(self.item_max_width),
506 // Replace the stub with the full overflowing last argument if the rewrite
507 // succeeded and its first line fits with the other arguments.
508 match (overflow_last, tactic, placeholder) {
509 (true, DefinitiveListTactic::Horizontal, Some(ref overflowed))
510 if self.items.len() == 1 =>
512 // When we are rewriting a nested function call, we restrict the
513 // budget for the inner function to avoid them being deeply nested.
514 // However, when the inner function has a prefix or a suffix
515 // (e.g. `foo() as u32`), this budget reduction may produce poorly
516 // formatted code, where a prefix or a suffix being left on its own
517 // line. Here we explicitlly check those cases.
518 if count_newlines(overflowed) == 1 {
522 .and_then(|last_item| last_item.rewrite(self.context, self.nested_shape));
523 let no_newline = rw.as_ref().map_or(false, |s| !s.contains('\n'));
525 list_items[self.items.len() - 1].item = rw;
527 list_items[self.items.len() - 1].item = Some(overflowed.to_owned());
530 list_items[self.items.len() - 1].item = Some(overflowed.to_owned());
533 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
534 list_items[self.items.len() - 1].item = placeholder;
536 _ if !self.items.is_empty() => {
537 list_items[self.items.len() - 1].item = self
540 .and_then(|last_item| last_item.rewrite(self.context, self.nested_shape));
542 // Use horizontal layout for a function with a single argument as long as
543 // everything fits in a single line.
544 // `self.one_line_width == 0` means vertical layout is forced.
545 if self.items.len() == 1
546 && self.one_line_width != 0
547 && !list_items[0].has_comment()
548 && !list_items[0].inner_as_ref().contains('\n')
549 && crate::lists::total_item_width(&list_items[0]) <= self.one_line_width
551 tactic = DefinitiveListTactic::Horizontal;
553 tactic = self.default_tactic(list_items);
555 if tactic == DefinitiveListTactic::Vertical {
556 if let Some((all_simple, num_args_before)) =
557 maybe_get_args_offset(self.ident, &self.items)
559 let one_line = all_simple
560 && definitive_tactic(
561 &list_items[..num_args_before],
562 ListTactic::HorizontalVertical,
564 self.nested_shape.width,
565 ) == DefinitiveListTactic::Horizontal
566 && definitive_tactic(
567 &list_items[num_args_before + 1..],
568 ListTactic::HorizontalVertical,
570 self.nested_shape.width,
571 ) == DefinitiveListTactic::Horizontal;
574 tactic = DefinitiveListTactic::SpecialMacro(num_args_before);
576 } else if is_every_expr_simple(&self.items) && no_long_items(list_items) {
577 tactic = DefinitiveListTactic::Mixed;
588 fn rewrite_items(&self) -> Option<(bool, String)> {
589 let span = self.items_span();
590 let items = itemize_list(
591 self.context.snippet_provider,
595 |item| item.span().lo(),
596 |item| item.span().hi(),
597 |item| item.rewrite(self.context, self.nested_shape),
602 let mut list_items: Vec<_> = items.collect();
604 // Try letting the last argument overflow to the next line with block
605 // indentation. If its first line fits on one line with the other arguments,
606 // we format the function arguments horizontally.
607 let tactic = self.try_overflow_last_item(&mut list_items);
608 let trailing_separator = if let Some(tactic) = self.force_separator_tactic {
610 } else if !self.context.use_block_indent() {
611 SeparatorTactic::Never
613 self.context.config.trailing_comma()
615 let ends_with_newline = match tactic {
616 DefinitiveListTactic::Vertical | DefinitiveListTactic::Mixed => {
617 self.context.use_block_indent()
622 let fmt = ListFormatting::new(self.nested_shape, self.context.config)
624 .trailing_separator(trailing_separator)
625 .ends_with_newline(ends_with_newline);
627 write_list(&list_items, &fmt)
628 .map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str))
631 fn wrap_items(&self, items_str: &str, shape: Shape, is_extendable: bool) -> String {
633 width: shape.width.saturating_sub(last_line_width(self.ident)),
637 let (prefix, suffix) = match self.custom_delims {
638 Some((lhs, rhs)) => (lhs, rhs),
639 _ => (self.prefix, self.suffix),
642 let extend_width = if items_str.is_empty() {
645 first_line_width(items_str) + 1
647 let nested_indent_str = self
650 .to_string_with_newline(self.context.config);
651 let indent_str = shape
654 .to_string_with_newline(self.context.config);
655 let mut result = String::with_capacity(
656 self.ident.len() + items_str.len() + 2 + indent_str.len() + nested_indent_str.len(),
658 result.push_str(self.ident);
659 result.push_str(prefix);
660 let force_single_line = if self.context.config.version() == Version::Two {
661 !self.context.use_block_indent() || (is_extendable && extend_width <= shape.width)
664 let fits_one_line = items_str.len() + 2 <= shape.width;
665 !self.context.use_block_indent()
666 || (self.context.inside_macro() && !items_str.contains('\n') && fits_one_line)
667 || (is_extendable && extend_width <= shape.width)
669 if force_single_line {
670 result.push_str(items_str);
672 if !items_str.is_empty() {
673 result.push_str(&nested_indent_str);
674 result.push_str(items_str);
676 result.push_str(&indent_str);
678 result.push_str(suffix);
682 fn rewrite(&self, shape: Shape) -> Option<String> {
683 let (extendable, items_str) = self.rewrite_items()?;
685 // If we are using visual indent style and failed to format, retry with block indent.
686 if !self.context.use_block_indent()
687 && need_block_indent(&items_str, self.nested_shape)
690 self.context.use_block.replace(true);
691 let result = self.rewrite(shape);
692 self.context.use_block.replace(false);
696 Some(self.wrap_items(&items_str, shape, extendable))
700 fn need_block_indent(s: &str, shape: Shape) -> bool {
701 s.lines().skip(1).any(|s| {
702 s.find(|c| !char::is_whitespace(c))
703 .map_or(false, |w| w + 1 < shape.indent.width())
707 fn can_be_overflowed(context: &RewriteContext, items: &[OverflowableItem]) -> bool {
710 .map_or(false, |x| x.can_be_overflowed(context, items.len()))
713 /// Returns a shape for the last argument which is going to be overflowed.
715 lists: &[OverflowableItem],
718 args_max_width: usize,
720 if items.len() == 1 && !lists.get(0)?.is_nested_call() {
723 let offset = items.iter().rev().skip(1).fold(0, |acc, i| {
725 acc + 2 + i.inner_as_ref().len()
728 width: min(args_max_width, shape.width),
734 fn shape_from_indent_style(
735 context: &RewriteContext,
740 let (shape, overhead) = if context.use_block_indent() {
743 .block_indent(context.config.tab_spaces())
744 .with_max_width(context.config);
745 (shape, 1) // 1 = ","
747 (shape.visual_indent(offset), overhead)
750 width: shape.width.saturating_sub(overhead),
755 fn no_long_items(list: &[ListItem]) -> bool {
757 .all(|item| item.inner_as_ref().len() <= SHORT_ITEM_THRESHOLD)
760 /// In case special-case style is required, returns an offset from which we start horizontal layout.
761 pub fn maybe_get_args_offset(callee_str: &str, args: &[OverflowableItem]) -> Option<(bool, usize)> {
762 if let Some(&(_, num_args_before)) = args
766 .find(|&&(s, _)| s == callee_str)
768 let all_simple = args.len() > num_args_before
769 && is_every_expr_simple(&args[0..num_args_before])
770 && is_every_expr_simple(&args[num_args_before + 1..]);
772 Some((all_simple, num_args_before))