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 pub config: &'a Config,
40 impl<'a> ListFormatting<'a> {
41 pub fn needs_trailing_separator(&self) -> bool {
42 match self.trailing_separator {
43 // We always put separator in front.
44 SeparatorTactic::Always => true,
45 SeparatorTactic::Vertical => self.tactic == DefinitiveListTactic::Vertical,
46 SeparatorTactic::Never => {
47 self.tactic == DefinitiveListTactic::Vertical && self.separator_place.is_front()
53 impl AsRef<ListItem> for ListItem {
54 fn as_ref(&self) -> &ListItem {
59 #[derive(PartialEq, Eq, Debug, Copy, Clone)]
60 pub enum ListItemCommentStyle {
61 // Try to keep the comment on the same line with the item.
63 // Put the comment on the previous or the next line of the item.
65 // No comment available.
69 #[derive(Debug, Clone)]
71 // None for comments mean that they are not present.
72 pub pre_comment: Option<String>,
73 pub pre_comment_style: ListItemCommentStyle,
74 // Item should include attributes and doc comments. None indicates a failed
76 pub item: Option<String>,
77 pub post_comment: Option<String>,
78 // Whether there is extra whitespace before this item.
83 pub fn empty() -> ListItem {
86 pre_comment_style: ListItemCommentStyle::None,
93 pub fn inner_as_ref(&self) -> &str {
94 self.item.as_ref().map_or("", |s| s)
97 pub fn is_different_group(&self) -> bool {
98 self.inner_as_ref().contains('\n') || self.pre_comment.is_some()
102 .map_or(false, |s| s.contains('\n'))
105 pub fn is_multiline(&self) -> bool {
106 self.inner_as_ref().contains('\n')
110 .map_or(false, |s| s.contains('\n'))
114 .map_or(false, |s| s.contains('\n'))
117 pub fn has_single_line_comment(&self) -> bool {
120 .map_or(false, |comment| comment.trim_left().starts_with("//"))
124 .map_or(false, |comment| comment.trim_left().starts_with("//"))
127 pub fn has_comment(&self) -> bool {
128 self.pre_comment.is_some() || self.post_comment.is_some()
131 pub fn from_str<S: Into<String>>(s: S) -> ListItem {
134 pre_comment_style: ListItemCommentStyle::None,
135 item: Some(s.into()),
141 // true if the item causes something to be written.
142 fn is_substantial(&self) -> bool {
143 fn empty(s: &Option<String>) -> bool {
145 Some(ref s) if !s.is_empty() => false,
150 !(empty(&self.pre_comment) && empty(&self.item) && empty(&self.post_comment))
154 /// The type of separator for lists.
155 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
162 pub fn len(&self) -> usize {
165 Separator::Comma => 2,
167 Separator::VerticalBar => 3,
172 pub fn definitive_tactic<I, T>(
177 ) -> DefinitiveListTactic
179 I: IntoIterator<Item = T> + Clone,
182 let pre_line_comments = items
185 .any(|item| item.as_ref().has_single_line_comment());
187 let limit = match tactic {
188 _ if pre_line_comments => return DefinitiveListTactic::Vertical,
189 ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
190 ListTactic::Vertical => return DefinitiveListTactic::Vertical,
191 ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
192 ListTactic::Mixed | ListTactic::HorizontalVertical => width,
195 let (sep_count, total_width) = calculate_width(items.clone());
196 let total_sep_len = sep.len() * sep_count.checked_sub(1).unwrap_or(0);
197 let real_total = total_width + total_sep_len;
199 if real_total <= limit
200 && !pre_line_comments
201 && !items.into_iter().any(|item| item.as_ref().is_multiline())
203 DefinitiveListTactic::Horizontal
206 ListTactic::Mixed => DefinitiveListTactic::Mixed,
207 _ => DefinitiveListTactic::Vertical,
212 // Format a list of commented items into a string.
213 // TODO: add unit tests
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);
232 let mut line_len = 0;
233 let indent_str = &formatting.shape.indent.to_string(formatting.config);
234 while let Some((i, item)) = iter.next() {
235 let item = item.as_ref();
236 let inner_item = item.item.as_ref()?;
238 let last = iter.peek().is_none();
239 let mut separate = match sep_place {
240 SeparatorPlace::Front => !first,
241 SeparatorPlace::Back => !last || trailing_separator,
243 let item_sep_len = if separate { sep_len } else { 0 };
245 // Item string may be multi-line. Its length (used for block comment alignment)
246 // should be only the length of the last line.
247 let item_last_line = if item.is_multiline() {
248 inner_item.lines().last().unwrap_or("")
252 let mut item_last_line_width = item_last_line.len() + item_sep_len;
253 if item_last_line.starts_with(&**indent_str) {
254 item_last_line_width -= indent_str.len();
257 if !item.is_substantial() {
262 DefinitiveListTactic::Horizontal if !first => {
265 DefinitiveListTactic::SpecialMacro(num_args_before) => {
268 } else if i < num_args_before {
270 } else if i <= num_args_before + 1 {
272 result.push_str(indent_str);
277 DefinitiveListTactic::Vertical
278 if !first && !inner_item.is_empty() && !result.is_empty() =>
281 result.push_str(indent_str);
283 DefinitiveListTactic::Mixed => {
284 let total_width = total_item_width(item) + item_sep_len;
286 // 1 is space between separator and item.
287 if line_len > 0 && line_len + 1 + total_width > formatting.shape.width {
289 result.push_str(indent_str);
291 if formatting.ends_with_newline {
292 trailing_separator = true;
296 if last && formatting.ends_with_newline {
297 separate = formatting.trailing_separator != SeparatorTactic::Never;
305 line_len += total_width;
311 if let Some(ref comment) = item.pre_comment {
312 // Block style in non-vertical mode.
313 let block_mode = tactic != DefinitiveListTactic::Vertical;
314 // Width restriction is only relevant in vertical mode.
316 rewrite_comment(comment, block_mode, formatting.shape, formatting.config)?;
317 result.push_str(&comment);
319 if !inner_item.is_empty() {
320 if tactic == DefinitiveListTactic::Vertical {
321 // We cannot keep pre-comments on the same line if the comment if normalized.
322 let keep_comment = if formatting.config.normalize_comments()
323 || item.pre_comment_style == ListItemCommentStyle::DifferentLine
327 // We will try to keep the comment on the same line with the item here.
329 let total_width = total_item_width(item) + item_sep_len + 1;
330 total_width <= formatting.shape.width
336 result.push_str(indent_str);
342 item_max_width = None;
345 if separate && sep_place.is_front() && !first {
346 result.push_str(formatting.separator.trim());
349 result.push_str(inner_item);
352 if tactic != DefinitiveListTactic::Vertical && item.post_comment.is_some() {
353 let comment = item.post_comment.as_ref().unwrap();
354 let formatted_comment = rewrite_comment(
357 Shape::legacy(formatting.shape.width, Indent::empty()),
362 result.push_str(&formatted_comment);
365 if separate && sep_place.is_back() {
366 result.push_str(formatting.separator);
369 if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
370 let comment = item.post_comment.as_ref().unwrap();
371 let overhead = last_line_width(&result) + first_line_width(comment.trim());
373 let rewrite_post_comment = |item_max_width: &mut Option<usize>| {
374 if item_max_width.is_none() && !last && !inner_item.contains('\n') {
375 *item_max_width = Some(max_width_of_item_with_post_comment(
379 formatting.config.max_width(),
382 let overhead = if starts_with_newline(comment) {
384 } else if let Some(max_width) = *item_max_width {
387 // 1 = space between item and comment.
388 item_last_line_width + 1
390 let width = formatting.shape.width.checked_sub(overhead).unwrap_or(1);
391 let offset = formatting.shape.indent + overhead;
392 let comment_shape = Shape::legacy(width, offset);
394 // Use block-style only for the last item or multiline comments.
395 let block_style = !formatting.ends_with_newline && last
396 || comment.trim().contains('\n')
397 || comment.trim().len() > width;
407 let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?;
409 if !starts_with_newline(comment) {
410 let mut comment_alignment =
411 post_comment_alignment(item_max_width, inner_item.len());
412 if first_line_width(&formatted_comment)
413 + last_line_width(&result)
415 + 1 > formatting.config.max_width()
417 item_max_width = None;
418 formatted_comment = rewrite_post_comment(&mut item_max_width)?;
419 comment_alignment = post_comment_alignment(item_max_width, inner_item.len());
421 for _ in 0..(comment_alignment + 1) {
424 // An additional space for the missing trailing separator.
425 if last && item_max_width.is_some() && !separate && !formatting.separator.is_empty()
431 result.push_str(indent_str);
433 if formatted_comment.contains('\n') {
434 item_max_width = None;
436 result.push_str(&formatted_comment);
438 item_max_width = None;
441 if formatting.preserve_newline
443 && tactic == DefinitiveListTactic::Vertical
446 item_max_width = None;
454 fn max_width_of_item_with_post_comment<I, T>(
461 I: IntoIterator<Item = T> + Clone,
464 let mut max_width = 0;
465 let mut first = true;
466 for item in items.clone().into_iter().skip(i) {
467 let item = item.as_ref();
468 let inner_item_width = item.inner_as_ref().len();
470 && (item.is_different_group()
471 || item.post_comment.is_none()
472 || inner_item_width + overhead > max_budget)
476 if max_width < inner_item_width {
477 max_width = inner_item_width;
487 fn post_comment_alignment(item_max_width: Option<usize>, inner_item_len: usize) -> usize {
489 .and_then(|max_line_width| max_line_width.checked_sub(inner_item_len))
493 pub struct ListItems<'a, I, F1, F2, F3>
497 snippet_provider: &'a SnippetProvider<'a>,
502 prev_span_end: BytePos,
503 next_span_start: BytePos,
509 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
511 I: Iterator<Item = T>,
512 F1: Fn(&T) -> BytePos,
513 F2: Fn(&T) -> BytePos,
514 F3: Fn(&T) -> Option<String>,
516 type Item = ListItem;
518 fn next(&mut self) -> Option<Self::Item> {
519 let white_space: &[_] = &[' ', '\t'];
521 self.inner.next().map(|item| {
522 let mut new_lines = false;
524 let pre_snippet = self
526 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
528 let trimmed_pre_snippet = pre_snippet.trim();
529 let has_single_line_comment = trimmed_pre_snippet.starts_with("//");
530 let has_block_comment = trimmed_pre_snippet.starts_with("/*");
531 let (pre_comment, pre_comment_style) = if has_single_line_comment {
533 Some(trimmed_pre_snippet.to_owned()),
534 ListItemCommentStyle::DifferentLine,
536 } else if has_block_comment {
537 let comment_end = pre_snippet.chars().rev().position(|c| c == '/').unwrap();
541 .take(comment_end + 1)
545 Some(trimmed_pre_snippet.to_owned()),
546 ListItemCommentStyle::DifferentLine,
550 Some(trimmed_pre_snippet.to_owned()),
551 ListItemCommentStyle::SameLine,
555 (None, ListItemCommentStyle::None)
559 let next_start = match self.inner.peek() {
560 Some(next_item) => (self.get_lo)(next_item),
561 None => self.next_span_start,
563 let post_snippet = self
565 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
568 let comment_end = match self.inner.peek() {
570 let mut block_open_index = post_snippet.find("/*");
571 // check if it really is a block comment (and not `//*` or a nested comment)
572 if let Some(i) = block_open_index {
573 match post_snippet.find('/') {
574 Some(j) if j < i => block_open_index = None,
575 _ if i > 0 && &post_snippet[i - 1..i] == "/" => block_open_index = None,
579 let newline_index = post_snippet.find('\n');
580 if let Some(separator_index) = post_snippet.find_uncommented(self.separator) {
581 match (block_open_index, newline_index) {
582 // Separator before comment, with the next item on same line.
583 // Comment belongs to next item.
584 (Some(i), None) if i > separator_index => separator_index + 1,
585 // Block-style post-comment before the separator.
586 (Some(i), None) => cmp::max(
587 find_comment_end(&post_snippet[i..]).unwrap() + i,
590 // Block-style post-comment. Either before or after the separator.
591 (Some(i), Some(j)) if i < j => cmp::max(
592 find_comment_end(&post_snippet[i..]).unwrap() + i,
595 // Potential *single* line comment.
596 (_, Some(j)) if j > separator_index => j + 1,
597 _ => post_snippet.len(),
599 } else if let Some(newline_index) = newline_index {
600 // Match arms may not have trailing comma. In any case, for match arms,
601 // we will assume that the post comment belongs to the next arm if they
602 // do not end with trailing comma.
609 .find_uncommented(self.terminator)
610 .unwrap_or_else(|| post_snippet.len()),
613 if !post_snippet.is_empty() && comment_end > 0 {
614 // Account for extra whitespace between items. This is fiddly
615 // because of the way we divide pre- and post- comments.
617 // Everything from the separator to the next item.
618 let test_snippet = &post_snippet[comment_end - 1..];
619 let first_newline = test_snippet
621 .unwrap_or_else(|| test_snippet.len());
622 // From the end of the first line of comments.
623 let test_snippet = &test_snippet[first_newline..];
624 let first = test_snippet
625 .find(|c: char| !c.is_whitespace())
626 .unwrap_or_else(|| test_snippet.len());
627 // From the end of the first line of comments to the next non-whitespace char.
628 let test_snippet = &test_snippet[..first];
630 if count_newlines(test_snippet) > 1 {
631 // There were multiple line breaks which got trimmed to nothing.
636 // Cleanup post-comment: strip separators and whitespace.
637 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
638 let post_snippet = post_snippet[..comment_end].trim();
640 let post_snippet_trimmed = if post_snippet.starts_with(|c| c == ',' || c == ':') {
641 post_snippet[1..].trim_matches(white_space)
642 } else if post_snippet.starts_with(self.separator) {
643 post_snippet[self.separator.len()..].trim_matches(white_space)
644 } else if post_snippet.ends_with(',') {
645 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
650 let post_comment = if !post_snippet_trimmed.is_empty() {
651 Some(post_snippet_trimmed.to_owned())
659 item: if self.inner.peek().is_none() && self.leave_last {
662 (self.get_item_string)(&item)
671 #[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
672 // Creates an iterator over a list's items with associated comments.
673 pub fn itemize_list<'a, T, I, F1, F2, F3>(
674 snippet_provider: &'a SnippetProvider,
681 prev_span_end: BytePos,
682 next_span_start: BytePos,
684 ) -> ListItems<'a, I, F1, F2, F3>
686 I: Iterator<Item = T>,
687 F1: Fn(&T) -> BytePos,
688 F2: Fn(&T) -> BytePos,
689 F3: Fn(&T) -> Option<String>,
693 inner: inner.peekable(),
705 /// Returns the count and total width of the list items.
706 fn calculate_width<I, T>(items: I) -> (usize, usize)
708 I: IntoIterator<Item = T>,
713 .map(|item| total_item_width(item.as_ref()))
714 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
717 pub fn total_item_width(item: &ListItem) -> usize {
718 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
719 + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
720 + item.item.as_ref().map_or(0, |str| str.len())
723 fn comment_len(comment: Option<&str>) -> usize {
726 let text_len = s.trim().len();
728 // We'll put " /*" before and " */" after inline comments.
738 // Compute horizontal and vertical shapes for a struct-lit-like thing.
739 pub fn struct_lit_shape(
741 context: &RewriteContext,
744 ) -> Option<(Option<Shape>, Shape)> {
745 let v_shape = match context.config.indent_style() {
746 IndentStyle::Visual => shape
748 .shrink_left(prefix_width)?
749 .sub_width(suffix_width)?,
750 IndentStyle::Block => {
751 let shape = shape.block_indent(context.config.tab_spaces());
753 width: context.budget(shape.indent.width()),
758 let shape_width = shape.width.checked_sub(prefix_width + suffix_width);
759 if let Some(w) = shape_width {
760 let shape_width = cmp::min(w, context.config.width_heuristics().struct_lit_width);
761 Some((Some(Shape::legacy(shape_width, shape.indent)), v_shape))
763 Some((None, v_shape))
767 // Compute the tactic for the internals of a struct-lit-like thing.
768 pub fn struct_lit_tactic(
769 h_shape: Option<Shape>,
770 context: &RewriteContext,
772 ) -> DefinitiveListTactic {
773 if let Some(h_shape) = h_shape {
774 let prelim_tactic = match (context.config.indent_style(), items.len()) {
775 (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
776 _ if context.config.struct_lit_single_line() => ListTactic::HorizontalVertical,
777 _ => ListTactic::Vertical,
779 definitive_tactic(items, prelim_tactic, Separator::Comma, h_shape.width)
781 DefinitiveListTactic::Vertical
785 // Given a tactic and possible shapes for horizontal and vertical layout,
786 // come up with the actual shape to use.
787 pub fn shape_for_tactic(
788 tactic: DefinitiveListTactic,
789 h_shape: Option<Shape>,
793 DefinitiveListTactic::Horizontal => h_shape.unwrap(),
798 // Create a ListFormatting object for formatting the internals of a
799 // struct-lit-like thing, that is a series of fields.
800 pub fn struct_lit_formatting<'a>(
802 tactic: DefinitiveListTactic,
803 context: &'a RewriteContext,
804 force_no_trailing_comma: bool,
805 ) -> ListFormatting<'a> {
806 let ends_with_newline = context.config.indent_style() != IndentStyle::Visual
807 && tactic == DefinitiveListTactic::Vertical;
811 trailing_separator: if force_no_trailing_comma {
812 SeparatorTactic::Never
814 context.config.trailing_comma()
816 separator_place: SeparatorPlace::Back,
819 preserve_newline: true,
820 config: context.config,