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::{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.starts_with("//"))
143 .map_or(false, |comment| comment.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 {
165 impl DefinitiveListTactic {
166 pub fn ends_with_newline(&self, indent_style: IndentStyle) -> bool {
168 IndentStyle::Block => *self != DefinitiveListTactic::Horizontal,
169 IndentStyle::Visual => false,
174 /// The type of separator for lists.
175 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
182 pub fn len(&self) -> usize {
185 Separator::Comma => 2,
187 Separator::VerticalBar => 3,
192 /// Where to put separator.
193 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
194 pub enum SeparatorPlace {
199 impl_enum_serialize_and_deserialize!(SeparatorPlace, Front, Back);
201 impl SeparatorPlace {
202 pub fn is_front(&self) -> bool {
203 *self == SeparatorPlace::Front
206 pub fn is_back(&self) -> bool {
207 *self == SeparatorPlace::Back
211 default: SeparatorPlace,
212 tactic: DefinitiveListTactic,
214 ) -> SeparatorPlace {
216 DefinitiveListTactic::Vertical => default,
226 pub fn definitive_tactic<I, T>(
231 ) -> DefinitiveListTactic
233 I: IntoIterator<Item = T> + Clone,
236 let pre_line_comments = items
239 .any(|item| item.as_ref().has_comment());
241 let limit = match tactic {
242 _ if pre_line_comments => return DefinitiveListTactic::Vertical,
243 ListTactic::Mixed => return DefinitiveListTactic::Mixed,
244 ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
245 ListTactic::Vertical => return DefinitiveListTactic::Vertical,
246 ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
247 ListTactic::HorizontalVertical => width,
250 let (sep_count, total_width) = calculate_width(items.clone());
251 let total_sep_len = sep.len() * sep_count.checked_sub(1).unwrap_or(0);
252 let real_total = total_width + total_sep_len;
254 if real_total <= limit && !pre_line_comments
255 && !items.into_iter().any(|item| item.as_ref().is_multiline())
257 DefinitiveListTactic::Horizontal
259 DefinitiveListTactic::Vertical
263 // Format a list of commented items into a string.
264 // TODO: add unit tests
265 pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
267 I: IntoIterator<Item = T> + Clone,
270 let tactic = formatting.tactic;
271 let sep_len = formatting.separator.len();
273 // Now that we know how we will layout, we can decide for sure if there
274 // will be a trailing separator.
275 let mut trailing_separator = formatting.needs_trailing_separator();
276 let mut result = String::with_capacity(128);
277 let cloned_items = items.clone();
278 let mut iter = items.into_iter().enumerate().peekable();
279 let mut item_max_width: Option<usize> = None;
281 SeparatorPlace::from_tactic(formatting.separator_place, tactic, formatting.separator);
283 let mut line_len = 0;
284 let indent_str = &formatting.shape.indent.to_string(formatting.config);
285 while let Some((i, item)) = iter.next() {
286 let item = item.as_ref();
287 let inner_item = item.item.as_ref()?;
289 let last = iter.peek().is_none();
290 let mut separate = match sep_place {
291 SeparatorPlace::Front => !first,
292 SeparatorPlace::Back => !last || trailing_separator,
294 let item_sep_len = if separate { sep_len } else { 0 };
296 // Item string may be multi-line. Its length (used for block comment alignment)
297 // should be only the length of the last line.
298 let item_last_line = if item.is_multiline() {
299 inner_item.lines().last().unwrap_or("")
303 let mut item_last_line_width = item_last_line.len() + item_sep_len;
304 if item_last_line.starts_with(&**indent_str) {
305 item_last_line_width -= indent_str.len();
309 DefinitiveListTactic::Horizontal if !first => {
312 DefinitiveListTactic::Vertical if !first => {
314 result.push_str(indent_str);
316 DefinitiveListTactic::Mixed => {
317 let total_width = total_item_width(item) + item_sep_len;
319 // 1 is space between separator and item.
320 if line_len > 0 && line_len + 1 + total_width > formatting.shape.width {
322 result.push_str(indent_str);
324 if formatting.ends_with_newline {
328 trailing_separator = true;
338 line_len += total_width;
344 if let Some(ref comment) = item.pre_comment {
345 // Block style in non-vertical mode.
346 let block_mode = tactic != DefinitiveListTactic::Vertical;
347 // Width restriction is only relevant in vertical mode.
349 rewrite_comment(comment, block_mode, formatting.shape, formatting.config)?;
350 result.push_str(&comment);
352 if tactic == DefinitiveListTactic::Vertical {
353 // We cannot keep pre-comments on the same line if the comment if normalized.
354 let keep_comment = if formatting.config.normalize_comments()
355 || item.pre_comment_style == ListItemCommentStyle::DifferentLine
359 // We will try to keep the comment on the same line with the item here.
361 let total_width = total_item_width(item) + item_sep_len + 1;
362 total_width <= formatting.shape.width
368 result.push_str(indent_str);
373 item_max_width = None;
376 if separate && sep_place.is_front() && !first {
377 result.push_str(formatting.separator.trim());
380 result.push_str(&inner_item[..]);
383 if tactic != DefinitiveListTactic::Vertical && item.post_comment.is_some() {
384 let comment = item.post_comment.as_ref().unwrap();
385 let formatted_comment = rewrite_comment(
388 Shape::legacy(formatting.shape.width, Indent::empty()),
393 result.push_str(&formatted_comment);
396 if separate && sep_place.is_back() {
397 result.push_str(formatting.separator);
400 if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
401 let comment = item.post_comment.as_ref().unwrap();
402 let overhead = last_line_width(&result) + first_line_width(comment.trim());
404 let rewrite_post_comment = |item_max_width: &mut Option<usize>| {
405 if item_max_width.is_none() && !last && !inner_item.contains('\n') {
406 *item_max_width = Some(max_width_of_item_with_post_comment(
410 formatting.config.max_width(),
413 let overhead = if let Some(max_width) = *item_max_width {
416 // 1 = space between item and comment.
417 item_last_line_width + 1
419 let width = formatting.shape.width.checked_sub(overhead).unwrap_or(1);
420 let offset = formatting.shape.indent + overhead;
421 let comment_shape = Shape::legacy(width, offset);
423 // Use block-style only for the last item or multiline comments.
424 let block_style = !formatting.ends_with_newline && last
425 || comment.trim().contains('\n')
426 || comment.trim().len() > width;
428 rewrite_comment(comment, block_style, comment_shape, formatting.config)
431 let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?;
433 if !starts_with_newline(&formatted_comment) {
434 let mut comment_alignment =
435 post_comment_alignment(item_max_width, inner_item.len());
436 if first_line_width(&formatted_comment) + last_line_width(&result)
437 + comment_alignment + 1 > formatting.config.max_width()
439 item_max_width = None;
440 formatted_comment = rewrite_post_comment(&mut item_max_width)?;
441 comment_alignment = post_comment_alignment(item_max_width, inner_item.len());
443 for _ in 0..(comment_alignment + 1) {
446 // An additional space for the missing trailing separator.
447 if last && item_max_width.is_some() && !separate && !formatting.separator.is_empty()
452 if formatted_comment.contains('\n') {
453 item_max_width = None;
455 result.push_str(&formatted_comment);
457 item_max_width = None;
460 if formatting.preserve_newline && !last && tactic == DefinitiveListTactic::Vertical
463 item_max_width = None;
471 fn max_width_of_item_with_post_comment<I, T>(
478 I: IntoIterator<Item = T> + Clone,
481 let mut max_width = 0;
482 let mut first = true;
483 for item in items.clone().into_iter().skip(i) {
484 let item = item.as_ref();
485 let inner_item_width = item.inner_as_ref().len();
487 && (item.is_different_group() || !item.post_comment.is_some()
488 || inner_item_width + overhead > max_budget)
492 if max_width < inner_item_width {
493 max_width = inner_item_width;
503 fn post_comment_alignment(item_max_width: Option<usize>, inner_item_len: usize) -> usize {
505 .and_then(|max_line_width| max_line_width.checked_sub(inner_item_len))
509 pub struct ListItems<'a, I, F1, F2, F3>
513 codemap: &'a CodeMap,
518 prev_span_end: BytePos,
519 next_span_start: BytePos,
525 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
527 I: Iterator<Item = T>,
528 F1: Fn(&T) -> BytePos,
529 F2: Fn(&T) -> BytePos,
530 F3: Fn(&T) -> Option<String>,
532 type Item = ListItem;
534 fn next(&mut self) -> Option<Self::Item> {
535 let white_space: &[_] = &[' ', '\t'];
537 self.inner.next().map(|item| {
538 let mut new_lines = false;
540 let pre_snippet = self.codemap
541 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
543 let trimmed_pre_snippet = pre_snippet.trim();
544 let has_single_line_comment = trimmed_pre_snippet.starts_with("//");
545 let has_block_comment = trimmed_pre_snippet.starts_with("/*");
546 let (pre_comment, pre_comment_style) = if has_single_line_comment {
548 Some(trimmed_pre_snippet.to_owned()),
549 ListItemCommentStyle::DifferentLine,
551 } else if has_block_comment {
552 let comment_end = pre_snippet.chars().rev().position(|c| c == '/').unwrap();
556 .take(comment_end + 1)
560 Some(trimmed_pre_snippet.to_owned()),
561 ListItemCommentStyle::DifferentLine,
565 Some(trimmed_pre_snippet.to_owned()),
566 ListItemCommentStyle::SameLine,
570 (None, ListItemCommentStyle::None)
574 let next_start = match self.inner.peek() {
575 Some(next_item) => (self.get_lo)(next_item),
576 None => self.next_span_start,
578 let post_snippet = self.codemap
579 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
582 let comment_end = match self.inner.peek() {
584 let mut block_open_index = post_snippet.find("/*");
585 // check if it really is a block comment (and not `//*` or a nested comment)
586 if let Some(i) = block_open_index {
587 match post_snippet.find("/") {
588 Some(j) if j < i => block_open_index = None,
589 _ if i > 0 && &post_snippet[i - 1..i] == "/" => block_open_index = None,
593 let newline_index = post_snippet.find('\n');
594 if let Some(separator_index) = post_snippet.find_uncommented(self.separator) {
595 match (block_open_index, newline_index) {
596 // Separator before comment, with the next item on same line.
597 // Comment belongs to next item.
598 (Some(i), None) if i > separator_index => separator_index + 1,
599 // Block-style post-comment before the separator.
600 (Some(i), None) => cmp::max(
601 find_comment_end(&post_snippet[i..]).unwrap() + i,
604 // Block-style post-comment. Either before or after the separator.
605 (Some(i), Some(j)) if i < j => cmp::max(
606 find_comment_end(&post_snippet[i..]).unwrap() + i,
609 // Potential *single* line comment.
610 (_, Some(j)) if j > separator_index => j + 1,
611 _ => post_snippet.len(),
614 // Match arms may not have trailing comma. In any case, for match arms,
615 // we will assume that the post comment belongs to the next arm if they
616 // do not end with trailing comma.
617 if let Some(newline_index) = newline_index {
625 .find_uncommented(self.terminator)
626 .unwrap_or_else(|| post_snippet.len()),
629 if !post_snippet.is_empty() && comment_end > 0 {
630 // Account for extra whitespace between items. This is fiddly
631 // because of the way we divide pre- and post- comments.
633 // Everything from the separator to the next item.
634 let test_snippet = &post_snippet[comment_end - 1..];
635 let first_newline = test_snippet
637 .unwrap_or_else(|| test_snippet.len());
638 // From the end of the first line of comments.
639 let test_snippet = &test_snippet[first_newline..];
640 let first = test_snippet
641 .find(|c: char| !c.is_whitespace())
642 .unwrap_or_else(|| test_snippet.len());
643 // From the end of the first line of comments to the next non-whitespace char.
644 let test_snippet = &test_snippet[..first];
646 if test_snippet.chars().filter(|c| c == &'\n').count() > 1 {
647 // There were multiple line breaks which got trimmed to nothing.
652 // Cleanup post-comment: strip separators and whitespace.
653 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
654 let post_snippet = post_snippet[..comment_end].trim();
656 let post_snippet_trimmed = if post_snippet.starts_with(|c| c == ',' || c == ':') {
657 post_snippet[1..].trim_matches(white_space)
658 } else if post_snippet.ends_with(',') {
659 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
664 let post_comment = if !post_snippet_trimmed.is_empty() {
665 Some(post_snippet_trimmed.to_owned())
671 pre_comment: pre_comment,
672 pre_comment_style: pre_comment_style,
673 item: if self.inner.peek().is_none() && self.leave_last {
676 (self.get_item_string)(&item)
678 post_comment: post_comment,
679 new_lines: new_lines,
685 // Creates an iterator over a list's items with associated comments.
686 pub fn itemize_list<'a, T, I, F1, F2, F3>(
687 codemap: &'a CodeMap,
694 prev_span_end: BytePos,
695 next_span_start: BytePos,
697 ) -> ListItems<'a, I, F1, F2, F3>
699 I: Iterator<Item = T>,
700 F1: Fn(&T) -> BytePos,
701 F2: Fn(&T) -> BytePos,
702 F3: Fn(&T) -> Option<String>,
706 inner: inner.peekable(),
709 get_item_string: get_item_string,
710 prev_span_end: prev_span_end,
711 next_span_start: next_span_start,
712 terminator: terminator,
713 separator: separator,
714 leave_last: leave_last,
718 /// Returns the count and total width of the list items.
719 fn calculate_width<I, T>(items: I) -> (usize, usize)
721 I: IntoIterator<Item = T>,
726 .map(|item| total_item_width(item.as_ref()))
727 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
730 pub fn total_item_width(item: &ListItem) -> usize {
731 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
732 + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
733 + item.item.as_ref().map_or(0, |str| str.len())
736 fn comment_len(comment: Option<&str>) -> usize {
739 let text_len = s.trim().len();
741 // We'll put " /*" before and " */" after inline comments.
751 // Compute horizontal and vertical shapes for a struct-lit-like thing.
752 pub fn struct_lit_shape(
754 context: &RewriteContext,
757 ) -> Option<(Option<Shape>, Shape)> {
758 let v_shape = match context.config.indent_style() {
759 IndentStyle::Visual => shape
761 .shrink_left(prefix_width)?
762 .sub_width(suffix_width)?,
763 IndentStyle::Block => {
764 let shape = shape.block_indent(context.config.tab_spaces());
766 width: context.budget(shape.indent.width()),
771 let shape_width = shape.width.checked_sub(prefix_width + suffix_width);
772 if let Some(w) = shape_width {
773 let shape_width = cmp::min(w, context.config.struct_lit_width());
774 Some((Some(Shape::legacy(shape_width, shape.indent)), v_shape))
776 Some((None, v_shape))
780 // Compute the tactic for the internals of a struct-lit-like thing.
781 pub fn struct_lit_tactic(
782 h_shape: Option<Shape>,
783 context: &RewriteContext,
785 ) -> DefinitiveListTactic {
786 if let Some(h_shape) = h_shape {
787 let prelim_tactic = match (context.config.indent_style(), items.len()) {
788 (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
789 _ => context.config.struct_lit_multiline_style().to_list_tactic(),
791 definitive_tactic(items, prelim_tactic, Separator::Comma, h_shape.width)
793 DefinitiveListTactic::Vertical
797 // Given a tactic and possible shapes for horizontal and vertical layout,
798 // come up with the actual shape to use.
799 pub fn shape_for_tactic(
800 tactic: DefinitiveListTactic,
801 h_shape: Option<Shape>,
805 DefinitiveListTactic::Horizontal => h_shape.unwrap(),
810 // Create a ListFormatting object for formatting the internals of a
811 // struct-lit-like thing, that is a series of fields.
812 pub fn struct_lit_formatting<'a>(
814 tactic: DefinitiveListTactic,
815 context: &'a RewriteContext,
816 force_no_trailing_comma: bool,
817 ) -> ListFormatting<'a> {
818 let ends_with_newline = context.config.indent_style() != IndentStyle::Visual
819 && tactic == DefinitiveListTactic::Vertical;
823 trailing_separator: if force_no_trailing_comma {
824 SeparatorTactic::Never
826 context.config.trailing_comma()
828 separator_place: SeparatorPlace::Back,
830 ends_with_newline: ends_with_newline,
831 preserve_newline: true,
832 config: context.config,