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 inner_as_ref(&self) -> &str {
84 self.item.as_ref().map_or("", |s| s)
87 pub fn is_different_group(&self) -> bool {
88 self.inner_as_ref().contains('\n') || self.pre_comment.is_some()
91 .map_or(false, |s| s.contains('\n'))
94 pub fn is_multiline(&self) -> bool {
95 self.inner_as_ref().contains('\n')
98 .map_or(false, |s| s.contains('\n'))
101 .map_or(false, |s| s.contains('\n'))
104 pub fn has_single_line_comment(&self) -> bool {
107 .map_or(false, |comment| comment.trim_left().starts_with("//"))
110 .map_or(false, |comment| comment.trim_left().starts_with("//"))
113 pub fn has_comment(&self) -> bool {
114 self.pre_comment.is_some() || self.post_comment.is_some()
117 pub fn from_str<S: Into<String>>(s: S) -> ListItem {
120 pre_comment_style: ListItemCommentStyle::None,
121 item: Some(s.into()),
127 // true if the item causes something to be written.
128 fn is_substantial(&self) -> bool {
129 fn empty(s: &Option<String>) -> bool {
131 Some(ref s) if !s.is_empty() => false,
136 !(empty(&self.pre_comment) && empty(&self.item) && empty(&self.post_comment))
140 /// The type of separator for lists.
141 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
148 pub fn len(&self) -> usize {
151 Separator::Comma => 2,
153 Separator::VerticalBar => 3,
158 pub fn definitive_tactic<I, T>(
163 ) -> DefinitiveListTactic
165 I: IntoIterator<Item = T> + Clone,
168 let pre_line_comments = items
171 .any(|item| item.as_ref().has_single_line_comment());
173 let limit = match tactic {
174 _ if pre_line_comments => return DefinitiveListTactic::Vertical,
175 ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
176 ListTactic::Vertical => return DefinitiveListTactic::Vertical,
177 ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
178 ListTactic::Mixed | ListTactic::HorizontalVertical => width,
181 let (sep_count, total_width) = calculate_width(items.clone());
182 let total_sep_len = sep.len() * sep_count.checked_sub(1).unwrap_or(0);
183 let real_total = total_width + total_sep_len;
185 if real_total <= limit && !pre_line_comments
186 && !items.into_iter().any(|item| item.as_ref().is_multiline())
188 DefinitiveListTactic::Horizontal
191 ListTactic::Mixed => DefinitiveListTactic::Mixed,
192 _ => DefinitiveListTactic::Vertical,
197 // Format a list of commented items into a string.
198 // TODO: add unit tests
199 pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
201 I: IntoIterator<Item = T> + Clone,
204 let tactic = formatting.tactic;
205 let sep_len = formatting.separator.len();
207 // Now that we know how we will layout, we can decide for sure if there
208 // will be a trailing separator.
209 let mut trailing_separator = formatting.needs_trailing_separator();
210 let mut result = String::with_capacity(128);
211 let cloned_items = items.clone();
212 let mut iter = items.into_iter().enumerate().peekable();
213 let mut item_max_width: Option<usize> = None;
215 SeparatorPlace::from_tactic(formatting.separator_place, tactic, formatting.separator);
217 let mut line_len = 0;
218 let indent_str = &formatting.shape.indent.to_string(formatting.config);
219 while let Some((i, item)) = iter.next() {
220 let item = item.as_ref();
221 let inner_item = item.item.as_ref()?;
223 let last = iter.peek().is_none();
224 let mut separate = match sep_place {
225 SeparatorPlace::Front => !first,
226 SeparatorPlace::Back => !last || trailing_separator,
228 let item_sep_len = if separate { sep_len } else { 0 };
230 // Item string may be multi-line. Its length (used for block comment alignment)
231 // should be only the length of the last line.
232 let item_last_line = if item.is_multiline() {
233 inner_item.lines().last().unwrap_or("")
237 let mut item_last_line_width = item_last_line.len() + item_sep_len;
238 if item_last_line.starts_with(&**indent_str) {
239 item_last_line_width -= indent_str.len();
242 if !item.is_substantial() {
247 DefinitiveListTactic::Horizontal if !first => {
250 DefinitiveListTactic::SpecialMacro(num_args_before) => {
253 } else if i < num_args_before {
255 } else if i <= num_args_before + 1 {
257 result.push_str(indent_str);
262 DefinitiveListTactic::Vertical
263 if !first && !inner_item.is_empty() && !result.is_empty() =>
266 result.push_str(indent_str);
268 DefinitiveListTactic::Mixed => {
269 let total_width = total_item_width(item) + item_sep_len;
271 // 1 is space between separator and item.
272 if line_len > 0 && line_len + 1 + total_width > formatting.shape.width {
274 result.push_str(indent_str);
276 if formatting.ends_with_newline {
277 trailing_separator = true;
281 if last && formatting.ends_with_newline {
282 separate = formatting.trailing_separator != SeparatorTactic::Never;
290 line_len += total_width;
296 if let Some(ref comment) = item.pre_comment {
297 // Block style in non-vertical mode.
298 let block_mode = tactic != DefinitiveListTactic::Vertical;
299 // Width restriction is only relevant in vertical mode.
301 rewrite_comment(comment, block_mode, formatting.shape, formatting.config)?;
302 result.push_str(&comment);
304 if !inner_item.is_empty() {
305 if tactic == DefinitiveListTactic::Vertical {
306 // We cannot keep pre-comments on the same line if the comment if normalized.
307 let keep_comment = if formatting.config.normalize_comments()
308 || item.pre_comment_style == ListItemCommentStyle::DifferentLine
312 // We will try to keep the comment on the same line with the item here.
314 let total_width = total_item_width(item) + item_sep_len + 1;
315 total_width <= formatting.shape.width
321 result.push_str(indent_str);
327 item_max_width = None;
330 if separate && sep_place.is_front() && !first {
331 result.push_str(formatting.separator.trim());
334 result.push_str(inner_item);
337 if tactic != DefinitiveListTactic::Vertical && item.post_comment.is_some() {
338 let comment = item.post_comment.as_ref().unwrap();
339 let formatted_comment = rewrite_comment(
342 Shape::legacy(formatting.shape.width, Indent::empty()),
347 result.push_str(&formatted_comment);
350 if separate && sep_place.is_back() {
351 result.push_str(formatting.separator);
354 if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
355 let comment = item.post_comment.as_ref().unwrap();
356 let overhead = last_line_width(&result) + first_line_width(comment.trim());
358 let rewrite_post_comment = |item_max_width: &mut Option<usize>| {
359 if item_max_width.is_none() && !last && !inner_item.contains('\n') {
360 *item_max_width = Some(max_width_of_item_with_post_comment(
364 formatting.config.max_width(),
367 let overhead = if starts_with_newline(comment) {
369 } else if let Some(max_width) = *item_max_width {
372 // 1 = space between item and comment.
373 item_last_line_width + 1
375 let width = formatting.shape.width.checked_sub(overhead).unwrap_or(1);
376 let offset = formatting.shape.indent + overhead;
377 let comment_shape = Shape::legacy(width, offset);
379 // Use block-style only for the last item or multiline comments.
380 let block_style = !formatting.ends_with_newline && last
381 || comment.trim().contains('\n')
382 || comment.trim().len() > width;
392 let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?;
394 if !starts_with_newline(comment) {
395 let mut comment_alignment =
396 post_comment_alignment(item_max_width, inner_item.len());
397 if first_line_width(&formatted_comment) + last_line_width(&result)
398 + comment_alignment + 1 > formatting.config.max_width()
400 item_max_width = None;
401 formatted_comment = rewrite_post_comment(&mut item_max_width)?;
402 comment_alignment = post_comment_alignment(item_max_width, inner_item.len());
404 for _ in 0..(comment_alignment + 1) {
407 // An additional space for the missing trailing separator.
408 if last && item_max_width.is_some() && !separate && !formatting.separator.is_empty()
414 result.push_str(indent_str);
416 if formatted_comment.contains('\n') {
417 item_max_width = None;
419 result.push_str(&formatted_comment);
421 item_max_width = None;
424 if formatting.preserve_newline && !last && tactic == DefinitiveListTactic::Vertical
427 item_max_width = None;
435 fn max_width_of_item_with_post_comment<I, T>(
442 I: IntoIterator<Item = T> + Clone,
445 let mut max_width = 0;
446 let mut first = true;
447 for item in items.clone().into_iter().skip(i) {
448 let item = item.as_ref();
449 let inner_item_width = item.inner_as_ref().len();
451 && (item.is_different_group() || !item.post_comment.is_some()
452 || inner_item_width + overhead > max_budget)
456 if max_width < inner_item_width {
457 max_width = inner_item_width;
467 fn post_comment_alignment(item_max_width: Option<usize>, inner_item_len: usize) -> usize {
469 .and_then(|max_line_width| max_line_width.checked_sub(inner_item_len))
473 pub struct ListItems<'a, I, F1, F2, F3>
477 snippet_provider: &'a SnippetProvider<'a>,
482 prev_span_end: BytePos,
483 next_span_start: BytePos,
489 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
491 I: Iterator<Item = T>,
492 F1: Fn(&T) -> BytePos,
493 F2: Fn(&T) -> BytePos,
494 F3: Fn(&T) -> Option<String>,
496 type Item = ListItem;
498 fn next(&mut self) -> Option<Self::Item> {
499 let white_space: &[_] = &[' ', '\t'];
501 self.inner.next().map(|item| {
502 let mut new_lines = false;
504 let pre_snippet = self.snippet_provider
505 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
507 let trimmed_pre_snippet = pre_snippet.trim();
508 let has_single_line_comment = trimmed_pre_snippet.starts_with("//");
509 let has_block_comment = trimmed_pre_snippet.starts_with("/*");
510 let (pre_comment, pre_comment_style) = if has_single_line_comment {
512 Some(trimmed_pre_snippet.to_owned()),
513 ListItemCommentStyle::DifferentLine,
515 } else if has_block_comment {
516 let comment_end = pre_snippet.chars().rev().position(|c| c == '/').unwrap();
520 .take(comment_end + 1)
524 Some(trimmed_pre_snippet.to_owned()),
525 ListItemCommentStyle::DifferentLine,
529 Some(trimmed_pre_snippet.to_owned()),
530 ListItemCommentStyle::SameLine,
534 (None, ListItemCommentStyle::None)
538 let next_start = match self.inner.peek() {
539 Some(next_item) => (self.get_lo)(next_item),
540 None => self.next_span_start,
542 let post_snippet = self.snippet_provider
543 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
546 let comment_end = match self.inner.peek() {
548 let mut block_open_index = post_snippet.find("/*");
549 // check if it really is a block comment (and not `//*` or a nested comment)
550 if let Some(i) = block_open_index {
551 match post_snippet.find('/') {
552 Some(j) if j < i => block_open_index = None,
553 _ if i > 0 && &post_snippet[i - 1..i] == "/" => block_open_index = None,
557 let newline_index = post_snippet.find('\n');
558 if let Some(separator_index) = post_snippet.find_uncommented(self.separator) {
559 match (block_open_index, newline_index) {
560 // Separator before comment, with the next item on same line.
561 // Comment belongs to next item.
562 (Some(i), None) if i > separator_index => separator_index + 1,
563 // Block-style post-comment before the separator.
564 (Some(i), None) => cmp::max(
565 find_comment_end(&post_snippet[i..]).unwrap() + i,
568 // Block-style post-comment. Either before or after the separator.
569 (Some(i), Some(j)) if i < j => cmp::max(
570 find_comment_end(&post_snippet[i..]).unwrap() + i,
573 // Potential *single* line comment.
574 (_, Some(j)) if j > separator_index => j + 1,
575 _ => post_snippet.len(),
577 } else if let Some(newline_index) = newline_index {
578 // Match arms may not have trailing comma. In any case, for match arms,
579 // we will assume that the post comment belongs to the next arm if they
580 // do not end with trailing comma.
587 .find_uncommented(self.terminator)
588 .unwrap_or_else(|| post_snippet.len()),
591 if !post_snippet.is_empty() && comment_end > 0 {
592 // Account for extra whitespace between items. This is fiddly
593 // because of the way we divide pre- and post- comments.
595 // Everything from the separator to the next item.
596 let test_snippet = &post_snippet[comment_end - 1..];
597 let first_newline = test_snippet
599 .unwrap_or_else(|| test_snippet.len());
600 // From the end of the first line of comments.
601 let test_snippet = &test_snippet[first_newline..];
602 let first = test_snippet
603 .find(|c: char| !c.is_whitespace())
604 .unwrap_or_else(|| test_snippet.len());
605 // From the end of the first line of comments to the next non-whitespace char.
606 let test_snippet = &test_snippet[..first];
608 if count_newlines(test_snippet) > 1 {
609 // There were multiple line breaks which got trimmed to nothing.
614 // Cleanup post-comment: strip separators and whitespace.
615 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
616 let post_snippet = post_snippet[..comment_end].trim();
618 let post_snippet_trimmed = if post_snippet.starts_with(|c| c == ',' || c == ':') {
619 post_snippet[1..].trim_matches(white_space)
620 } else if post_snippet.starts_with(self.separator) {
621 post_snippet[self.separator.len()..].trim_matches(white_space)
622 } else if post_snippet.ends_with(',') {
623 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
628 let post_comment = if !post_snippet_trimmed.is_empty() {
629 Some(post_snippet_trimmed.to_owned())
637 item: if self.inner.peek().is_none() && self.leave_last {
640 (self.get_item_string)(&item)
649 #[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
650 // Creates an iterator over a list's items with associated comments.
651 pub fn itemize_list<'a, T, I, F1, F2, F3>(
652 snippet_provider: &'a SnippetProvider,
659 prev_span_end: BytePos,
660 next_span_start: BytePos,
662 ) -> ListItems<'a, I, F1, F2, F3>
664 I: Iterator<Item = T>,
665 F1: Fn(&T) -> BytePos,
666 F2: Fn(&T) -> BytePos,
667 F3: Fn(&T) -> Option<String>,
671 inner: inner.peekable(),
683 /// Returns the count and total width of the list items.
684 fn calculate_width<I, T>(items: I) -> (usize, usize)
686 I: IntoIterator<Item = T>,
691 .map(|item| total_item_width(item.as_ref()))
692 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
695 pub fn total_item_width(item: &ListItem) -> usize {
696 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
697 + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
698 + item.item.as_ref().map_or(0, |str| str.len())
701 fn comment_len(comment: Option<&str>) -> usize {
704 let text_len = s.trim().len();
706 // We'll put " /*" before and " */" after inline comments.
716 // Compute horizontal and vertical shapes for a struct-lit-like thing.
717 pub fn struct_lit_shape(
719 context: &RewriteContext,
722 ) -> Option<(Option<Shape>, Shape)> {
723 let v_shape = match context.config.indent_style() {
724 IndentStyle::Visual => shape
726 .shrink_left(prefix_width)?
727 .sub_width(suffix_width)?,
728 IndentStyle::Block => {
729 let shape = shape.block_indent(context.config.tab_spaces());
731 width: context.budget(shape.indent.width()),
736 let shape_width = shape.width.checked_sub(prefix_width + suffix_width);
737 if let Some(w) = shape_width {
738 let shape_width = cmp::min(w, context.config.width_heuristics().struct_lit_width);
739 Some((Some(Shape::legacy(shape_width, shape.indent)), v_shape))
741 Some((None, v_shape))
745 // Compute the tactic for the internals of a struct-lit-like thing.
746 pub fn struct_lit_tactic(
747 h_shape: Option<Shape>,
748 context: &RewriteContext,
750 ) -> DefinitiveListTactic {
751 if let Some(h_shape) = h_shape {
752 let prelim_tactic = match (context.config.indent_style(), items.len()) {
753 (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
754 _ if context.config.struct_lit_single_line() => ListTactic::HorizontalVertical,
755 _ => ListTactic::Vertical,
757 definitive_tactic(items, prelim_tactic, Separator::Comma, h_shape.width)
759 DefinitiveListTactic::Vertical
763 // Given a tactic and possible shapes for horizontal and vertical layout,
764 // come up with the actual shape to use.
765 pub fn shape_for_tactic(
766 tactic: DefinitiveListTactic,
767 h_shape: Option<Shape>,
771 DefinitiveListTactic::Horizontal => h_shape.unwrap(),
776 // Create a ListFormatting object for formatting the internals of a
777 // struct-lit-like thing, that is a series of fields.
778 pub fn struct_lit_formatting<'a>(
780 tactic: DefinitiveListTactic,
781 context: &'a RewriteContext,
782 force_no_trailing_comma: bool,
783 ) -> ListFormatting<'a> {
784 let ends_with_newline = context.config.indent_style() != IndentStyle::Visual
785 && tactic == DefinitiveListTactic::Vertical;
789 trailing_separator: if force_no_trailing_comma {
790 SeparatorTactic::Never
792 context.config.trailing_comma()
794 separator_place: SeparatorPlace::Back,
797 preserve_newline: true,
798 config: context.config,