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};
21 can_be_overflowed_expr, is_every_expr_simple, is_method_call, is_nested_call, is_simple_expr,
24 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator};
26 use patterns::{can_be_overflowed_pat, TuplePatField};
27 use rewrite::{Rewrite, RewriteContext};
29 use source_map::SpanUtils;
31 use types::{can_be_overflowed_type, SegmentParam};
32 use utils::{count_newlines, extra_offset, first_line_width, last_line_width, mk_sp};
36 const SHORT_ITEM_THRESHOLD: usize = 10;
38 /// A list of `format!`-like macros, that take a long format string and a list of arguments to
41 /// Organized as a list of `(&str, usize)` tuples, giving the name of the macro and the number of
42 /// arguments before the format string (none for `format!("format", ...)`, one for `assert!(result,
43 /// "format", ...)`, two for `assert_eq!(left, right, "format", ...)`).
44 const SPECIAL_MACRO_WHITELIST: &[(&str, usize)] = &[
45 // format! like macros
46 // From the Rust Standard Library.
55 // From the `log` crate.
65 // assert_eq! like macros
68 ("debug_assert_eq!", 2),
69 ("debug_assert_ne!", 2),
72 const SPECIAL_ATTR_WHITELIST: &[(&str, usize)] = &[
73 // From the `failure` crate.
78 pub enum OverflowableItem<'a> {
80 GenericParam(&'a ast::GenericParam),
81 MacroArg(&'a MacroArg),
82 NestedMetaItem(&'a ast::NestedMetaItem),
83 SegmentParam(&'a SegmentParam<'a>),
84 StructField(&'a ast::StructField),
85 TuplePatField(&'a TuplePatField<'a>),
89 impl<'a> Rewrite for OverflowableItem<'a> {
90 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
91 self.map(|item| item.rewrite(context, shape))
95 impl<'a> Spanned for OverflowableItem<'a> {
96 fn span(&self) -> Span {
97 self.map(|item| item.span())
101 impl<'a> OverflowableItem<'a> {
102 pub fn map<F, T>(&self, f: F) -> T
104 F: Fn(&IntoOverflowableItem<'a>) -> T,
107 OverflowableItem::Expr(expr) => f(*expr),
108 OverflowableItem::GenericParam(gp) => f(*gp),
109 OverflowableItem::MacroArg(macro_arg) => f(*macro_arg),
110 OverflowableItem::NestedMetaItem(nmi) => f(*nmi),
111 OverflowableItem::SegmentParam(sp) => f(*sp),
112 OverflowableItem::StructField(sf) => f(*sf),
113 OverflowableItem::TuplePatField(pat) => f(*pat),
114 OverflowableItem::Ty(ty) => f(*ty),
118 pub fn is_simple(&self) -> bool {
120 OverflowableItem::Expr(expr) => is_simple_expr(expr),
121 OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_simple_expr(expr),
122 OverflowableItem::NestedMetaItem(nested_meta_item) => match nested_meta_item.node {
123 ast::NestedMetaItemKind::Literal(..) => true,
124 ast::NestedMetaItemKind::MetaItem(ref meta_item) => match meta_item.node {
125 ast::MetaItemKind::Word => true,
133 pub fn is_expr(&self) -> bool {
135 OverflowableItem::Expr(..) => true,
136 OverflowableItem::MacroArg(MacroArg::Expr(..)) => true,
141 pub fn is_nested_call(&self) -> bool {
143 OverflowableItem::Expr(expr) => is_nested_call(expr),
144 OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_nested_call(expr),
149 pub fn to_expr(&self) -> Option<&'a ast::Expr> {
151 OverflowableItem::Expr(expr) => Some(expr),
152 OverflowableItem::MacroArg(macro_arg) => match macro_arg {
153 MacroArg::Expr(ref expr) => Some(expr),
160 pub fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
162 OverflowableItem::Expr(expr) => can_be_overflowed_expr(context, expr, len),
163 OverflowableItem::MacroArg(macro_arg) => match macro_arg {
164 MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
165 MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
166 MacroArg::Pat(..) => false,
167 MacroArg::Item(..) => len == 1,
169 OverflowableItem::NestedMetaItem(nested_meta_item) if len == 1 => {
170 match nested_meta_item.node {
171 ast::NestedMetaItemKind::Literal(..) => false,
172 ast::NestedMetaItemKind::MetaItem(..) => true,
175 OverflowableItem::SegmentParam(seg) => match seg {
176 SegmentParam::Type(ty) => can_be_overflowed_type(context, ty, len),
179 OverflowableItem::TuplePatField(pat) => can_be_overflowed_pat(context, pat, len),
180 OverflowableItem::Ty(ty) => can_be_overflowed_type(context, ty, len),
185 fn whitelist(&self) -> &'static [(&'static str, usize)] {
187 OverflowableItem::MacroArg(..) => SPECIAL_MACRO_WHITELIST,
188 OverflowableItem::NestedMetaItem(..) => SPECIAL_ATTR_WHITELIST,
194 pub trait IntoOverflowableItem<'a>: Rewrite + Spanned {
195 fn into_overflowable_item(&'a self) -> OverflowableItem<'a>;
198 impl<'a, T: 'a + IntoOverflowableItem<'a>> IntoOverflowableItem<'a> for ptr::P<T> {
199 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
200 (**self).into_overflowable_item()
204 macro_rules! impl_into_overflowable_item_for_ast_node {
205 ($($ast_node:ident),*) => {
207 impl<'a> IntoOverflowableItem<'a> for ast::$ast_node {
208 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
209 OverflowableItem::$ast_node(self)
216 macro_rules! impl_into_overflowable_item_for_rustfmt_types {
217 ([$($ty:ident),*], [$($ty_with_lifetime:ident),*]) => {
219 impl<'a> IntoOverflowableItem<'a> for $ty {
220 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
221 OverflowableItem::$ty(self)
226 impl<'a> IntoOverflowableItem<'a> for $ty_with_lifetime<'a> {
227 fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
228 OverflowableItem::$ty_with_lifetime(self)
235 impl_into_overflowable_item_for_ast_node!(Expr, GenericParam, NestedMetaItem, StructField, Ty);
236 impl_into_overflowable_item_for_rustfmt_types!([MacroArg], [SegmentParam, TuplePatField]);
238 pub fn into_overflowable_list<'a, T>(
239 iter: impl Iterator<Item = &'a T>,
240 ) -> impl Iterator<Item = OverflowableItem<'a>>
242 T: 'a + IntoOverflowableItem<'a>,
244 iter.map(|x| IntoOverflowableItem::into_overflowable_item(x))
247 pub fn rewrite_with_parens<'a, T: 'a + IntoOverflowableItem<'a>>(
248 context: &'a RewriteContext,
250 items: impl Iterator<Item = &'a T>,
253 item_max_width: usize,
254 force_separator_tactic: Option<SeparatorTactic>,
255 ) -> Option<String> {
265 force_separator_tactic,
271 pub fn rewrite_with_angle_brackets<'a, T: 'a + IntoOverflowableItem<'a>>(
272 context: &'a RewriteContext,
274 items: impl Iterator<Item = &'a T>,
277 ) -> Option<String> {
286 context.config.max_width(),
293 pub fn rewrite_with_square_brackets<'a, T: 'a + IntoOverflowableItem<'a>>(
294 context: &'a RewriteContext,
296 items: impl Iterator<Item = &'a T>,
299 force_separator_tactic: Option<SeparatorTactic>,
300 delim_token: Option<DelimToken>,
301 ) -> Option<String> {
302 let (lhs, rhs) = match delim_token {
303 Some(DelimToken::Paren) => ("(", ")"),
304 Some(DelimToken::Brace) => ("{", "}"),
315 context.config.width_heuristics().array_width,
316 force_separator_tactic,
323 context: &'a RewriteContext<'a>,
324 items: Vec<OverflowableItem<'a>>,
326 prefix: &'static str,
327 suffix: &'static str,
328 one_line_shape: Shape,
331 item_max_width: usize,
332 one_line_width: usize,
333 force_separator_tactic: Option<SeparatorTactic>,
334 custom_delims: Option<(&'a str, &'a str)>,
337 impl<'a> Context<'a> {
338 pub fn new<T: 'a + IntoOverflowableItem<'a>>(
339 context: &'a RewriteContext,
340 items: impl Iterator<Item = &'a T>,
344 prefix: &'static str,
345 suffix: &'static str,
346 item_max_width: usize,
347 force_separator_tactic: Option<SeparatorTactic>,
348 custom_delims: Option<(&'a str, &'a str)>,
350 let used_width = extra_offset(ident, shape);
352 let one_line_width = shape.width.saturating_sub(used_width + 2);
355 let one_line_shape = shape
356 .offset_left(last_line_width(ident) + 1)
357 .and_then(|shape| shape.sub_width(1))
358 .unwrap_or(Shape { width: 0, ..shape });
359 let nested_shape = shape_from_indent_style(context, shape, used_width + 2, used_width + 1);
362 items: into_overflowable_list(items).collect(),
371 force_separator_tactic,
376 fn last_item(&self) -> Option<&OverflowableItem> {
380 fn items_span(&self) -> Span {
384 .span_after(self.span, self.prefix);
385 mk_sp(span_lo, self.span.hi())
388 fn rewrite_last_item_with_overflow(
390 last_list_item: &mut ListItem,
392 ) -> Option<String> {
393 let last_item = self.last_item()?;
394 let rewrite = match last_item {
395 OverflowableItem::Expr(ref expr) => {
397 // When overflowing the closure which consists of a single control flow
398 // expression, force to use block if its condition uses multi line.
399 ast::ExprKind::Closure(..) => {
400 // If the argument consists of multiple closures, we do not overflow
402 if closures::args_have_many_closure(&self.items) {
405 closures::rewrite_last_closure(self.context, expr, shape)
409 // When overflowing the expressions which consists of a control flow
410 // expression, avoid condition to use multi line.
411 ast::ExprKind::If(..)
412 | ast::ExprKind::IfLet(..)
413 | ast::ExprKind::ForLoop(..)
414 | ast::ExprKind::Loop(..)
415 | ast::ExprKind::While(..)
416 | ast::ExprKind::WhileLet(..)
417 | ast::ExprKind::Match(..) => {
418 let multi_line = rewrite_cond(self.context, expr, shape)
419 .map_or(false, |cond| cond.contains('\n'));
424 expr.rewrite(self.context, shape)
428 _ => expr.rewrite(self.context, shape),
431 item => item.rewrite(self.context, shape),
434 if let Some(rewrite) = rewrite {
435 // splitn(2, *).next().unwrap() is always safe.
436 let rewrite_first_line = Some(rewrite.splitn(2, '\n').next().unwrap().to_owned());
437 last_list_item.item = rewrite_first_line;
444 fn default_tactic(&self, list_items: &[ListItem]) -> DefinitiveListTactic {
447 ListTactic::LimitedHorizontalVertical(self.item_max_width),
453 fn try_overflow_last_item(&self, list_items: &mut Vec<ListItem>) -> DefinitiveListTactic {
455 let combine_arg_with_callee = self.items.len() == 1
456 && self.items[0].is_expr()
457 && self.ident.len() < self.context.config.tab_spaces();
458 let overflow_last = combine_arg_with_callee || can_be_overflowed(self.context, &self.items);
460 // Replace the last item with its first line to see if it fits with
462 let placeholder = if overflow_last {
463 let old_value = *self.context.force_one_line_chain.borrow();
464 match self.last_item() {
465 Some(OverflowableItem::Expr(expr))
466 if !combine_arg_with_callee && is_method_call(expr) =>
468 self.context.force_one_line_chain.replace(true);
470 Some(OverflowableItem::MacroArg(MacroArg::Expr(expr)))
471 if !combine_arg_with_callee
472 && is_method_call(expr)
473 && self.context.config.version() == Version::Two =>
475 self.context.force_one_line_chain.replace(true);
479 let result = last_item_shape(
485 .and_then(|arg_shape| {
486 self.rewrite_last_item_with_overflow(
487 &mut list_items[self.items.len() - 1],
491 self.context.force_one_line_chain.replace(old_value);
497 let mut tactic = definitive_tactic(
499 ListTactic::LimitedHorizontalVertical(self.item_max_width),
504 // Replace the stub with the full overflowing last argument if the rewrite
505 // succeeded and its first line fits with the other arguments.
506 match (overflow_last, tactic, placeholder) {
507 (true, DefinitiveListTactic::Horizontal, Some(ref overflowed))
508 if self.items.len() == 1 =>
510 // When we are rewriting a nested function call, we restrict the
511 // budget for the inner function to avoid them being deeply nested.
512 // However, when the inner function has a prefix or a suffix
513 // (e.g. `foo() as u32`), this budget reduction may produce poorly
514 // formatted code, where a prefix or a suffix being left on its own
515 // line. Here we explicitlly check those cases.
516 if count_newlines(overflowed) == 1 {
520 .and_then(|last_item| last_item.rewrite(self.context, self.nested_shape));
521 let no_newline = rw.as_ref().map_or(false, |s| !s.contains('\n'));
523 list_items[self.items.len() - 1].item = rw;
525 list_items[self.items.len() - 1].item = Some(overflowed.to_owned());
528 list_items[self.items.len() - 1].item = Some(overflowed.to_owned());
531 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
532 list_items[self.items.len() - 1].item = placeholder;
534 _ if !self.items.is_empty() => {
535 list_items[self.items.len() - 1].item = self
538 .and_then(|last_item| last_item.rewrite(self.context, self.nested_shape));
540 // Use horizontal layout for a function with a single argument as long as
541 // everything fits in a single line.
542 // `self.one_line_width == 0` means vertical layout is forced.
543 if self.items.len() == 1
544 && self.one_line_width != 0
545 && !list_items[0].has_comment()
546 && !list_items[0].inner_as_ref().contains('\n')
547 && ::lists::total_item_width(&list_items[0]) <= self.one_line_width
549 tactic = DefinitiveListTactic::Horizontal;
551 tactic = self.default_tactic(list_items);
553 if tactic == DefinitiveListTactic::Vertical {
554 if let Some((all_simple, num_args_before)) =
555 maybe_get_args_offset(self.ident, &self.items)
557 let one_line = all_simple
558 && definitive_tactic(
559 &list_items[..num_args_before],
560 ListTactic::HorizontalVertical,
562 self.nested_shape.width,
563 ) == DefinitiveListTactic::Horizontal
564 && definitive_tactic(
565 &list_items[num_args_before + 1..],
566 ListTactic::HorizontalVertical,
568 self.nested_shape.width,
569 ) == DefinitiveListTactic::Horizontal;
572 tactic = DefinitiveListTactic::SpecialMacro(num_args_before);
574 } else if is_every_expr_simple(&self.items) && no_long_items(list_items) {
575 tactic = DefinitiveListTactic::Mixed;
586 fn rewrite_items(&self) -> Option<(bool, String)> {
587 let span = self.items_span();
588 let items = itemize_list(
589 self.context.snippet_provider,
593 |item| item.span().lo(),
594 |item| item.span().hi(),
595 |item| item.rewrite(self.context, self.nested_shape),
600 let mut list_items: Vec<_> = items.collect();
602 // Try letting the last argument overflow to the next line with block
603 // indentation. If its first line fits on one line with the other arguments,
604 // we format the function arguments horizontally.
605 let tactic = self.try_overflow_last_item(&mut list_items);
606 let trailing_separator = if let Some(tactic) = self.force_separator_tactic {
608 } else if !self.context.use_block_indent() {
609 SeparatorTactic::Never
611 self.context.config.trailing_comma()
613 let ends_with_newline = match tactic {
614 DefinitiveListTactic::Vertical | DefinitiveListTactic::Mixed => {
615 self.context.use_block_indent()
620 let fmt = ListFormatting::new(self.nested_shape, self.context.config)
622 .trailing_separator(trailing_separator)
623 .ends_with_newline(ends_with_newline);
625 write_list(&list_items, &fmt)
626 .map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str))
629 fn wrap_items(&self, items_str: &str, shape: Shape, is_extendable: bool) -> String {
631 width: shape.width.saturating_sub(last_line_width(self.ident)),
635 let (prefix, suffix) = match self.custom_delims {
636 Some((lhs, rhs)) => (lhs, rhs),
637 _ => (self.prefix, self.suffix),
640 let extend_width = if items_str.is_empty() {
643 first_line_width(items_str) + 1
645 let nested_indent_str = self
648 .to_string_with_newline(self.context.config);
649 let indent_str = shape
652 .to_string_with_newline(self.context.config);
653 let mut result = String::with_capacity(
654 self.ident.len() + items_str.len() + 2 + indent_str.len() + nested_indent_str.len(),
656 result.push_str(self.ident);
657 result.push_str(prefix);
658 let force_single_line = if self.context.config.version() == Version::Two {
659 !self.context.use_block_indent() || (is_extendable && extend_width <= shape.width)
662 let fits_one_line = items_str.len() + 2 <= shape.width;
663 !self.context.use_block_indent()
664 || (self.context.inside_macro() && !items_str.contains('\n') && fits_one_line)
665 || (is_extendable && extend_width <= shape.width)
667 if force_single_line {
668 result.push_str(items_str);
670 if !items_str.is_empty() {
671 result.push_str(&nested_indent_str);
672 result.push_str(items_str);
674 result.push_str(&indent_str);
676 result.push_str(suffix);
680 fn rewrite(&self, shape: Shape) -> Option<String> {
681 let (extendable, items_str) = self.rewrite_items()?;
683 // If we are using visual indent style and failed to format, retry with block indent.
684 if !self.context.use_block_indent()
685 && need_block_indent(&items_str, self.nested_shape)
688 self.context.use_block.replace(true);
689 let result = self.rewrite(shape);
690 self.context.use_block.replace(false);
694 Some(self.wrap_items(&items_str, shape, extendable))
698 fn need_block_indent(s: &str, shape: Shape) -> bool {
699 s.lines().skip(1).any(|s| {
700 s.find(|c| !char::is_whitespace(c))
701 .map_or(false, |w| w + 1 < shape.indent.width())
705 fn can_be_overflowed(context: &RewriteContext, items: &[OverflowableItem]) -> bool {
708 .map_or(false, |x| x.can_be_overflowed(context, items.len()))
711 /// Returns a shape for the last argument which is going to be overflowed.
713 lists: &[OverflowableItem],
716 args_max_width: usize,
718 if items.len() == 1 && !lists.get(0)?.is_nested_call() {
721 let offset = items.iter().rev().skip(1).fold(0, |acc, i| {
723 acc + 2 + i.inner_as_ref().len()
726 width: min(args_max_width, shape.width),
732 fn shape_from_indent_style(
733 context: &RewriteContext,
738 let (shape, overhead) = if context.use_block_indent() {
741 .block_indent(context.config.tab_spaces())
742 .with_max_width(context.config);
743 (shape, 1) // 1 = ","
745 (shape.visual_indent(offset), overhead)
748 width: shape.width.saturating_sub(overhead),
753 fn no_long_items(list: &[ListItem]) -> bool {
755 .all(|item| item.inner_as_ref().len() <= SHORT_ITEM_THRESHOLD)
758 /// In case special-case style is required, returns an offset from which we start horizontal layout.
759 pub fn maybe_get_args_offset(callee_str: &str, args: &[OverflowableItem]) -> Option<(bool, usize)> {
760 if let Some(&(_, num_args_before)) = args
764 .find(|&&(s, _)| s == callee_str)
766 let all_simple = args.len() > num_args_before
767 && is_every_expr_simple(&args[0..num_args_before])
768 && is_every_expr_simple(&args[num_args_before + 1..]);
770 Some((all_simple, num_args_before))