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::codemap::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 pub tactic: DefinitiveListTactic,
28 pub separator: &'a str,
29 pub trailing_separator: SeparatorTactic,
30 pub 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 pub ends_with_newline: bool,
35 // Remove newlines between list elements for expressions.
36 pub preserve_newline: bool,
37 // Nested import lists get some special handling for the "Mixed" list type
39 pub config: &'a Config,
42 impl<'a> ListFormatting<'a> {
43 pub fn needs_trailing_separator(&self) -> bool {
44 match self.trailing_separator {
45 // We always put separator in front.
46 SeparatorTactic::Always => true,
47 SeparatorTactic::Vertical => self.tactic == DefinitiveListTactic::Vertical,
48 SeparatorTactic::Never => {
49 self.tactic == DefinitiveListTactic::Vertical && self.separator_place.is_front()
55 impl AsRef<ListItem> for ListItem {
56 fn as_ref(&self) -> &ListItem {
61 #[derive(PartialEq, Eq, Debug, Copy, Clone)]
62 pub enum ListItemCommentStyle {
63 // Try to keep the comment on the same line with the item.
65 // Put the comment on the previous or the next line of the item.
67 // No comment available.
71 #[derive(Debug, Clone)]
73 // None for comments mean that they are not present.
74 pub pre_comment: Option<String>,
75 pub pre_comment_style: ListItemCommentStyle,
76 // Item should include attributes and doc comments. None indicates a failed
78 pub item: Option<String>,
79 pub post_comment: Option<String>,
80 // Whether there is extra whitespace before this item.
85 pub fn empty() -> ListItem {
88 pre_comment_style: ListItemCommentStyle::None,
95 pub fn inner_as_ref(&self) -> &str {
96 self.item.as_ref().map_or("", |s| s)
99 pub fn is_different_group(&self) -> bool {
100 self.inner_as_ref().contains('\n') || self.pre_comment.is_some() || self
103 .map_or(false, |s| s.contains('\n'))
106 pub fn is_multiline(&self) -> bool {
107 self.inner_as_ref().contains('\n')
111 .map_or(false, |s| s.contains('\n'))
115 .map_or(false, |s| s.contains('\n'))
118 pub fn has_single_line_comment(&self) -> bool {
121 .map_or(false, |comment| comment.trim_left().starts_with("//"))
125 .map_or(false, |comment| comment.trim_left().starts_with("//"))
128 pub fn has_comment(&self) -> bool {
129 self.pre_comment.is_some() || self.post_comment.is_some()
132 pub fn from_str<S: Into<String>>(s: S) -> ListItem {
135 pre_comment_style: ListItemCommentStyle::None,
136 item: Some(s.into()),
142 // true if the item causes something to be written.
143 fn is_substantial(&self) -> bool {
144 fn empty(s: &Option<String>) -> bool {
146 Some(ref s) if !s.is_empty() => false,
151 !(empty(&self.pre_comment) && empty(&self.item) && empty(&self.post_comment))
155 /// The type of separator for lists.
156 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
163 pub fn len(&self) -> usize {
166 Separator::Comma => 2,
168 Separator::VerticalBar => 3,
173 pub fn definitive_tactic<I, T>(
178 ) -> DefinitiveListTactic
180 I: IntoIterator<Item = T> + Clone,
183 let pre_line_comments = items
186 .any(|item| item.as_ref().has_single_line_comment());
188 let limit = match tactic {
189 _ if pre_line_comments => return DefinitiveListTactic::Vertical,
190 ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
191 ListTactic::Vertical => return DefinitiveListTactic::Vertical,
192 ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
193 ListTactic::Mixed | ListTactic::HorizontalVertical => width,
196 let (sep_count, total_width) = calculate_width(items.clone());
197 let total_sep_len = sep.len() * sep_count.saturating_sub(1);
198 let real_total = total_width + total_sep_len;
200 if real_total <= limit
201 && !pre_line_comments
202 && !items.into_iter().any(|item| item.as_ref().is_multiline())
204 DefinitiveListTactic::Horizontal
207 ListTactic::Mixed => DefinitiveListTactic::Mixed,
208 _ => DefinitiveListTactic::Vertical,
213 // Format a list of commented items into a string.
214 pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
216 I: IntoIterator<Item = T> + Clone,
219 let tactic = formatting.tactic;
220 let sep_len = formatting.separator.len();
222 // Now that we know how we will layout, we can decide for sure if there
223 // will be a trailing separator.
224 let mut trailing_separator = formatting.needs_trailing_separator();
225 let mut result = String::with_capacity(128);
226 let cloned_items = items.clone();
227 let mut iter = items.into_iter().enumerate().peekable();
228 let mut item_max_width: Option<usize> = None;
230 SeparatorPlace::from_tactic(formatting.separator_place, tactic, formatting.separator);
231 let mut prev_item_had_post_comment = false;
232 let mut prev_item_is_nested_import = false;
234 let mut line_len = 0;
235 let indent_str = &formatting.shape.indent.to_string(formatting.config);
236 while let Some((i, item)) = iter.next() {
237 let item = item.as_ref();
238 let inner_item = item.item.as_ref()?;
240 let last = iter.peek().is_none();
241 let mut separate = match sep_place {
242 SeparatorPlace::Front => !first,
243 SeparatorPlace::Back => !last || trailing_separator,
245 let item_sep_len = if separate { sep_len } else { 0 };
247 // Item string may be multi-line. Its length (used for block comment alignment)
248 // should be only the length of the last line.
249 let item_last_line = if item.is_multiline() {
250 inner_item.lines().last().unwrap_or("")
254 let mut item_last_line_width = item_last_line.len() + item_sep_len;
255 if item_last_line.starts_with(&**indent_str) {
256 item_last_line_width -= indent_str.len();
259 if !item.is_substantial() {
264 DefinitiveListTactic::Horizontal if !first => {
267 DefinitiveListTactic::SpecialMacro(num_args_before) => {
270 } else if i < num_args_before {
272 } else if i <= num_args_before + 1 {
274 result.push_str(indent_str);
279 DefinitiveListTactic::Vertical
280 if !first && !inner_item.is_empty() && !result.is_empty() =>
283 result.push_str(indent_str);
285 DefinitiveListTactic::Mixed => {
286 let total_width = total_item_width(item) + item_sep_len;
288 // 1 is space between separator and item.
289 if (line_len > 0 && line_len + 1 + total_width > formatting.shape.width)
290 || prev_item_had_post_comment
291 || (formatting.nested
292 && (prev_item_is_nested_import || (!first && inner_item.contains("::"))))
295 result.push_str(indent_str);
297 if formatting.ends_with_newline {
298 trailing_separator = true;
300 } else if line_len > 0 {
305 if last && formatting.ends_with_newline {
306 separate = formatting.trailing_separator != SeparatorTactic::Never;
309 line_len += total_width;
315 if let Some(ref comment) = item.pre_comment {
316 // Block style in non-vertical mode.
317 let block_mode = tactic == DefinitiveListTactic::Horizontal;
318 // Width restriction is only relevant in vertical mode.
320 rewrite_comment(comment, block_mode, formatting.shape, formatting.config)?;
321 result.push_str(&comment);
323 if !inner_item.is_empty() {
324 if tactic == DefinitiveListTactic::Vertical || tactic == DefinitiveListTactic::Mixed
326 // We cannot keep pre-comments on the same line if the comment if normalized.
327 let keep_comment = if formatting.config.normalize_comments()
328 || item.pre_comment_style == ListItemCommentStyle::DifferentLine
332 // We will try to keep the comment on the same line with the item here.
334 let total_width = total_item_width(item) + item_sep_len + 1;
335 total_width <= formatting.shape.width
341 result.push_str(indent_str);
342 // This is the width of the item (without comments).
343 line_len = item.item.as_ref().map_or(0, |str| str.len());
349 item_max_width = None;
352 if separate && sep_place.is_front() && !first {
353 result.push_str(formatting.separator.trim());
356 result.push_str(inner_item);
359 if tactic == DefinitiveListTactic::Horizontal && item.post_comment.is_some() {
360 let comment = item.post_comment.as_ref().unwrap();
361 let formatted_comment = rewrite_comment(
364 Shape::legacy(formatting.shape.width, Indent::empty()),
369 result.push_str(&formatted_comment);
372 if separate && sep_place.is_back() {
373 result.push_str(formatting.separator);
376 if tactic != DefinitiveListTactic::Horizontal && item.post_comment.is_some() {
377 let comment = item.post_comment.as_ref().unwrap();
378 let overhead = last_line_width(&result) + first_line_width(comment.trim());
380 let rewrite_post_comment = |item_max_width: &mut Option<usize>| {
381 if item_max_width.is_none() && !last && !inner_item.contains('\n') {
382 *item_max_width = Some(max_width_of_item_with_post_comment(
386 formatting.config.max_width(),
389 let overhead = if starts_with_newline(comment) {
391 } else if let Some(max_width) = *item_max_width {
394 // 1 = space between item and comment.
395 item_last_line_width + 1
397 let width = formatting.shape.width.checked_sub(overhead).unwrap_or(1);
398 let offset = formatting.shape.indent + overhead;
399 let comment_shape = Shape::legacy(width, offset);
401 // Use block-style only for the last item or multiline comments.
402 let block_style = !formatting.ends_with_newline && last
403 || comment.trim().contains('\n')
404 || comment.trim().len() > width;
414 let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?;
416 if !starts_with_newline(comment) {
417 let mut comment_alignment =
418 post_comment_alignment(item_max_width, inner_item.len());
419 if first_line_width(&formatted_comment)
420 + last_line_width(&result)
423 > formatting.config.max_width()
425 item_max_width = None;
426 formatted_comment = rewrite_post_comment(&mut item_max_width)?;
427 comment_alignment = post_comment_alignment(item_max_width, inner_item.len());
429 for _ in 0..(comment_alignment + 1) {
432 // An additional space for the missing trailing separator.
433 if last && item_max_width.is_some() && !separate && !formatting.separator.is_empty()
439 result.push_str(indent_str);
441 if formatted_comment.contains('\n') {
442 item_max_width = None;
444 result.push_str(&formatted_comment);
446 item_max_width = None;
449 if formatting.preserve_newline
451 && tactic == DefinitiveListTactic::Vertical
454 item_max_width = None;
458 prev_item_had_post_comment = item.post_comment.is_some();
459 prev_item_is_nested_import = inner_item.contains("::");
465 fn max_width_of_item_with_post_comment<I, T>(
472 I: IntoIterator<Item = T> + Clone,
475 let mut max_width = 0;
476 let mut first = true;
477 for item in items.clone().into_iter().skip(i) {
478 let item = item.as_ref();
479 let inner_item_width = item.inner_as_ref().len();
481 && (item.is_different_group()
482 || item.post_comment.is_none()
483 || inner_item_width + overhead > max_budget)
487 if max_width < inner_item_width {
488 max_width = inner_item_width;
498 fn post_comment_alignment(item_max_width: Option<usize>, inner_item_len: usize) -> usize {
499 item_max_width.unwrap_or(0).saturating_sub(inner_item_len)
502 pub struct ListItems<'a, I, F1, F2, F3>
506 snippet_provider: &'a SnippetProvider<'a>,
511 prev_span_end: BytePos,
512 next_span_start: BytePos,
518 pub fn extract_pre_comment(pre_snippet: &str) -> (Option<String>, ListItemCommentStyle) {
519 let trimmed_pre_snippet = pre_snippet.trim();
520 let has_single_line_comment = trimmed_pre_snippet.starts_with("//");
521 let has_block_comment = trimmed_pre_snippet.starts_with("/*");
522 if has_single_line_comment {
524 Some(trimmed_pre_snippet.to_owned()),
525 ListItemCommentStyle::DifferentLine,
527 } else if has_block_comment {
528 let comment_end = pre_snippet.chars().rev().position(|c| c == '/').unwrap();
532 .take(comment_end + 1)
536 Some(trimmed_pre_snippet.to_owned()),
537 ListItemCommentStyle::DifferentLine,
541 Some(trimmed_pre_snippet.to_owned()),
542 ListItemCommentStyle::SameLine,
546 (None, ListItemCommentStyle::None)
550 pub fn extract_post_comment(
554 ) -> Option<String> {
555 let white_space: &[_] = &[' ', '\t'];
557 // Cleanup post-comment: strip separators and whitespace.
558 let post_snippet = post_snippet[..comment_end].trim();
559 let post_snippet_trimmed = if post_snippet.starts_with(|c| c == ',' || c == ':') {
560 post_snippet[1..].trim_matches(white_space)
561 } else if post_snippet.starts_with(separator) {
562 post_snippet[separator.len()..].trim_matches(white_space)
563 } else if post_snippet.ends_with(',') {
564 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
569 if !post_snippet_trimmed.is_empty() {
570 Some(post_snippet_trimmed.to_owned())
576 pub fn get_comment_end(
584 .find_uncommented(terminator)
585 .unwrap_or_else(|| post_snippet.len());
588 let mut block_open_index = post_snippet.find("/*");
589 // check if it really is a block comment (and not `//*` or a nested comment)
590 if let Some(i) = block_open_index {
591 match post_snippet.find('/') {
592 Some(j) if j < i => block_open_index = None,
593 _ if i > 0 && &post_snippet[i - 1..i] == "/" => block_open_index = None,
597 let newline_index = post_snippet.find('\n');
598 if let Some(separator_index) = post_snippet.find_uncommented(separator) {
599 match (block_open_index, newline_index) {
600 // Separator before comment, with the next item on same line.
601 // Comment belongs to next item.
602 (Some(i), None) if i > separator_index => separator_index + 1,
603 // Block-style post-comment before the separator.
604 (Some(i), None) => cmp::max(
605 find_comment_end(&post_snippet[i..]).unwrap() + i,
608 // Block-style post-comment. Either before or after the separator.
609 (Some(i), Some(j)) if i < j => cmp::max(
610 find_comment_end(&post_snippet[i..]).unwrap() + i,
613 // Potential *single* line comment.
614 (_, Some(j)) if j > separator_index => j + 1,
615 _ => post_snippet.len(),
617 } else if let Some(newline_index) = newline_index {
618 // Match arms may not have trailing comma. In any case, for match arms,
619 // we will assume that the post comment belongs to the next arm if they
620 // do not end with trailing comma.
627 // Account for extra whitespace between items. This is fiddly
628 // because of the way we divide pre- and post- comments.
629 fn has_extra_newline(post_snippet: &str, comment_end: usize) -> bool {
630 if post_snippet.is_empty() || comment_end == 0 {
634 // Everything from the separator to the next item.
635 let test_snippet = &post_snippet[comment_end - 1..];
636 let first_newline = test_snippet
638 .unwrap_or_else(|| test_snippet.len());
639 // From the end of the first line of comments.
640 let test_snippet = &test_snippet[first_newline..];
641 let first = test_snippet
642 .find(|c: char| !c.is_whitespace())
643 .unwrap_or_else(|| test_snippet.len());
644 // From the end of the first line of comments to the next non-whitespace char.
645 let test_snippet = &test_snippet[..first];
647 // There were multiple line breaks which got trimmed to nothing.
648 count_newlines(test_snippet) > 1
651 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
653 I: Iterator<Item = T>,
654 F1: Fn(&T) -> BytePos,
655 F2: Fn(&T) -> BytePos,
656 F3: Fn(&T) -> Option<String>,
658 type Item = ListItem;
660 fn next(&mut self) -> Option<Self::Item> {
661 self.inner.next().map(|item| {
663 let pre_snippet = self
665 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
667 let (pre_comment, pre_comment_style) = extract_pre_comment(pre_snippet);
670 let next_start = match self.inner.peek() {
671 Some(next_item) => (self.get_lo)(next_item),
672 None => self.next_span_start,
674 let post_snippet = self
676 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
678 let comment_end = get_comment_end(
682 self.inner.peek().is_none(),
684 let new_lines = has_extra_newline(post_snippet, comment_end);
685 let post_comment = extract_post_comment(post_snippet, comment_end, self.separator);
687 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
692 item: if self.inner.peek().is_none() && self.leave_last {
695 (self.get_item_string)(&item)
704 #[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
705 // Creates an iterator over a list's items with associated comments.
706 pub fn itemize_list<'a, T, I, F1, F2, F3>(
707 snippet_provider: &'a SnippetProvider,
714 prev_span_end: BytePos,
715 next_span_start: BytePos,
717 ) -> ListItems<'a, I, F1, F2, F3>
719 I: Iterator<Item = T>,
720 F1: Fn(&T) -> BytePos,
721 F2: Fn(&T) -> BytePos,
722 F3: Fn(&T) -> Option<String>,
726 inner: inner.peekable(),
738 /// Returns the count and total width of the list items.
739 fn calculate_width<I, T>(items: I) -> (usize, usize)
741 I: IntoIterator<Item = T>,
746 .map(|item| total_item_width(item.as_ref()))
747 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
750 pub fn total_item_width(item: &ListItem) -> usize {
751 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
752 + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
753 + item.item.as_ref().map_or(0, |str| str.len())
756 fn comment_len(comment: Option<&str>) -> usize {
759 let text_len = s.trim().len();
761 // We'll put " /*" before and " */" after inline comments.
771 // Compute horizontal and vertical shapes for a struct-lit-like thing.
772 pub fn struct_lit_shape(
774 context: &RewriteContext,
777 ) -> Option<(Option<Shape>, Shape)> {
778 let v_shape = match context.config.indent_style() {
779 IndentStyle::Visual => shape
781 .shrink_left(prefix_width)?
782 .sub_width(suffix_width)?,
783 IndentStyle::Block => {
784 let shape = shape.block_indent(context.config.tab_spaces());
786 width: context.budget(shape.indent.width()),
791 let shape_width = shape.width.checked_sub(prefix_width + suffix_width);
792 if let Some(w) = shape_width {
793 let shape_width = cmp::min(w, context.config.width_heuristics().struct_lit_width);
794 Some((Some(Shape::legacy(shape_width, shape.indent)), v_shape))
796 Some((None, v_shape))
800 // Compute the tactic for the internals of a struct-lit-like thing.
801 pub fn struct_lit_tactic(
802 h_shape: Option<Shape>,
803 context: &RewriteContext,
805 ) -> DefinitiveListTactic {
806 if let Some(h_shape) = h_shape {
807 let prelim_tactic = match (context.config.indent_style(), items.len()) {
808 (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
809 _ if context.config.struct_lit_single_line() => ListTactic::HorizontalVertical,
810 _ => ListTactic::Vertical,
812 definitive_tactic(items, prelim_tactic, Separator::Comma, h_shape.width)
814 DefinitiveListTactic::Vertical
818 // Given a tactic and possible shapes for horizontal and vertical layout,
819 // come up with the actual shape to use.
820 pub fn shape_for_tactic(
821 tactic: DefinitiveListTactic,
822 h_shape: Option<Shape>,
826 DefinitiveListTactic::Horizontal => h_shape.unwrap(),
831 // Create a ListFormatting object for formatting the internals of a
832 // struct-lit-like thing, that is a series of fields.
833 pub fn struct_lit_formatting<'a>(
835 tactic: DefinitiveListTactic,
836 context: &'a RewriteContext,
837 force_no_trailing_comma: bool,
838 ) -> ListFormatting<'a> {
839 let ends_with_newline = context.config.indent_style() != IndentStyle::Visual
840 && tactic == DefinitiveListTactic::Vertical;
844 trailing_separator: if force_no_trailing_comma {
845 SeparatorTactic::Never
847 context.config.trailing_comma()
849 separator_place: SeparatorPlace::Back,
852 preserve_newline: true,
854 config: context.config,