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 separate = formatting.trailing_separator != SeparatorTactic::Never;
300 line_len += total_width;
306 if let Some(ref comment) = item.pre_comment {
307 // Block style in non-vertical mode.
308 let block_mode = tactic != DefinitiveListTactic::Vertical;
309 // Width restriction is only relevant in vertical mode.
311 rewrite_comment(comment, block_mode, formatting.shape, formatting.config)?;
312 result.push_str(&comment);
314 if !inner_item.is_empty() {
315 if tactic == DefinitiveListTactic::Vertical {
316 // We cannot keep pre-comments on the same line if the comment if normalized.
317 let keep_comment = if formatting.config.normalize_comments()
318 || item.pre_comment_style == ListItemCommentStyle::DifferentLine
322 // We will try to keep the comment on the same line with the item here.
324 let total_width = total_item_width(item) + item_sep_len + 1;
325 total_width <= formatting.shape.width
331 result.push_str(indent_str);
337 item_max_width = None;
340 if separate && sep_place.is_front() && !first {
341 result.push_str(formatting.separator.trim());
344 result.push_str(inner_item);
347 if tactic != DefinitiveListTactic::Vertical && item.post_comment.is_some() {
348 let comment = item.post_comment.as_ref().unwrap();
349 let formatted_comment = rewrite_comment(
352 Shape::legacy(formatting.shape.width, Indent::empty()),
357 result.push_str(&formatted_comment);
360 if separate && sep_place.is_back() {
361 result.push_str(formatting.separator);
364 if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
365 let comment = item.post_comment.as_ref().unwrap();
366 let overhead = last_line_width(&result) + first_line_width(comment.trim());
368 let rewrite_post_comment = |item_max_width: &mut Option<usize>| {
369 if item_max_width.is_none() && !last && !inner_item.contains('\n') {
370 *item_max_width = Some(max_width_of_item_with_post_comment(
374 formatting.config.max_width(),
377 let overhead = if starts_with_newline(comment) {
379 } else if let Some(max_width) = *item_max_width {
382 // 1 = space between item and comment.
383 item_last_line_width + 1
385 let width = formatting.shape.width.checked_sub(overhead).unwrap_or(1);
386 let offset = formatting.shape.indent + overhead;
387 let comment_shape = Shape::legacy(width, offset);
389 // Use block-style only for the last item or multiline comments.
390 let block_style = !formatting.ends_with_newline && last
391 || comment.trim().contains('\n')
392 || comment.trim().len() > width;
402 let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?;
404 if !starts_with_newline(comment) {
405 let mut comment_alignment =
406 post_comment_alignment(item_max_width, inner_item.len());
407 if first_line_width(&formatted_comment) + last_line_width(&result)
408 + comment_alignment + 1 > formatting.config.max_width()
410 item_max_width = None;
411 formatted_comment = rewrite_post_comment(&mut item_max_width)?;
412 comment_alignment = post_comment_alignment(item_max_width, inner_item.len());
414 for _ in 0..(comment_alignment + 1) {
417 // An additional space for the missing trailing separator.
418 if last && item_max_width.is_some() && !separate && !formatting.separator.is_empty()
424 result.push_str(indent_str);
426 if formatted_comment.contains('\n') {
427 item_max_width = None;
429 result.push_str(&formatted_comment);
431 item_max_width = None;
434 if formatting.preserve_newline && !last && tactic == DefinitiveListTactic::Vertical
437 item_max_width = None;
445 fn max_width_of_item_with_post_comment<I, T>(
452 I: IntoIterator<Item = T> + Clone,
455 let mut max_width = 0;
456 let mut first = true;
457 for item in items.clone().into_iter().skip(i) {
458 let item = item.as_ref();
459 let inner_item_width = item.inner_as_ref().len();
461 && (item.is_different_group() || !item.post_comment.is_some()
462 || inner_item_width + overhead > max_budget)
466 if max_width < inner_item_width {
467 max_width = inner_item_width;
477 fn post_comment_alignment(item_max_width: Option<usize>, inner_item_len: usize) -> usize {
479 .and_then(|max_line_width| max_line_width.checked_sub(inner_item_len))
483 pub struct ListItems<'a, I, F1, F2, F3>
487 snippet_provider: &'a SnippetProvider<'a>,
492 prev_span_end: BytePos,
493 next_span_start: BytePos,
499 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
501 I: Iterator<Item = T>,
502 F1: Fn(&T) -> BytePos,
503 F2: Fn(&T) -> BytePos,
504 F3: Fn(&T) -> Option<String>,
506 type Item = ListItem;
508 fn next(&mut self) -> Option<Self::Item> {
509 let white_space: &[_] = &[' ', '\t'];
511 self.inner.next().map(|item| {
512 let mut new_lines = false;
514 let pre_snippet = self.snippet_provider
515 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
517 let trimmed_pre_snippet = pre_snippet.trim();
518 let has_single_line_comment = trimmed_pre_snippet.starts_with("//");
519 let has_block_comment = trimmed_pre_snippet.starts_with("/*");
520 let (pre_comment, pre_comment_style) = if has_single_line_comment {
522 Some(trimmed_pre_snippet.to_owned()),
523 ListItemCommentStyle::DifferentLine,
525 } else if has_block_comment {
526 let comment_end = pre_snippet.chars().rev().position(|c| c == '/').unwrap();
530 .take(comment_end + 1)
534 Some(trimmed_pre_snippet.to_owned()),
535 ListItemCommentStyle::DifferentLine,
539 Some(trimmed_pre_snippet.to_owned()),
540 ListItemCommentStyle::SameLine,
544 (None, ListItemCommentStyle::None)
548 let next_start = match self.inner.peek() {
549 Some(next_item) => (self.get_lo)(next_item),
550 None => self.next_span_start,
552 let post_snippet = self.snippet_provider
553 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
556 let comment_end = match self.inner.peek() {
558 let mut block_open_index = post_snippet.find("/*");
559 // check if it really is a block comment (and not `//*` or a nested comment)
560 if let Some(i) = block_open_index {
561 match post_snippet.find('/') {
562 Some(j) if j < i => block_open_index = None,
563 _ if i > 0 && &post_snippet[i - 1..i] == "/" => block_open_index = None,
567 let newline_index = post_snippet.find('\n');
568 if let Some(separator_index) = post_snippet.find_uncommented(self.separator) {
569 match (block_open_index, newline_index) {
570 // Separator before comment, with the next item on same line.
571 // Comment belongs to next item.
572 (Some(i), None) if i > separator_index => separator_index + 1,
573 // Block-style post-comment before the separator.
574 (Some(i), None) => cmp::max(
575 find_comment_end(&post_snippet[i..]).unwrap() + i,
578 // Block-style post-comment. Either before or after the separator.
579 (Some(i), Some(j)) if i < j => cmp::max(
580 find_comment_end(&post_snippet[i..]).unwrap() + i,
583 // Potential *single* line comment.
584 (_, Some(j)) if j > separator_index => j + 1,
585 _ => post_snippet.len(),
587 } else if let Some(newline_index) = newline_index {
588 // Match arms may not have trailing comma. In any case, for match arms,
589 // we will assume that the post comment belongs to the next arm if they
590 // do not end with trailing comma.
597 .find_uncommented(self.terminator)
598 .unwrap_or_else(|| post_snippet.len()),
601 if !post_snippet.is_empty() && comment_end > 0 {
602 // Account for extra whitespace between items. This is fiddly
603 // because of the way we divide pre- and post- comments.
605 // Everything from the separator to the next item.
606 let test_snippet = &post_snippet[comment_end - 1..];
607 let first_newline = test_snippet
609 .unwrap_or_else(|| test_snippet.len());
610 // From the end of the first line of comments.
611 let test_snippet = &test_snippet[first_newline..];
612 let first = test_snippet
613 .find(|c: char| !c.is_whitespace())
614 .unwrap_or_else(|| test_snippet.len());
615 // From the end of the first line of comments to the next non-whitespace char.
616 let test_snippet = &test_snippet[..first];
618 if count_newlines(test_snippet) > 1 {
619 // There were multiple line breaks which got trimmed to nothing.
624 // Cleanup post-comment: strip separators and whitespace.
625 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
626 let post_snippet = post_snippet[..comment_end].trim();
628 let post_snippet_trimmed = if post_snippet.starts_with(|c| c == ',' || c == ':') {
629 post_snippet[1..].trim_matches(white_space)
630 } else if post_snippet.starts_with(self.separator) {
631 post_snippet[self.separator.len()..].trim_matches(white_space)
632 } else if post_snippet.ends_with(',') {
633 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
638 let post_comment = if !post_snippet_trimmed.is_empty() {
639 Some(post_snippet_trimmed.to_owned())
647 item: if self.inner.peek().is_none() && self.leave_last {
650 (self.get_item_string)(&item)
659 #[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
660 // Creates an iterator over a list's items with associated comments.
661 pub fn itemize_list<'a, T, I, F1, F2, F3>(
662 snippet_provider: &'a SnippetProvider,
669 prev_span_end: BytePos,
670 next_span_start: BytePos,
672 ) -> ListItems<'a, I, F1, F2, F3>
674 I: Iterator<Item = T>,
675 F1: Fn(&T) -> BytePos,
676 F2: Fn(&T) -> BytePos,
677 F3: Fn(&T) -> Option<String>,
681 inner: inner.peekable(),
693 /// Returns the count and total width of the list items.
694 fn calculate_width<I, T>(items: I) -> (usize, usize)
696 I: IntoIterator<Item = T>,
701 .map(|item| total_item_width(item.as_ref()))
702 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
705 pub fn total_item_width(item: &ListItem) -> usize {
706 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
707 + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
708 + item.item.as_ref().map_or(0, |str| str.len())
711 fn comment_len(comment: Option<&str>) -> usize {
714 let text_len = s.trim().len();
716 // We'll put " /*" before and " */" after inline comments.
726 // Compute horizontal and vertical shapes for a struct-lit-like thing.
727 pub fn struct_lit_shape(
729 context: &RewriteContext,
732 ) -> Option<(Option<Shape>, Shape)> {
733 let v_shape = match context.config.indent_style() {
734 IndentStyle::Visual => shape
736 .shrink_left(prefix_width)?
737 .sub_width(suffix_width)?,
738 IndentStyle::Block => {
739 let shape = shape.block_indent(context.config.tab_spaces());
741 width: context.budget(shape.indent.width()),
746 let shape_width = shape.width.checked_sub(prefix_width + suffix_width);
747 if let Some(w) = shape_width {
748 let shape_width = cmp::min(w, context.config.width_heuristics().struct_lit_width);
749 Some((Some(Shape::legacy(shape_width, shape.indent)), v_shape))
751 Some((None, v_shape))
755 // Compute the tactic for the internals of a struct-lit-like thing.
756 pub fn struct_lit_tactic(
757 h_shape: Option<Shape>,
758 context: &RewriteContext,
760 ) -> DefinitiveListTactic {
761 if let Some(h_shape) = h_shape {
762 let prelim_tactic = match (context.config.indent_style(), items.len()) {
763 (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
764 _ if context.config.struct_lit_single_line() => ListTactic::HorizontalVertical,
765 _ => ListTactic::Vertical,
767 definitive_tactic(items, prelim_tactic, Separator::Comma, h_shape.width)
769 DefinitiveListTactic::Vertical
773 // Given a tactic and possible shapes for horizontal and vertical layout,
774 // come up with the actual shape to use.
775 pub fn shape_for_tactic(
776 tactic: DefinitiveListTactic,
777 h_shape: Option<Shape>,
781 DefinitiveListTactic::Horizontal => h_shape.unwrap(),
786 // Create a ListFormatting object for formatting the internals of a
787 // struct-lit-like thing, that is a series of fields.
788 pub fn struct_lit_formatting<'a>(
790 tactic: DefinitiveListTactic,
791 context: &'a RewriteContext,
792 force_no_trailing_comma: bool,
793 ) -> ListFormatting<'a> {
794 let ends_with_newline = context.config.indent_style() != IndentStyle::Visual
795 && tactic == DefinitiveListTactic::Vertical;
799 trailing_separator: if force_no_trailing_comma {
800 SeparatorTactic::Never
802 context.config.trailing_comma()
804 separator_place: SeparatorPlace::Back,
807 preserve_newline: true,
808 config: context.config,