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.
12 use std::iter::Peekable;
14 use syntax::codemap::{BytePos, CodeMap};
16 use comment::{find_comment_end, rewrite_comment, FindUncommented};
17 use config::{Config, IndentStyle};
18 use rewrite::RewriteContext;
19 use shape::{Indent, Shape};
20 use utils::{count_newlines, first_line_width, last_line_width, mk_sp, starts_with_newline};
22 /// Formatting tactic for lists. This will be cast down to a
23 /// `DefinitiveListTactic` depending on the number and length of the items and
25 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
29 // All items on one row.
31 // Try Horizontal layout, if that fails then vertical.
33 // HorizontalVertical with a soft limit of n characters.
34 LimitedHorizontalVertical(usize),
35 // Pack as many items as possible per row over (possibly) many rows.
39 impl_enum_serialize_and_deserialize!(ListTactic, Vertical, Horizontal, HorizontalVertical, Mixed);
41 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
42 pub enum SeparatorTactic {
48 impl_enum_serialize_and_deserialize!(SeparatorTactic, Always, Never, Vertical);
50 impl SeparatorTactic {
51 pub fn from_bool(b: bool) -> SeparatorTactic {
53 SeparatorTactic::Always
55 SeparatorTactic::Never
60 pub struct ListFormatting<'a> {
61 pub tactic: DefinitiveListTactic,
62 pub separator: &'a str,
63 pub trailing_separator: SeparatorTactic,
64 pub separator_place: SeparatorPlace,
66 // Non-expressions, e.g. items, will have a new line at the end of the list.
67 // Important for comment styles.
68 pub ends_with_newline: bool,
69 // Remove newlines between list elements for expressions.
70 pub preserve_newline: bool,
71 pub config: &'a Config,
74 impl<'a> ListFormatting<'a> {
75 pub fn needs_trailing_separator(&self) -> bool {
76 match self.trailing_separator {
77 // We always put separator in front.
78 SeparatorTactic::Always => true,
79 SeparatorTactic::Vertical => self.tactic == DefinitiveListTactic::Vertical,
80 SeparatorTactic::Never => {
81 self.tactic == DefinitiveListTactic::Vertical && self.separator_place.is_front()
87 impl AsRef<ListItem> for ListItem {
88 fn as_ref(&self) -> &ListItem {
93 #[derive(PartialEq, Eq)]
94 pub enum ListItemCommentStyle {
95 // Try to keep the comment on the same line with the item.
97 // Put the comment on the previous or the next line of the item.
99 // No comment available.
103 pub struct ListItem {
104 // None for comments mean that they are not present.
105 pub pre_comment: Option<String>,
106 pub pre_comment_style: ListItemCommentStyle,
107 // Item should include attributes and doc comments. None indicates a failed
109 pub item: Option<String>,
110 pub post_comment: Option<String>,
111 // Whether there is extra whitespace before this item.
116 pub fn inner_as_ref(&self) -> &str {
117 self.item.as_ref().map_or("", |s| s)
120 pub fn is_different_group(&self) -> bool {
121 self.inner_as_ref().contains('\n') || self.pre_comment.is_some()
124 .map_or(false, |s| s.contains('\n'))
127 pub fn is_multiline(&self) -> bool {
128 self.inner_as_ref().contains('\n')
131 .map_or(false, |s| s.contains('\n'))
134 .map_or(false, |s| s.contains('\n'))
137 pub fn has_comment(&self) -> bool {
140 .map_or(false, |comment| comment.trim_left().starts_with("//"))
143 .map_or(false, |comment| comment.trim_left().starts_with("//"))
146 pub fn from_str<S: Into<String>>(s: S) -> ListItem {
149 pre_comment_style: ListItemCommentStyle::None,
150 item: Some(s.into()),
157 /// The definitive formatting tactic for lists.
158 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
159 pub enum DefinitiveListTactic {
163 /// Special case tactic for `format!()`, `write!()` style macros.
167 impl DefinitiveListTactic {
168 pub fn ends_with_newline(&self, indent_style: IndentStyle) -> bool {
170 IndentStyle::Block => *self != DefinitiveListTactic::Horizontal,
171 IndentStyle::Visual => false,
176 /// The type of separator for lists.
177 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
184 pub fn len(&self) -> usize {
187 Separator::Comma => 2,
189 Separator::VerticalBar => 3,
194 /// Where to put separator.
195 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
196 pub enum SeparatorPlace {
201 impl_enum_serialize_and_deserialize!(SeparatorPlace, Front, Back);
203 impl SeparatorPlace {
204 pub fn is_front(&self) -> bool {
205 *self == SeparatorPlace::Front
208 pub fn is_back(&self) -> bool {
209 *self == SeparatorPlace::Back
213 default: SeparatorPlace,
214 tactic: DefinitiveListTactic,
216 ) -> SeparatorPlace {
218 DefinitiveListTactic::Vertical => default,
228 pub fn definitive_tactic<I, T>(
233 ) -> DefinitiveListTactic
235 I: IntoIterator<Item = T> + Clone,
238 let pre_line_comments = items
241 .any(|item| item.as_ref().has_comment());
243 let limit = match tactic {
244 _ if pre_line_comments => return DefinitiveListTactic::Vertical,
245 ListTactic::Mixed => return DefinitiveListTactic::Mixed,
246 ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
247 ListTactic::Vertical => return DefinitiveListTactic::Vertical,
248 ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
249 ListTactic::HorizontalVertical => width,
252 let (sep_count, total_width) = calculate_width(items.clone());
253 let total_sep_len = sep.len() * sep_count.checked_sub(1).unwrap_or(0);
254 let real_total = total_width + total_sep_len;
256 if real_total <= limit && !pre_line_comments
257 && !items.into_iter().any(|item| item.as_ref().is_multiline())
259 DefinitiveListTactic::Horizontal
261 DefinitiveListTactic::Vertical
265 // Format a list of commented items into a string.
266 // TODO: add unit tests
267 pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
269 I: IntoIterator<Item = T> + Clone,
272 let tactic = formatting.tactic;
273 let sep_len = formatting.separator.len();
275 // Now that we know how we will layout, we can decide for sure if there
276 // will be a trailing separator.
277 let mut trailing_separator = formatting.needs_trailing_separator();
278 let mut result = String::with_capacity(128);
279 let cloned_items = items.clone();
280 let mut iter = items.into_iter().enumerate().peekable();
281 let mut item_max_width: Option<usize> = None;
283 SeparatorPlace::from_tactic(formatting.separator_place, tactic, formatting.separator);
285 let mut line_len = 0;
286 let indent_str = &formatting.shape.indent.to_string(formatting.config);
287 while let Some((i, item)) = iter.next() {
288 let item = item.as_ref();
289 let inner_item = item.item.as_ref()?;
291 let last = iter.peek().is_none();
292 let mut separate = match sep_place {
293 SeparatorPlace::Front => !first,
294 SeparatorPlace::Back => !last || trailing_separator,
296 let item_sep_len = if separate { sep_len } else { 0 };
298 // Item string may be multi-line. Its length (used for block comment alignment)
299 // should be only the length of the last line.
300 let item_last_line = if item.is_multiline() {
301 inner_item.lines().last().unwrap_or("")
305 let mut item_last_line_width = item_last_line.len() + item_sep_len;
306 if item_last_line.starts_with(&**indent_str) {
307 item_last_line_width -= indent_str.len();
311 DefinitiveListTactic::Horizontal if !first => {
314 DefinitiveListTactic::SpecialMacro(num_args_before) => {
317 } else if i < num_args_before {
319 } else if i <= num_args_before + 1 {
321 result.push_str(indent_str);
326 DefinitiveListTactic::Vertical if !first => {
328 result.push_str(indent_str);
330 DefinitiveListTactic::Mixed => {
331 let total_width = total_item_width(item) + item_sep_len;
333 // 1 is space between separator and item.
334 if line_len > 0 && line_len + 1 + total_width > formatting.shape.width {
336 result.push_str(indent_str);
338 if formatting.ends_with_newline {
342 trailing_separator = true;
352 line_len += total_width;
358 if let Some(ref comment) = item.pre_comment {
359 // Block style in non-vertical mode.
360 let block_mode = tactic != DefinitiveListTactic::Vertical;
361 // Width restriction is only relevant in vertical mode.
363 rewrite_comment(comment, block_mode, formatting.shape, formatting.config)?;
364 result.push_str(&comment);
366 if tactic == DefinitiveListTactic::Vertical {
367 // We cannot keep pre-comments on the same line if the comment if normalized.
368 let keep_comment = if formatting.config.normalize_comments()
369 || item.pre_comment_style == ListItemCommentStyle::DifferentLine
373 // We will try to keep the comment on the same line with the item here.
375 let total_width = total_item_width(item) + item_sep_len + 1;
376 total_width <= formatting.shape.width
382 result.push_str(indent_str);
387 item_max_width = None;
390 if separate && sep_place.is_front() && !first {
391 result.push_str(formatting.separator.trim());
394 result.push_str(&inner_item[..]);
397 if tactic != DefinitiveListTactic::Vertical && item.post_comment.is_some() {
398 let comment = item.post_comment.as_ref().unwrap();
399 let formatted_comment = rewrite_comment(
402 Shape::legacy(formatting.shape.width, Indent::empty()),
407 result.push_str(&formatted_comment);
410 if separate && sep_place.is_back() {
411 result.push_str(formatting.separator);
414 if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
415 let comment = item.post_comment.as_ref().unwrap();
416 let overhead = last_line_width(&result) + first_line_width(comment.trim());
418 let rewrite_post_comment = |item_max_width: &mut Option<usize>| {
419 if item_max_width.is_none() && !last && !inner_item.contains('\n') {
420 *item_max_width = Some(max_width_of_item_with_post_comment(
424 formatting.config.max_width(),
427 let overhead = if starts_with_newline(comment) {
429 } else if let Some(max_width) = *item_max_width {
432 // 1 = space between item and comment.
433 item_last_line_width + 1
435 let width = formatting.shape.width.checked_sub(overhead).unwrap_or(1);
436 let offset = formatting.shape.indent + overhead;
437 let comment_shape = Shape::legacy(width, offset);
439 // Use block-style only for the last item or multiline comments.
440 let block_style = !formatting.ends_with_newline && last
441 || comment.trim().contains('\n')
442 || comment.trim().len() > width;
452 let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?;
454 if !starts_with_newline(comment) {
455 let mut comment_alignment =
456 post_comment_alignment(item_max_width, inner_item.len());
457 if first_line_width(&formatted_comment) + last_line_width(&result)
458 + comment_alignment + 1 > formatting.config.max_width()
460 item_max_width = None;
461 formatted_comment = rewrite_post_comment(&mut item_max_width)?;
462 comment_alignment = post_comment_alignment(item_max_width, inner_item.len());
464 for _ in 0..(comment_alignment + 1) {
467 // An additional space for the missing trailing separator.
468 if last && item_max_width.is_some() && !separate && !formatting.separator.is_empty()
474 result.push_str(indent_str);
476 if formatted_comment.contains('\n') {
477 item_max_width = None;
479 result.push_str(&formatted_comment);
481 item_max_width = None;
484 if formatting.preserve_newline && !last && tactic == DefinitiveListTactic::Vertical
487 item_max_width = None;
495 fn max_width_of_item_with_post_comment<I, T>(
502 I: IntoIterator<Item = T> + Clone,
505 let mut max_width = 0;
506 let mut first = true;
507 for item in items.clone().into_iter().skip(i) {
508 let item = item.as_ref();
509 let inner_item_width = item.inner_as_ref().len();
511 && (item.is_different_group() || !item.post_comment.is_some()
512 || inner_item_width + overhead > max_budget)
516 if max_width < inner_item_width {
517 max_width = inner_item_width;
527 fn post_comment_alignment(item_max_width: Option<usize>, inner_item_len: usize) -> usize {
529 .and_then(|max_line_width| max_line_width.checked_sub(inner_item_len))
533 pub struct ListItems<'a, I, F1, F2, F3>
537 codemap: &'a CodeMap,
542 prev_span_end: BytePos,
543 next_span_start: BytePos,
549 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
551 I: Iterator<Item = T>,
552 F1: Fn(&T) -> BytePos,
553 F2: Fn(&T) -> BytePos,
554 F3: Fn(&T) -> Option<String>,
556 type Item = ListItem;
558 fn next(&mut self) -> Option<Self::Item> {
559 let white_space: &[_] = &[' ', '\t'];
561 self.inner.next().map(|item| {
562 let mut new_lines = false;
564 let pre_snippet = self.codemap
565 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
567 let trimmed_pre_snippet = pre_snippet.trim();
568 let has_single_line_comment = trimmed_pre_snippet.starts_with("//");
569 let has_block_comment = trimmed_pre_snippet.starts_with("/*");
570 let (pre_comment, pre_comment_style) = if has_single_line_comment {
572 Some(trimmed_pre_snippet.to_owned()),
573 ListItemCommentStyle::DifferentLine,
575 } else if has_block_comment {
576 let comment_end = pre_snippet.chars().rev().position(|c| c == '/').unwrap();
580 .take(comment_end + 1)
584 Some(trimmed_pre_snippet.to_owned()),
585 ListItemCommentStyle::DifferentLine,
589 Some(trimmed_pre_snippet.to_owned()),
590 ListItemCommentStyle::SameLine,
594 (None, ListItemCommentStyle::None)
598 let next_start = match self.inner.peek() {
599 Some(next_item) => (self.get_lo)(next_item),
600 None => self.next_span_start,
602 let post_snippet = self.codemap
603 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
606 let comment_end = match self.inner.peek() {
608 let mut block_open_index = post_snippet.find("/*");
609 // check if it really is a block comment (and not `//*` or a nested comment)
610 if let Some(i) = block_open_index {
611 match post_snippet.find('/') {
612 Some(j) if j < i => block_open_index = None,
613 _ if i > 0 && &post_snippet[i - 1..i] == "/" => block_open_index = None,
617 let newline_index = post_snippet.find('\n');
618 if let Some(separator_index) = post_snippet.find_uncommented(self.separator) {
619 match (block_open_index, newline_index) {
620 // Separator before comment, with the next item on same line.
621 // Comment belongs to next item.
622 (Some(i), None) if i > separator_index => separator_index + 1,
623 // Block-style post-comment before the separator.
624 (Some(i), None) => cmp::max(
625 find_comment_end(&post_snippet[i..]).unwrap() + i,
628 // Block-style post-comment. Either before or after the separator.
629 (Some(i), Some(j)) if i < j => cmp::max(
630 find_comment_end(&post_snippet[i..]).unwrap() + i,
633 // Potential *single* line comment.
634 (_, Some(j)) if j > separator_index => j + 1,
635 _ => post_snippet.len(),
637 } else if let Some(newline_index) = newline_index {
638 // Match arms may not have trailing comma. In any case, for match arms,
639 // we will assume that the post comment belongs to the next arm if they
640 // do not end with trailing comma.
647 .find_uncommented(self.terminator)
648 .unwrap_or_else(|| post_snippet.len()),
651 if !post_snippet.is_empty() && comment_end > 0 {
652 // Account for extra whitespace between items. This is fiddly
653 // because of the way we divide pre- and post- comments.
655 // Everything from the separator to the next item.
656 let test_snippet = &post_snippet[comment_end - 1..];
657 let first_newline = test_snippet
659 .unwrap_or_else(|| test_snippet.len());
660 // From the end of the first line of comments.
661 let test_snippet = &test_snippet[first_newline..];
662 let first = test_snippet
663 .find(|c: char| !c.is_whitespace())
664 .unwrap_or_else(|| test_snippet.len());
665 // From the end of the first line of comments to the next non-whitespace char.
666 let test_snippet = &test_snippet[..first];
668 if count_newlines(test_snippet) > 1 {
669 // There were multiple line breaks which got trimmed to nothing.
674 // Cleanup post-comment: strip separators and whitespace.
675 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
676 let post_snippet = post_snippet[..comment_end].trim();
678 let post_snippet_trimmed = if post_snippet.starts_with(|c| c == ',' || c == ':') {
679 post_snippet[1..].trim_matches(white_space)
680 } else if post_snippet.ends_with(',') {
681 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
686 let post_comment = if !post_snippet_trimmed.is_empty() {
687 Some(post_snippet_trimmed.to_owned())
695 item: if self.inner.peek().is_none() && self.leave_last {
698 (self.get_item_string)(&item)
707 // Creates an iterator over a list's items with associated comments.
708 pub fn itemize_list<'a, T, I, F1, F2, F3>(
709 codemap: &'a CodeMap,
716 prev_span_end: BytePos,
717 next_span_start: BytePos,
719 ) -> ListItems<'a, I, F1, F2, F3>
721 I: Iterator<Item = T>,
722 F1: Fn(&T) -> BytePos,
723 F2: Fn(&T) -> BytePos,
724 F3: Fn(&T) -> Option<String>,
728 inner: inner.peekable(),
740 /// Returns the count and total width of the list items.
741 fn calculate_width<I, T>(items: I) -> (usize, usize)
743 I: IntoIterator<Item = T>,
748 .map(|item| total_item_width(item.as_ref()))
749 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
752 pub fn total_item_width(item: &ListItem) -> usize {
753 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
754 + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
755 + item.item.as_ref().map_or(0, |str| str.len())
758 fn comment_len(comment: Option<&str>) -> usize {
761 let text_len = s.trim().len();
763 // We'll put " /*" before and " */" after inline comments.
773 // Compute horizontal and vertical shapes for a struct-lit-like thing.
774 pub fn struct_lit_shape(
776 context: &RewriteContext,
779 ) -> Option<(Option<Shape>, Shape)> {
780 let v_shape = match context.config.indent_style() {
781 IndentStyle::Visual => shape
783 .shrink_left(prefix_width)?
784 .sub_width(suffix_width)?,
785 IndentStyle::Block => {
786 let shape = shape.block_indent(context.config.tab_spaces());
788 width: context.budget(shape.indent.width()),
793 let shape_width = shape.width.checked_sub(prefix_width + suffix_width);
794 if let Some(w) = shape_width {
795 let shape_width = cmp::min(w, context.config.width_heuristics().struct_lit_width);
796 Some((Some(Shape::legacy(shape_width, shape.indent)), v_shape))
798 Some((None, v_shape))
802 // Compute the tactic for the internals of a struct-lit-like thing.
803 pub fn struct_lit_tactic(
804 h_shape: Option<Shape>,
805 context: &RewriteContext,
807 ) -> DefinitiveListTactic {
808 if let Some(h_shape) = h_shape {
809 let prelim_tactic = match (context.config.indent_style(), items.len()) {
810 (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
811 _ if context.config.struct_lit_single_line() => ListTactic::HorizontalVertical,
812 _ => ListTactic::Vertical,
814 definitive_tactic(items, prelim_tactic, Separator::Comma, h_shape.width)
816 DefinitiveListTactic::Vertical
820 // Given a tactic and possible shapes for horizontal and vertical layout,
821 // come up with the actual shape to use.
822 pub fn shape_for_tactic(
823 tactic: DefinitiveListTactic,
824 h_shape: Option<Shape>,
828 DefinitiveListTactic::Horizontal => h_shape.unwrap(),
833 // Create a ListFormatting object for formatting the internals of a
834 // struct-lit-like thing, that is a series of fields.
835 pub fn struct_lit_formatting<'a>(
837 tactic: DefinitiveListTactic,
838 context: &'a RewriteContext,
839 force_no_trailing_comma: bool,
840 ) -> ListFormatting<'a> {
841 let ends_with_newline = context.config.indent_style() != IndentStyle::Visual
842 && tactic == DefinitiveListTactic::Vertical;
846 trailing_separator: if force_no_trailing_comma {
847 SeparatorTactic::Never
849 context.config.trailing_comma()
851 separator_place: SeparatorPlace::Back,
854 preserve_newline: true,
855 config: context.config,