1 // Copyright 2015 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 //! Format list-like expressions and items.
14 use std::iter::Peekable;
17 use syntax::source_map::BytePos;
19 use comment::{find_comment_end, rewrite_comment, FindUncommented};
20 use config::{Config, IndentStyle};
21 use rewrite::RewriteContext;
22 use shape::{Indent, Shape};
23 use utils::{count_newlines, first_line_width, last_line_width, mk_sp, starts_with_newline};
24 use visitor::SnippetProvider;
26 pub struct ListFormatting<'a> {
27 tactic: DefinitiveListTactic,
29 trailing_separator: SeparatorTactic,
30 separator_place: SeparatorPlace,
32 // Non-expressions, e.g. items, will have a new line at the end of the list.
33 // Important for comment styles.
34 ends_with_newline: bool,
35 // Remove newlines between list elements for expressions.
36 preserve_newline: bool,
37 // Nested import lists get some special handling for the "Mixed" list type
42 impl<'a> ListFormatting<'a> {
43 pub fn new(shape: Shape, config: &'a Config) -> Self {
45 tactic: DefinitiveListTactic::Vertical,
47 trailing_separator: SeparatorTactic::Never,
48 separator_place: SeparatorPlace::Back,
50 ends_with_newline: true,
51 preserve_newline: false,
57 pub fn tactic(mut self, tactic: DefinitiveListTactic) -> Self {
62 pub fn separator(mut self, separator: &'a str) -> Self {
63 self.separator = separator;
67 pub fn trailing_separator(mut self, trailing_separator: SeparatorTactic) -> Self {
68 self.trailing_separator = trailing_separator;
72 pub fn separator_place(mut self, separator_place: SeparatorPlace) -> Self {
73 self.separator_place = separator_place;
77 pub fn ends_with_newline(mut self, ends_with_newline: bool) -> Self {
78 self.ends_with_newline = ends_with_newline;
82 pub fn preserve_newline(mut self, preserve_newline: bool) -> Self {
83 self.preserve_newline = preserve_newline;
87 pub fn nested(mut self, nested: bool) -> Self {
92 pub fn needs_trailing_separator(&self) -> bool {
93 match self.trailing_separator {
94 // We always put separator in front.
95 SeparatorTactic::Always => true,
96 SeparatorTactic::Vertical => self.tactic == DefinitiveListTactic::Vertical,
97 SeparatorTactic::Never => {
98 self.tactic == DefinitiveListTactic::Vertical && self.separator_place.is_front()
104 impl AsRef<ListItem> for ListItem {
105 fn as_ref(&self) -> &ListItem {
110 #[derive(PartialEq, Eq, Debug, Copy, Clone)]
111 pub enum ListItemCommentStyle {
112 // Try to keep the comment on the same line with the item.
114 // Put the comment on the previous or the next line of the item.
116 // No comment available.
120 #[derive(Debug, Clone)]
121 pub struct ListItem {
122 // None for comments mean that they are not present.
123 pub pre_comment: Option<String>,
124 pub pre_comment_style: ListItemCommentStyle,
125 // Item should include attributes and doc comments. None indicates a failed
127 pub item: Option<String>,
128 pub post_comment: Option<String>,
129 // Whether there is extra whitespace before this item.
134 pub fn empty() -> ListItem {
137 pre_comment_style: ListItemCommentStyle::None,
144 pub fn inner_as_ref(&self) -> &str {
145 self.item.as_ref().map_or("", |s| s)
148 pub fn is_different_group(&self) -> bool {
149 self.inner_as_ref().contains('\n') || self.pre_comment.is_some() || self
152 .map_or(false, |s| s.contains('\n'))
155 pub fn is_multiline(&self) -> bool {
156 self.inner_as_ref().contains('\n')
160 .map_or(false, |s| s.contains('\n'))
164 .map_or(false, |s| s.contains('\n'))
167 pub fn has_single_line_comment(&self) -> bool {
170 .map_or(false, |comment| comment.trim_left().starts_with("//"))
174 .map_or(false, |comment| comment.trim_left().starts_with("//"))
177 pub fn has_comment(&self) -> bool {
178 self.pre_comment.is_some() || self.post_comment.is_some()
181 pub fn from_str<S: Into<String>>(s: S) -> ListItem {
184 pre_comment_style: ListItemCommentStyle::None,
185 item: Some(s.into()),
191 // true if the item causes something to be written.
192 fn is_substantial(&self) -> bool {
193 fn empty(s: &Option<String>) -> bool {
195 Some(ref s) if !s.is_empty() => false,
200 !(empty(&self.pre_comment) && empty(&self.item) && empty(&self.post_comment))
204 /// The type of separator for lists.
205 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
212 pub fn len(self) -> usize {
215 Separator::Comma => 2,
217 Separator::VerticalBar => 3,
222 pub fn definitive_tactic<I, T>(
227 ) -> DefinitiveListTactic
229 I: IntoIterator<Item = T> + Clone,
232 let pre_line_comments = items
235 .any(|item| item.as_ref().has_single_line_comment());
237 let limit = match tactic {
238 _ if pre_line_comments => return DefinitiveListTactic::Vertical,
239 ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
240 ListTactic::Vertical => return DefinitiveListTactic::Vertical,
241 ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
242 ListTactic::Mixed | ListTactic::HorizontalVertical => width,
245 let (sep_count, total_width) = calculate_width(items.clone());
246 let total_sep_len = sep.len() * sep_count.saturating_sub(1);
247 let real_total = total_width + total_sep_len;
249 if real_total <= limit
250 && !pre_line_comments
251 && !items.into_iter().any(|item| item.as_ref().is_multiline())
253 DefinitiveListTactic::Horizontal
256 ListTactic::Mixed => DefinitiveListTactic::Mixed,
257 _ => DefinitiveListTactic::Vertical,
262 // Format a list of commented items into a string.
263 pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
265 I: IntoIterator<Item = T> + Clone,
268 let tactic = formatting.tactic;
269 let sep_len = formatting.separator.len();
271 // Now that we know how we will layout, we can decide for sure if there
272 // will be a trailing separator.
273 let mut trailing_separator = formatting.needs_trailing_separator();
274 let mut result = String::with_capacity(128);
275 let cloned_items = items.clone();
276 let mut iter = items.into_iter().enumerate().peekable();
277 let mut item_max_width: Option<usize> = None;
279 SeparatorPlace::from_tactic(formatting.separator_place, tactic, formatting.separator);
280 let mut prev_item_had_post_comment = false;
281 let mut prev_item_is_nested_import = false;
283 let mut line_len = 0;
284 let indent_str = &formatting.shape.indent.to_string(formatting.config);
285 while let Some((i, item)) = iter.next() {
286 let item = item.as_ref();
287 let inner_item = item.item.as_ref()?;
289 let last = iter.peek().is_none();
290 let mut separate = match sep_place {
291 SeparatorPlace::Front => !first,
292 SeparatorPlace::Back => !last || trailing_separator,
294 let item_sep_len = if separate { sep_len } else { 0 };
296 // Item string may be multi-line. Its length (used for block comment alignment)
297 // should be only the length of the last line.
298 let item_last_line = if item.is_multiline() {
299 inner_item.lines().last().unwrap_or("")
303 let mut item_last_line_width = item_last_line.len() + item_sep_len;
304 if item_last_line.starts_with(&**indent_str) {
305 item_last_line_width -= indent_str.len();
308 if !item.is_substantial() {
313 DefinitiveListTactic::Horizontal if !first => {
316 DefinitiveListTactic::SpecialMacro(num_args_before) => {
319 } else if i < num_args_before {
321 } else if i <= num_args_before + 1 {
323 result.push_str(indent_str);
328 DefinitiveListTactic::Vertical
329 if !first && !inner_item.is_empty() && !result.is_empty() =>
332 result.push_str(indent_str);
334 DefinitiveListTactic::Mixed => {
335 let total_width = total_item_width(item) + item_sep_len;
337 // 1 is space between separator and item.
338 if (line_len > 0 && line_len + 1 + total_width > formatting.shape.width)
339 || prev_item_had_post_comment
340 || (formatting.nested
341 && (prev_item_is_nested_import || (!first && inner_item.contains("::"))))
344 result.push_str(indent_str);
346 if formatting.ends_with_newline {
347 trailing_separator = true;
349 } else if line_len > 0 {
354 if last && formatting.ends_with_newline {
355 separate = formatting.trailing_separator != SeparatorTactic::Never;
358 line_len += total_width;
364 if let Some(ref comment) = item.pre_comment {
365 // Block style in non-vertical mode.
366 let block_mode = tactic == DefinitiveListTactic::Horizontal;
367 // Width restriction is only relevant in vertical mode.
369 rewrite_comment(comment, block_mode, formatting.shape, formatting.config)?;
370 result.push_str(&comment);
372 if !inner_item.is_empty() {
373 if tactic == DefinitiveListTactic::Vertical || tactic == DefinitiveListTactic::Mixed
375 // We cannot keep pre-comments on the same line if the comment if normalized.
376 let keep_comment = if formatting.config.normalize_comments()
377 || item.pre_comment_style == ListItemCommentStyle::DifferentLine
381 // We will try to keep the comment on the same line with the item here.
383 let total_width = total_item_width(item) + item_sep_len + 1;
384 total_width <= formatting.shape.width
390 result.push_str(indent_str);
391 // This is the width of the item (without comments).
392 line_len = item.item.as_ref().map_or(0, |str| str.len());
398 item_max_width = None;
401 if separate && sep_place.is_front() && !first {
402 result.push_str(formatting.separator.trim());
405 result.push_str(inner_item);
408 if tactic == DefinitiveListTactic::Horizontal && item.post_comment.is_some() {
409 let comment = item.post_comment.as_ref().unwrap();
410 let formatted_comment = rewrite_comment(
413 Shape::legacy(formatting.shape.width, Indent::empty()),
418 result.push_str(&formatted_comment);
421 if separate && sep_place.is_back() {
422 result.push_str(formatting.separator);
425 if tactic != DefinitiveListTactic::Horizontal && item.post_comment.is_some() {
426 let comment = item.post_comment.as_ref().unwrap();
427 let overhead = last_line_width(&result) + first_line_width(comment.trim());
429 let rewrite_post_comment = |item_max_width: &mut Option<usize>| {
430 if item_max_width.is_none() && !last && !inner_item.contains('\n') {
431 *item_max_width = Some(max_width_of_item_with_post_comment(
435 formatting.config.max_width(),
438 let overhead = if starts_with_newline(comment) {
440 } else if let Some(max_width) = *item_max_width {
443 // 1 = space between item and comment.
444 item_last_line_width + 1
446 let width = formatting.shape.width.checked_sub(overhead).unwrap_or(1);
447 let offset = formatting.shape.indent + overhead;
448 let comment_shape = Shape::legacy(width, offset);
450 // Use block-style only for the last item or multiline comments.
451 let block_style = !formatting.ends_with_newline && last
452 || comment.trim().contains('\n')
453 || comment.trim().len() > width;
463 let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?;
465 if !starts_with_newline(comment) {
466 let mut comment_alignment =
467 post_comment_alignment(item_max_width, inner_item.len());
468 if first_line_width(&formatted_comment)
469 + last_line_width(&result)
472 > formatting.config.max_width()
474 item_max_width = None;
475 formatted_comment = rewrite_post_comment(&mut item_max_width)?;
476 comment_alignment = post_comment_alignment(item_max_width, inner_item.len());
478 for _ in 0..=comment_alignment {
481 // An additional space for the missing trailing separator.
482 if last && item_max_width.is_some() && !separate && !formatting.separator.is_empty()
488 result.push_str(indent_str);
490 if formatted_comment.contains('\n') {
491 item_max_width = None;
493 result.push_str(&formatted_comment);
495 item_max_width = None;
498 if formatting.preserve_newline
500 && tactic == DefinitiveListTactic::Vertical
503 item_max_width = None;
507 prev_item_had_post_comment = item.post_comment.is_some();
508 prev_item_is_nested_import = inner_item.contains("::");
514 fn max_width_of_item_with_post_comment<I, T>(
521 I: IntoIterator<Item = T> + Clone,
524 let mut max_width = 0;
525 let mut first = true;
526 for item in items.clone().into_iter().skip(i) {
527 let item = item.as_ref();
528 let inner_item_width = item.inner_as_ref().len();
530 && (item.is_different_group()
531 || item.post_comment.is_none()
532 || inner_item_width + overhead > max_budget)
536 if max_width < inner_item_width {
537 max_width = inner_item_width;
547 fn post_comment_alignment(item_max_width: Option<usize>, inner_item_len: usize) -> usize {
548 item_max_width.unwrap_or(0).saturating_sub(inner_item_len)
551 pub struct ListItems<'a, I, F1, F2, F3>
555 snippet_provider: &'a SnippetProvider<'a>,
560 prev_span_end: BytePos,
561 next_span_start: BytePos,
567 pub fn extract_pre_comment(pre_snippet: &str) -> (Option<String>, ListItemCommentStyle) {
568 let trimmed_pre_snippet = pre_snippet.trim();
569 let has_single_line_comment = trimmed_pre_snippet.starts_with("//");
570 let has_block_comment = trimmed_pre_snippet.starts_with("/*");
571 if has_single_line_comment {
573 Some(trimmed_pre_snippet.to_owned()),
574 ListItemCommentStyle::DifferentLine,
576 } else if has_block_comment {
577 let comment_end = pre_snippet.chars().rev().position(|c| c == '/').unwrap();
581 .take(comment_end + 1)
585 Some(trimmed_pre_snippet.to_owned()),
586 ListItemCommentStyle::DifferentLine,
590 Some(trimmed_pre_snippet.to_owned()),
591 ListItemCommentStyle::SameLine,
595 (None, ListItemCommentStyle::None)
599 pub fn extract_post_comment(
603 ) -> Option<String> {
604 let white_space: &[_] = &[' ', '\t'];
606 // Cleanup post-comment: strip separators and whitespace.
607 let post_snippet = post_snippet[..comment_end].trim();
608 let post_snippet_trimmed = if post_snippet.starts_with(|c| c == ',' || c == ':') {
609 post_snippet[1..].trim_matches(white_space)
610 } else if post_snippet.starts_with(separator) {
611 post_snippet[separator.len()..].trim_matches(white_space)
612 } else if post_snippet.ends_with(',') {
613 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
618 if !post_snippet_trimmed.is_empty() {
619 Some(post_snippet_trimmed.to_owned())
625 pub fn get_comment_end(
633 .find_uncommented(terminator)
634 .unwrap_or_else(|| post_snippet.len());
637 let mut block_open_index = post_snippet.find("/*");
638 // check if it really is a block comment (and not `//*` or a nested comment)
639 if let Some(i) = block_open_index {
640 match post_snippet.find('/') {
641 Some(j) if j < i => block_open_index = None,
642 _ if i > 0 && &post_snippet[i - 1..i] == "/" => block_open_index = None,
646 let newline_index = post_snippet.find('\n');
647 if let Some(separator_index) = post_snippet.find_uncommented(separator) {
648 match (block_open_index, newline_index) {
649 // Separator before comment, with the next item on same line.
650 // Comment belongs to next item.
651 (Some(i), None) if i > separator_index => separator_index + 1,
652 // Block-style post-comment before the separator.
653 (Some(i), None) => cmp::max(
654 find_comment_end(&post_snippet[i..]).unwrap() + i,
657 // Block-style post-comment. Either before or after the separator.
658 (Some(i), Some(j)) if i < j => cmp::max(
659 find_comment_end(&post_snippet[i..]).unwrap() + i,
662 // Potential *single* line comment.
663 (_, Some(j)) if j > separator_index => j + 1,
664 _ => post_snippet.len(),
666 } else if let Some(newline_index) = newline_index {
667 // Match arms may not have trailing comma. In any case, for match arms,
668 // we will assume that the post comment belongs to the next arm if they
669 // do not end with trailing comma.
676 // Account for extra whitespace between items. This is fiddly
677 // because of the way we divide pre- and post- comments.
678 fn has_extra_newline(post_snippet: &str, comment_end: usize) -> bool {
679 if post_snippet.is_empty() || comment_end == 0 {
683 // Everything from the separator to the next item.
684 let test_snippet = &post_snippet[comment_end - 1..];
685 let first_newline = test_snippet
687 .unwrap_or_else(|| test_snippet.len());
688 // From the end of the first line of comments.
689 let test_snippet = &test_snippet[first_newline..];
690 let first = test_snippet
691 .find(|c: char| !c.is_whitespace())
692 .unwrap_or_else(|| test_snippet.len());
693 // From the end of the first line of comments to the next non-whitespace char.
694 let test_snippet = &test_snippet[..first];
696 // There were multiple line breaks which got trimmed to nothing.
697 count_newlines(test_snippet) > 1
700 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
702 I: Iterator<Item = T>,
703 F1: Fn(&T) -> BytePos,
704 F2: Fn(&T) -> BytePos,
705 F3: Fn(&T) -> Option<String>,
707 type Item = ListItem;
709 fn next(&mut self) -> Option<Self::Item> {
710 self.inner.next().map(|item| {
712 let pre_snippet = self
714 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
716 let (pre_comment, pre_comment_style) = extract_pre_comment(pre_snippet);
719 let next_start = match self.inner.peek() {
720 Some(next_item) => (self.get_lo)(next_item),
721 None => self.next_span_start,
723 let post_snippet = self
725 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
727 let comment_end = get_comment_end(
731 self.inner.peek().is_none(),
733 let new_lines = has_extra_newline(post_snippet, comment_end);
734 let post_comment = extract_post_comment(post_snippet, comment_end, self.separator);
736 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
741 item: if self.inner.peek().is_none() && self.leave_last {
744 (self.get_item_string)(&item)
753 #[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
754 // Creates an iterator over a list's items with associated comments.
755 pub fn itemize_list<'a, T, I, F1, F2, F3>(
756 snippet_provider: &'a SnippetProvider,
763 prev_span_end: BytePos,
764 next_span_start: BytePos,
766 ) -> ListItems<'a, I, F1, F2, F3>
768 I: Iterator<Item = T>,
769 F1: Fn(&T) -> BytePos,
770 F2: Fn(&T) -> BytePos,
771 F3: Fn(&T) -> Option<String>,
775 inner: inner.peekable(),
787 /// Returns the count and total width of the list items.
788 fn calculate_width<I, T>(items: I) -> (usize, usize)
790 I: IntoIterator<Item = T>,
795 .map(|item| total_item_width(item.as_ref()))
796 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
799 pub fn total_item_width(item: &ListItem) -> usize {
800 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
801 + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
802 + item.item.as_ref().map_or(0, |str| str.len())
805 fn comment_len(comment: Option<&str>) -> usize {
808 let text_len = s.trim().len();
810 // We'll put " /*" before and " */" after inline comments.
820 // Compute horizontal and vertical shapes for a struct-lit-like thing.
821 pub fn struct_lit_shape(
823 context: &RewriteContext,
826 ) -> Option<(Option<Shape>, Shape)> {
827 let v_shape = match context.config.indent_style() {
828 IndentStyle::Visual => shape
830 .shrink_left(prefix_width)?
831 .sub_width(suffix_width)?,
832 IndentStyle::Block => {
833 let shape = shape.block_indent(context.config.tab_spaces());
835 width: context.budget(shape.indent.width()),
840 let shape_width = shape.width.checked_sub(prefix_width + suffix_width);
841 if let Some(w) = shape_width {
842 let shape_width = cmp::min(w, context.config.width_heuristics().struct_lit_width);
843 Some((Some(Shape::legacy(shape_width, shape.indent)), v_shape))
845 Some((None, v_shape))
849 // Compute the tactic for the internals of a struct-lit-like thing.
850 pub fn struct_lit_tactic(
851 h_shape: Option<Shape>,
852 context: &RewriteContext,
854 ) -> DefinitiveListTactic {
855 if let Some(h_shape) = h_shape {
856 let prelim_tactic = match (context.config.indent_style(), items.len()) {
857 (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
858 _ if context.config.struct_lit_single_line() => ListTactic::HorizontalVertical,
859 _ => ListTactic::Vertical,
861 definitive_tactic(items, prelim_tactic, Separator::Comma, h_shape.width)
863 DefinitiveListTactic::Vertical
867 // Given a tactic and possible shapes for horizontal and vertical layout,
868 // come up with the actual shape to use.
869 pub fn shape_for_tactic(
870 tactic: DefinitiveListTactic,
871 h_shape: Option<Shape>,
875 DefinitiveListTactic::Horizontal => h_shape.unwrap(),
880 // Create a ListFormatting object for formatting the internals of a
881 // struct-lit-like thing, that is a series of fields.
882 pub fn struct_lit_formatting<'a>(
884 tactic: DefinitiveListTactic,
885 context: &'a RewriteContext,
886 force_no_trailing_comma: bool,
887 ) -> ListFormatting<'a> {
888 let ends_with_newline = context.config.indent_style() != IndentStyle::Visual
889 && tactic == DefinitiveListTactic::Vertical;
893 trailing_separator: if force_no_trailing_comma {
894 SeparatorTactic::Never
896 context.config.trailing_comma()
898 separator_place: SeparatorPlace::Back,
901 preserve_newline: true,
903 config: context.config,