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()
101 .map_or(false, |s| s.contains('\n'))
104 pub fn is_multiline(&self) -> bool {
105 self.inner_as_ref().contains('\n')
108 .map_or(false, |s| s.contains('\n'))
111 .map_or(false, |s| s.contains('\n'))
114 pub fn has_single_line_comment(&self) -> bool {
117 .map_or(false, |comment| comment.trim_left().starts_with("//"))
120 .map_or(false, |comment| comment.trim_left().starts_with("//"))
123 pub fn has_comment(&self) -> bool {
124 self.pre_comment.is_some() || self.post_comment.is_some()
127 pub fn from_str<S: Into<String>>(s: S) -> ListItem {
130 pre_comment_style: ListItemCommentStyle::None,
131 item: Some(s.into()),
137 // true if the item causes something to be written.
138 fn is_substantial(&self) -> bool {
139 fn empty(s: &Option<String>) -> bool {
141 Some(ref s) if !s.is_empty() => false,
146 !(empty(&self.pre_comment) && empty(&self.item) && empty(&self.post_comment))
150 /// The type of separator for lists.
151 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
158 pub fn len(&self) -> usize {
161 Separator::Comma => 2,
163 Separator::VerticalBar => 3,
168 pub fn definitive_tactic<I, T>(
173 ) -> DefinitiveListTactic
175 I: IntoIterator<Item = T> + Clone,
178 let pre_line_comments = items
181 .any(|item| item.as_ref().has_single_line_comment());
183 let limit = match tactic {
184 _ if pre_line_comments => return DefinitiveListTactic::Vertical,
185 ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
186 ListTactic::Vertical => return DefinitiveListTactic::Vertical,
187 ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
188 ListTactic::Mixed | ListTactic::HorizontalVertical => width,
191 let (sep_count, total_width) = calculate_width(items.clone());
192 let total_sep_len = sep.len() * sep_count.checked_sub(1).unwrap_or(0);
193 let real_total = total_width + total_sep_len;
195 if real_total <= limit && !pre_line_comments
196 && !items.into_iter().any(|item| item.as_ref().is_multiline())
198 DefinitiveListTactic::Horizontal
201 ListTactic::Mixed => DefinitiveListTactic::Mixed,
202 _ => DefinitiveListTactic::Vertical,
207 // Format a list of commented items into a string.
208 // TODO: add unit tests
209 pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
211 I: IntoIterator<Item = T> + Clone,
214 let tactic = formatting.tactic;
215 let sep_len = formatting.separator.len();
217 // Now that we know how we will layout, we can decide for sure if there
218 // will be a trailing separator.
219 let mut trailing_separator = formatting.needs_trailing_separator();
220 let mut result = String::with_capacity(128);
221 let cloned_items = items.clone();
222 let mut iter = items.into_iter().enumerate().peekable();
223 let mut item_max_width: Option<usize> = None;
225 SeparatorPlace::from_tactic(formatting.separator_place, tactic, formatting.separator);
227 let mut line_len = 0;
228 let indent_str = &formatting.shape.indent.to_string(formatting.config);
229 while let Some((i, item)) = iter.next() {
230 let item = item.as_ref();
231 let inner_item = item.item.as_ref()?;
233 let last = iter.peek().is_none();
234 let mut separate = match sep_place {
235 SeparatorPlace::Front => !first,
236 SeparatorPlace::Back => !last || trailing_separator,
238 let item_sep_len = if separate { sep_len } else { 0 };
240 // Item string may be multi-line. Its length (used for block comment alignment)
241 // should be only the length of the last line.
242 let item_last_line = if item.is_multiline() {
243 inner_item.lines().last().unwrap_or("")
247 let mut item_last_line_width = item_last_line.len() + item_sep_len;
248 if item_last_line.starts_with(&**indent_str) {
249 item_last_line_width -= indent_str.len();
252 if !item.is_substantial() {
257 DefinitiveListTactic::Horizontal if !first => {
260 DefinitiveListTactic::SpecialMacro(num_args_before) => {
263 } else if i < num_args_before {
265 } else if i <= num_args_before + 1 {
267 result.push_str(indent_str);
272 DefinitiveListTactic::Vertical
273 if !first && !inner_item.is_empty() && !result.is_empty() =>
276 result.push_str(indent_str);
278 DefinitiveListTactic::Mixed => {
279 let total_width = total_item_width(item) + item_sep_len;
281 // 1 is space between separator and item.
282 if line_len > 0 && line_len + 1 + total_width > formatting.shape.width {
284 result.push_str(indent_str);
286 if formatting.ends_with_newline {
287 trailing_separator = true;
291 if last && formatting.ends_with_newline {
292 match formatting.trailing_separator {
293 SeparatorTactic::Always | SeparatorTactic::Vertical => separate = true,
303 line_len += total_width;
309 if let Some(ref comment) = item.pre_comment {
310 // Block style in non-vertical mode.
311 let block_mode = tactic != DefinitiveListTactic::Vertical;
312 // Width restriction is only relevant in vertical mode.
314 rewrite_comment(comment, block_mode, formatting.shape, formatting.config)?;
315 result.push_str(&comment);
317 if !inner_item.is_empty() {
318 if tactic == DefinitiveListTactic::Vertical {
319 // We cannot keep pre-comments on the same line if the comment if normalized.
320 let keep_comment = if formatting.config.normalize_comments()
321 || item.pre_comment_style == ListItemCommentStyle::DifferentLine
325 // We will try to keep the comment on the same line with the item here.
327 let total_width = total_item_width(item) + item_sep_len + 1;
328 total_width <= formatting.shape.width
334 result.push_str(indent_str);
340 item_max_width = None;
343 if separate && sep_place.is_front() && !first {
344 result.push_str(formatting.separator.trim());
347 result.push_str(inner_item);
350 if tactic != DefinitiveListTactic::Vertical && item.post_comment.is_some() {
351 let comment = item.post_comment.as_ref().unwrap();
352 let formatted_comment = rewrite_comment(
355 Shape::legacy(formatting.shape.width, Indent::empty()),
360 result.push_str(&formatted_comment);
363 if separate && sep_place.is_back() {
364 result.push_str(formatting.separator);
367 if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
368 let comment = item.post_comment.as_ref().unwrap();
369 let overhead = last_line_width(&result) + first_line_width(comment.trim());
371 let rewrite_post_comment = |item_max_width: &mut Option<usize>| {
372 if item_max_width.is_none() && !last && !inner_item.contains('\n') {
373 *item_max_width = Some(max_width_of_item_with_post_comment(
377 formatting.config.max_width(),
380 let overhead = if starts_with_newline(comment) {
382 } else if let Some(max_width) = *item_max_width {
385 // 1 = space between item and comment.
386 item_last_line_width + 1
388 let width = formatting.shape.width.checked_sub(overhead).unwrap_or(1);
389 let offset = formatting.shape.indent + overhead;
390 let comment_shape = Shape::legacy(width, offset);
392 // Use block-style only for the last item or multiline comments.
393 let block_style = !formatting.ends_with_newline && last
394 || comment.trim().contains('\n')
395 || comment.trim().len() > width;
405 let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?;
407 if !starts_with_newline(comment) {
408 let mut comment_alignment =
409 post_comment_alignment(item_max_width, inner_item.len());
410 if first_line_width(&formatted_comment) + last_line_width(&result)
411 + comment_alignment + 1 > formatting.config.max_width()
413 item_max_width = None;
414 formatted_comment = rewrite_post_comment(&mut item_max_width)?;
415 comment_alignment = post_comment_alignment(item_max_width, inner_item.len());
417 for _ in 0..(comment_alignment + 1) {
420 // An additional space for the missing trailing separator.
421 if last && item_max_width.is_some() && !separate && !formatting.separator.is_empty()
427 result.push_str(indent_str);
429 if formatted_comment.contains('\n') {
430 item_max_width = None;
432 result.push_str(&formatted_comment);
434 item_max_width = None;
437 if formatting.preserve_newline && !last && tactic == DefinitiveListTactic::Vertical
440 item_max_width = None;
448 fn max_width_of_item_with_post_comment<I, T>(
455 I: IntoIterator<Item = T> + Clone,
458 let mut max_width = 0;
459 let mut first = true;
460 for item in items.clone().into_iter().skip(i) {
461 let item = item.as_ref();
462 let inner_item_width = item.inner_as_ref().len();
464 && (item.is_different_group() || !item.post_comment.is_some()
465 || inner_item_width + overhead > max_budget)
469 if max_width < inner_item_width {
470 max_width = inner_item_width;
480 fn post_comment_alignment(item_max_width: Option<usize>, inner_item_len: usize) -> usize {
482 .and_then(|max_line_width| max_line_width.checked_sub(inner_item_len))
486 pub struct ListItems<'a, I, F1, F2, F3>
490 snippet_provider: &'a SnippetProvider<'a>,
495 prev_span_end: BytePos,
496 next_span_start: BytePos,
502 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
504 I: Iterator<Item = T>,
505 F1: Fn(&T) -> BytePos,
506 F2: Fn(&T) -> BytePos,
507 F3: Fn(&T) -> Option<String>,
509 type Item = ListItem;
511 fn next(&mut self) -> Option<Self::Item> {
512 let white_space: &[_] = &[' ', '\t'];
514 self.inner.next().map(|item| {
515 let mut new_lines = false;
517 let pre_snippet = self.snippet_provider
518 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
520 let trimmed_pre_snippet = pre_snippet.trim();
521 let has_single_line_comment = trimmed_pre_snippet.starts_with("//");
522 let has_block_comment = trimmed_pre_snippet.starts_with("/*");
523 let (pre_comment, pre_comment_style) = if has_single_line_comment {
525 Some(trimmed_pre_snippet.to_owned()),
526 ListItemCommentStyle::DifferentLine,
528 } else if has_block_comment {
529 let comment_end = pre_snippet.chars().rev().position(|c| c == '/').unwrap();
533 .take(comment_end + 1)
537 Some(trimmed_pre_snippet.to_owned()),
538 ListItemCommentStyle::DifferentLine,
542 Some(trimmed_pre_snippet.to_owned()),
543 ListItemCommentStyle::SameLine,
547 (None, ListItemCommentStyle::None)
551 let next_start = match self.inner.peek() {
552 Some(next_item) => (self.get_lo)(next_item),
553 None => self.next_span_start,
555 let post_snippet = self.snippet_provider
556 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
559 let comment_end = match self.inner.peek() {
561 let mut block_open_index = post_snippet.find("/*");
562 // check if it really is a block comment (and not `//*` or a nested comment)
563 if let Some(i) = block_open_index {
564 match post_snippet.find('/') {
565 Some(j) if j < i => block_open_index = None,
566 _ if i > 0 && &post_snippet[i - 1..i] == "/" => block_open_index = None,
570 let newline_index = post_snippet.find('\n');
571 if let Some(separator_index) = post_snippet.find_uncommented(self.separator) {
572 match (block_open_index, newline_index) {
573 // Separator before comment, with the next item on same line.
574 // Comment belongs to next item.
575 (Some(i), None) if i > separator_index => separator_index + 1,
576 // Block-style post-comment before the separator.
577 (Some(i), None) => cmp::max(
578 find_comment_end(&post_snippet[i..]).unwrap() + i,
581 // Block-style post-comment. Either before or after the separator.
582 (Some(i), Some(j)) if i < j => cmp::max(
583 find_comment_end(&post_snippet[i..]).unwrap() + i,
586 // Potential *single* line comment.
587 (_, Some(j)) if j > separator_index => j + 1,
588 _ => post_snippet.len(),
590 } else if let Some(newline_index) = newline_index {
591 // Match arms may not have trailing comma. In any case, for match arms,
592 // we will assume that the post comment belongs to the next arm if they
593 // do not end with trailing comma.
600 .find_uncommented(self.terminator)
601 .unwrap_or_else(|| post_snippet.len()),
604 if !post_snippet.is_empty() && comment_end > 0 {
605 // Account for extra whitespace between items. This is fiddly
606 // because of the way we divide pre- and post- comments.
608 // Everything from the separator to the next item.
609 let test_snippet = &post_snippet[comment_end - 1..];
610 let first_newline = test_snippet
612 .unwrap_or_else(|| test_snippet.len());
613 // From the end of the first line of comments.
614 let test_snippet = &test_snippet[first_newline..];
615 let first = test_snippet
616 .find(|c: char| !c.is_whitespace())
617 .unwrap_or_else(|| test_snippet.len());
618 // From the end of the first line of comments to the next non-whitespace char.
619 let test_snippet = &test_snippet[..first];
621 if count_newlines(test_snippet) > 1 {
622 // There were multiple line breaks which got trimmed to nothing.
627 // Cleanup post-comment: strip separators and whitespace.
628 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
629 let post_snippet = post_snippet[..comment_end].trim();
631 let post_snippet_trimmed = if post_snippet.starts_with(|c| c == ',' || c == ':') {
632 post_snippet[1..].trim_matches(white_space)
633 } else if post_snippet.starts_with(self.separator) {
634 post_snippet[self.separator.len()..].trim_matches(white_space)
635 } else if post_snippet.ends_with(',') {
636 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
641 let post_comment = if !post_snippet_trimmed.is_empty() {
642 Some(post_snippet_trimmed.to_owned())
650 item: if self.inner.peek().is_none() && self.leave_last {
653 (self.get_item_string)(&item)
662 #[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
663 // Creates an iterator over a list's items with associated comments.
664 pub fn itemize_list<'a, T, I, F1, F2, F3>(
665 snippet_provider: &'a SnippetProvider,
672 prev_span_end: BytePos,
673 next_span_start: BytePos,
675 ) -> ListItems<'a, I, F1, F2, F3>
677 I: Iterator<Item = T>,
678 F1: Fn(&T) -> BytePos,
679 F2: Fn(&T) -> BytePos,
680 F3: Fn(&T) -> Option<String>,
684 inner: inner.peekable(),
696 /// Returns the count and total width of the list items.
697 fn calculate_width<I, T>(items: I) -> (usize, usize)
699 I: IntoIterator<Item = T>,
704 .map(|item| total_item_width(item.as_ref()))
705 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
708 pub fn total_item_width(item: &ListItem) -> usize {
709 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
710 + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
711 + item.item.as_ref().map_or(0, |str| str.len())
714 fn comment_len(comment: Option<&str>) -> usize {
717 let text_len = s.trim().len();
719 // We'll put " /*" before and " */" after inline comments.
729 // Compute horizontal and vertical shapes for a struct-lit-like thing.
730 pub fn struct_lit_shape(
732 context: &RewriteContext,
735 ) -> Option<(Option<Shape>, Shape)> {
736 let v_shape = match context.config.indent_style() {
737 IndentStyle::Visual => shape
739 .shrink_left(prefix_width)?
740 .sub_width(suffix_width)?,
741 IndentStyle::Block => {
742 let shape = shape.block_indent(context.config.tab_spaces());
744 width: context.budget(shape.indent.width()),
749 let shape_width = shape.width.checked_sub(prefix_width + suffix_width);
750 if let Some(w) = shape_width {
751 let shape_width = cmp::min(w, context.config.width_heuristics().struct_lit_width);
752 Some((Some(Shape::legacy(shape_width, shape.indent)), v_shape))
754 Some((None, v_shape))
758 // Compute the tactic for the internals of a struct-lit-like thing.
759 pub fn struct_lit_tactic(
760 h_shape: Option<Shape>,
761 context: &RewriteContext,
763 ) -> DefinitiveListTactic {
764 if let Some(h_shape) = h_shape {
765 let prelim_tactic = match (context.config.indent_style(), items.len()) {
766 (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
767 _ if context.config.struct_lit_single_line() => ListTactic::HorizontalVertical,
768 _ => ListTactic::Vertical,
770 definitive_tactic(items, prelim_tactic, Separator::Comma, h_shape.width)
772 DefinitiveListTactic::Vertical
776 // Given a tactic and possible shapes for horizontal and vertical layout,
777 // come up with the actual shape to use.
778 pub fn shape_for_tactic(
779 tactic: DefinitiveListTactic,
780 h_shape: Option<Shape>,
784 DefinitiveListTactic::Horizontal => h_shape.unwrap(),
789 // Create a ListFormatting object for formatting the internals of a
790 // struct-lit-like thing, that is a series of fields.
791 pub fn struct_lit_formatting<'a>(
793 tactic: DefinitiveListTactic,
794 context: &'a RewriteContext,
795 force_no_trailing_comma: bool,
796 ) -> ListFormatting<'a> {
797 let ends_with_newline = context.config.indent_style() != IndentStyle::Visual
798 && tactic == DefinitiveListTactic::Vertical;
802 trailing_separator: if force_no_trailing_comma {
803 SeparatorTactic::Never
805 context.config.trailing_comma()
807 separator_place: SeparatorPlace::Back,
810 preserve_newline: true,
811 config: context.config,