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.saturating_sub(1);
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 {
488 item_max_width.unwrap_or(0).saturating_sub(inner_item_len)
491 pub struct ListItems<'a, I, F1, F2, F3>
495 snippet_provider: &'a SnippetProvider<'a>,
500 prev_span_end: BytePos,
501 next_span_start: BytePos,
507 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
509 I: Iterator<Item = T>,
510 F1: Fn(&T) -> BytePos,
511 F2: Fn(&T) -> BytePos,
512 F3: Fn(&T) -> Option<String>,
514 type Item = ListItem;
516 fn next(&mut self) -> Option<Self::Item> {
517 let white_space: &[_] = &[' ', '\t'];
519 self.inner.next().map(|item| {
520 let mut new_lines = false;
522 let pre_snippet = self
524 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
526 let trimmed_pre_snippet = pre_snippet.trim();
527 let has_single_line_comment = trimmed_pre_snippet.starts_with("//");
528 let has_block_comment = trimmed_pre_snippet.starts_with("/*");
529 let (pre_comment, pre_comment_style) = if has_single_line_comment {
531 Some(trimmed_pre_snippet.to_owned()),
532 ListItemCommentStyle::DifferentLine,
534 } else if has_block_comment {
535 let comment_end = pre_snippet.chars().rev().position(|c| c == '/').unwrap();
539 .take(comment_end + 1)
543 Some(trimmed_pre_snippet.to_owned()),
544 ListItemCommentStyle::DifferentLine,
548 Some(trimmed_pre_snippet.to_owned()),
549 ListItemCommentStyle::SameLine,
553 (None, ListItemCommentStyle::None)
557 let next_start = match self.inner.peek() {
558 Some(next_item) => (self.get_lo)(next_item),
559 None => self.next_span_start,
561 let post_snippet = self
563 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
566 let comment_end = match self.inner.peek() {
568 let mut block_open_index = post_snippet.find("/*");
569 // check if it really is a block comment (and not `//*` or a nested comment)
570 if let Some(i) = block_open_index {
571 match post_snippet.find('/') {
572 Some(j) if j < i => block_open_index = None,
573 _ if i > 0 && &post_snippet[i - 1..i] == "/" => block_open_index = None,
577 let newline_index = post_snippet.find('\n');
578 if let Some(separator_index) = post_snippet.find_uncommented(self.separator) {
579 match (block_open_index, newline_index) {
580 // Separator before comment, with the next item on same line.
581 // Comment belongs to next item.
582 (Some(i), None) if i > separator_index => separator_index + 1,
583 // Block-style post-comment before the separator.
584 (Some(i), None) => cmp::max(
585 find_comment_end(&post_snippet[i..]).unwrap() + i,
588 // Block-style post-comment. Either before or after the separator.
589 (Some(i), Some(j)) if i < j => cmp::max(
590 find_comment_end(&post_snippet[i..]).unwrap() + i,
593 // Potential *single* line comment.
594 (_, Some(j)) if j > separator_index => j + 1,
595 _ => post_snippet.len(),
597 } else if let Some(newline_index) = newline_index {
598 // Match arms may not have trailing comma. In any case, for match arms,
599 // we will assume that the post comment belongs to the next arm if they
600 // do not end with trailing comma.
607 .find_uncommented(self.terminator)
608 .unwrap_or_else(|| post_snippet.len()),
611 if !post_snippet.is_empty() && comment_end > 0 {
612 // Account for extra whitespace between items. This is fiddly
613 // because of the way we divide pre- and post- comments.
615 // Everything from the separator to the next item.
616 let test_snippet = &post_snippet[comment_end - 1..];
617 let first_newline = test_snippet
619 .unwrap_or_else(|| test_snippet.len());
620 // From the end of the first line of comments.
621 let test_snippet = &test_snippet[first_newline..];
622 let first = test_snippet
623 .find(|c: char| !c.is_whitespace())
624 .unwrap_or_else(|| test_snippet.len());
625 // From the end of the first line of comments to the next non-whitespace char.
626 let test_snippet = &test_snippet[..first];
628 if count_newlines(test_snippet) > 1 {
629 // There were multiple line breaks which got trimmed to nothing.
634 // Cleanup post-comment: strip separators and whitespace.
635 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
636 let post_snippet = post_snippet[..comment_end].trim();
638 let post_snippet_trimmed = if post_snippet.starts_with(|c| c == ',' || c == ':') {
639 post_snippet[1..].trim_matches(white_space)
640 } else if post_snippet.starts_with(self.separator) {
641 post_snippet[self.separator.len()..].trim_matches(white_space)
642 } else if post_snippet.ends_with(',') {
643 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
648 let post_comment = if !post_snippet_trimmed.is_empty() {
649 Some(post_snippet_trimmed.to_owned())
657 item: if self.inner.peek().is_none() && self.leave_last {
660 (self.get_item_string)(&item)
669 #[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
670 // Creates an iterator over a list's items with associated comments.
671 pub fn itemize_list<'a, T, I, F1, F2, F3>(
672 snippet_provider: &'a SnippetProvider,
679 prev_span_end: BytePos,
680 next_span_start: BytePos,
682 ) -> ListItems<'a, I, F1, F2, F3>
684 I: Iterator<Item = T>,
685 F1: Fn(&T) -> BytePos,
686 F2: Fn(&T) -> BytePos,
687 F3: Fn(&T) -> Option<String>,
691 inner: inner.peekable(),
703 /// Returns the count and total width of the list items.
704 fn calculate_width<I, T>(items: I) -> (usize, usize)
706 I: IntoIterator<Item = T>,
711 .map(|item| total_item_width(item.as_ref()))
712 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
715 pub fn total_item_width(item: &ListItem) -> usize {
716 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
717 + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
718 + item.item.as_ref().map_or(0, |str| str.len())
721 fn comment_len(comment: Option<&str>) -> usize {
724 let text_len = s.trim().len();
726 // We'll put " /*" before and " */" after inline comments.
736 // Compute horizontal and vertical shapes for a struct-lit-like thing.
737 pub fn struct_lit_shape(
739 context: &RewriteContext,
742 ) -> Option<(Option<Shape>, Shape)> {
743 let v_shape = match context.config.indent_style() {
744 IndentStyle::Visual => shape
746 .shrink_left(prefix_width)?
747 .sub_width(suffix_width)?,
748 IndentStyle::Block => {
749 let shape = shape.block_indent(context.config.tab_spaces());
751 width: context.budget(shape.indent.width()),
756 let shape_width = shape.width.checked_sub(prefix_width + suffix_width);
757 if let Some(w) = shape_width {
758 let shape_width = cmp::min(w, context.config.width_heuristics().struct_lit_width);
759 Some((Some(Shape::legacy(shape_width, shape.indent)), v_shape))
761 Some((None, v_shape))
765 // Compute the tactic for the internals of a struct-lit-like thing.
766 pub fn struct_lit_tactic(
767 h_shape: Option<Shape>,
768 context: &RewriteContext,
770 ) -> DefinitiveListTactic {
771 if let Some(h_shape) = h_shape {
772 let prelim_tactic = match (context.config.indent_style(), items.len()) {
773 (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
774 _ if context.config.struct_lit_single_line() => ListTactic::HorizontalVertical,
775 _ => ListTactic::Vertical,
777 definitive_tactic(items, prelim_tactic, Separator::Comma, h_shape.width)
779 DefinitiveListTactic::Vertical
783 // Given a tactic and possible shapes for horizontal and vertical layout,
784 // come up with the actual shape to use.
785 pub fn shape_for_tactic(
786 tactic: DefinitiveListTactic,
787 h_shape: Option<Shape>,
791 DefinitiveListTactic::Horizontal => h_shape.unwrap(),
796 // Create a ListFormatting object for formatting the internals of a
797 // struct-lit-like thing, that is a series of fields.
798 pub fn struct_lit_formatting<'a>(
800 tactic: DefinitiveListTactic,
801 context: &'a RewriteContext,
802 force_no_trailing_comma: bool,
803 ) -> ListFormatting<'a> {
804 let ends_with_newline = context.config.indent_style() != IndentStyle::Visual
805 && tactic == DefinitiveListTactic::Vertical;
809 trailing_separator: if force_no_trailing_comma {
810 SeparatorTactic::Never
812 context.config.trailing_comma()
814 separator_place: SeparatorPlace::Back,
817 preserve_newline: true,
818 config: context.config,