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.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!()` variants.
165 // Special case tactic for `write!()` varianta.
169 impl DefinitiveListTactic {
170 pub fn ends_with_newline(&self, indent_style: IndentStyle) -> bool {
172 IndentStyle::Block => *self != DefinitiveListTactic::Horizontal,
173 IndentStyle::Visual => false,
178 /// The type of separator for lists.
179 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
186 pub fn len(&self) -> usize {
189 Separator::Comma => 2,
191 Separator::VerticalBar => 3,
196 /// Where to put separator.
197 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
198 pub enum SeparatorPlace {
203 impl_enum_serialize_and_deserialize!(SeparatorPlace, Front, Back);
205 impl SeparatorPlace {
206 pub fn is_front(&self) -> bool {
207 *self == SeparatorPlace::Front
210 pub fn is_back(&self) -> bool {
211 *self == SeparatorPlace::Back
215 default: SeparatorPlace,
216 tactic: DefinitiveListTactic,
218 ) -> SeparatorPlace {
220 DefinitiveListTactic::Vertical => default,
230 pub fn definitive_tactic<I, T>(
235 ) -> DefinitiveListTactic
237 I: IntoIterator<Item = T> + Clone,
240 let pre_line_comments = items
243 .any(|item| item.as_ref().has_comment());
245 let limit = match tactic {
246 _ if pre_line_comments => return DefinitiveListTactic::Vertical,
247 ListTactic::Mixed => return DefinitiveListTactic::Mixed,
248 ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
249 ListTactic::Vertical => return DefinitiveListTactic::Vertical,
250 ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
251 ListTactic::HorizontalVertical => width,
254 let (sep_count, total_width) = calculate_width(items.clone());
255 let total_sep_len = sep.len() * sep_count.checked_sub(1).unwrap_or(0);
256 let real_total = total_width + total_sep_len;
258 if real_total <= limit && !pre_line_comments
259 && !items.into_iter().any(|item| item.as_ref().is_multiline())
261 DefinitiveListTactic::Horizontal
263 DefinitiveListTactic::Vertical
267 // Format a list of commented items into a string.
268 // TODO: add unit tests
269 pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
271 I: IntoIterator<Item = T> + Clone,
274 let mut tactic = formatting.tactic;
275 let sep_len = formatting.separator.len();
277 // Now that we know how we will layout, we can decide for sure if there
278 // will be a trailing separator.
279 let mut trailing_separator = formatting.needs_trailing_separator();
280 let mut result = String::with_capacity(128);
281 let cloned_items = items.clone();
282 let mut iter = items.into_iter().enumerate().peekable();
283 let mut item_max_width: Option<usize> = None;
285 SeparatorPlace::from_tactic(formatting.separator_place, tactic, formatting.separator);
287 let mut line_len = 0;
288 let indent_str = &formatting.shape.indent.to_string(formatting.config);
289 while let Some((i, item)) = iter.next() {
290 let item = item.as_ref();
291 let inner_item = item.item.as_ref()?;
293 let last = iter.peek().is_none();
294 let mut separate = match sep_place {
295 SeparatorPlace::Front => !first,
296 SeparatorPlace::Back => !last || trailing_separator,
298 let item_sep_len = if separate { sep_len } else { 0 };
300 // Item string may be multi-line. Its length (used for block comment alignment)
301 // should be only the length of the last line.
302 let item_last_line = if item.is_multiline() {
303 inner_item.lines().last().unwrap_or("")
307 let mut item_last_line_width = item_last_line.len() + item_sep_len;
308 if item_last_line.starts_with(&**indent_str) {
309 item_last_line_width -= indent_str.len();
313 DefinitiveListTactic::Horizontal if !first => {
316 DefinitiveListTactic::FormatCall if !first => {
318 result.push_str(indent_str);
319 tactic = DefinitiveListTactic::Horizontal;
321 DefinitiveListTactic::WriteCall => {
329 result.push_str(indent_str);
332 result.push_str(indent_str);
333 tactic = DefinitiveListTactic::Horizontal;
338 DefinitiveListTactic::Vertical if !first => {
340 result.push_str(indent_str);
342 DefinitiveListTactic::Mixed => {
343 let total_width = total_item_width(item) + item_sep_len;
345 // 1 is space between separator and item.
346 if line_len > 0 && line_len + 1 + total_width > formatting.shape.width {
348 result.push_str(indent_str);
350 if formatting.ends_with_newline {
354 trailing_separator = true;
364 line_len += total_width;
370 if let Some(ref comment) = item.pre_comment {
371 // Block style in non-vertical mode.
372 let block_mode = tactic != DefinitiveListTactic::Vertical;
373 // Width restriction is only relevant in vertical mode.
375 rewrite_comment(comment, block_mode, formatting.shape, formatting.config)?;
376 result.push_str(&comment);
378 if tactic == DefinitiveListTactic::Vertical {
379 // We cannot keep pre-comments on the same line if the comment if normalized.
380 let keep_comment = if formatting.config.normalize_comments()
381 || item.pre_comment_style == ListItemCommentStyle::DifferentLine
385 // We will try to keep the comment on the same line with the item here.
387 let total_width = total_item_width(item) + item_sep_len + 1;
388 total_width <= formatting.shape.width
394 result.push_str(indent_str);
399 item_max_width = None;
402 if separate && sep_place.is_front() && !first {
403 result.push_str(formatting.separator.trim());
406 result.push_str(&inner_item[..]);
409 if tactic != DefinitiveListTactic::Vertical && item.post_comment.is_some() {
410 let comment = item.post_comment.as_ref().unwrap();
411 let formatted_comment = rewrite_comment(
414 Shape::legacy(formatting.shape.width, Indent::empty()),
419 result.push_str(&formatted_comment);
422 if separate && sep_place.is_back() {
423 result.push_str(formatting.separator);
426 if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
427 let comment = item.post_comment.as_ref().unwrap();
428 let overhead = last_line_width(&result) + first_line_width(comment.trim());
430 let rewrite_post_comment = |item_max_width: &mut Option<usize>| {
431 if item_max_width.is_none() && !last && !inner_item.contains('\n') {
432 *item_max_width = Some(max_width_of_item_with_post_comment(
436 formatting.config.max_width(),
439 let overhead = if starts_with_newline(comment) {
441 } else if let Some(max_width) = *item_max_width {
444 // 1 = space between item and comment.
445 item_last_line_width + 1
447 let width = formatting.shape.width.checked_sub(overhead).unwrap_or(1);
448 let offset = formatting.shape.indent + overhead;
449 let comment_shape = Shape::legacy(width, offset);
451 // Use block-style only for the last item or multiline comments.
452 let block_style = !formatting.ends_with_newline && last
453 || comment.trim().contains('\n')
454 || comment.trim().len() > width;
464 let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?;
466 if !starts_with_newline(comment) {
467 let mut comment_alignment =
468 post_comment_alignment(item_max_width, inner_item.len());
469 if first_line_width(&formatted_comment) + last_line_width(&result)
470 + comment_alignment + 1 > formatting.config.max_width()
472 item_max_width = None;
473 formatted_comment = rewrite_post_comment(&mut item_max_width)?;
474 comment_alignment = post_comment_alignment(item_max_width, inner_item.len());
476 for _ in 0..(comment_alignment + 1) {
479 // An additional space for the missing trailing separator.
480 if last && item_max_width.is_some() && !separate && !formatting.separator.is_empty()
486 result.push_str(indent_str);
488 if formatted_comment.contains('\n') {
489 item_max_width = None;
491 result.push_str(&formatted_comment);
493 item_max_width = None;
496 if formatting.preserve_newline && !last && tactic == DefinitiveListTactic::Vertical
499 item_max_width = None;
507 fn max_width_of_item_with_post_comment<I, T>(
514 I: IntoIterator<Item = T> + Clone,
517 let mut max_width = 0;
518 let mut first = true;
519 for item in items.clone().into_iter().skip(i) {
520 let item = item.as_ref();
521 let inner_item_width = item.inner_as_ref().len();
523 && (item.is_different_group() || !item.post_comment.is_some()
524 || inner_item_width + overhead > max_budget)
528 if max_width < inner_item_width {
529 max_width = inner_item_width;
539 fn post_comment_alignment(item_max_width: Option<usize>, inner_item_len: usize) -> usize {
541 .and_then(|max_line_width| max_line_width.checked_sub(inner_item_len))
545 pub struct ListItems<'a, I, F1, F2, F3>
549 codemap: &'a CodeMap,
554 prev_span_end: BytePos,
555 next_span_start: BytePos,
561 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
563 I: Iterator<Item = T>,
564 F1: Fn(&T) -> BytePos,
565 F2: Fn(&T) -> BytePos,
566 F3: Fn(&T) -> Option<String>,
568 type Item = ListItem;
570 fn next(&mut self) -> Option<Self::Item> {
571 let white_space: &[_] = &[' ', '\t'];
573 self.inner.next().map(|item| {
574 let mut new_lines = false;
576 let pre_snippet = self.codemap
577 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
579 let trimmed_pre_snippet = pre_snippet.trim();
580 let has_single_line_comment = trimmed_pre_snippet.starts_with("//");
581 let has_block_comment = trimmed_pre_snippet.starts_with("/*");
582 let (pre_comment, pre_comment_style) = if has_single_line_comment {
584 Some(trimmed_pre_snippet.to_owned()),
585 ListItemCommentStyle::DifferentLine,
587 } else if has_block_comment {
588 let comment_end = pre_snippet.chars().rev().position(|c| c == '/').unwrap();
592 .take(comment_end + 1)
596 Some(trimmed_pre_snippet.to_owned()),
597 ListItemCommentStyle::DifferentLine,
601 Some(trimmed_pre_snippet.to_owned()),
602 ListItemCommentStyle::SameLine,
606 (None, ListItemCommentStyle::None)
610 let next_start = match self.inner.peek() {
611 Some(next_item) => (self.get_lo)(next_item),
612 None => self.next_span_start,
614 let post_snippet = self.codemap
615 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
618 let comment_end = match self.inner.peek() {
620 let mut block_open_index = post_snippet.find("/*");
621 // check if it really is a block comment (and not `//*` or a nested comment)
622 if let Some(i) = block_open_index {
623 match post_snippet.find('/') {
624 Some(j) if j < i => block_open_index = None,
625 _ if i > 0 && &post_snippet[i - 1..i] == "/" => block_open_index = None,
629 let newline_index = post_snippet.find('\n');
630 if let Some(separator_index) = post_snippet.find_uncommented(self.separator) {
631 match (block_open_index, newline_index) {
632 // Separator before comment, with the next item on same line.
633 // Comment belongs to next item.
634 (Some(i), None) if i > separator_index => separator_index + 1,
635 // Block-style post-comment before the separator.
636 (Some(i), None) => cmp::max(
637 find_comment_end(&post_snippet[i..]).unwrap() + i,
640 // Block-style post-comment. Either before or after the separator.
641 (Some(i), Some(j)) if i < j => cmp::max(
642 find_comment_end(&post_snippet[i..]).unwrap() + i,
645 // Potential *single* line comment.
646 (_, Some(j)) if j > separator_index => j + 1,
647 _ => post_snippet.len(),
649 } else if let Some(newline_index) = newline_index {
650 // Match arms may not have trailing comma. In any case, for match arms,
651 // we will assume that the post comment belongs to the next arm if they
652 // do not end with trailing comma.
659 .find_uncommented(self.terminator)
660 .unwrap_or_else(|| post_snippet.len()),
663 if !post_snippet.is_empty() && comment_end > 0 {
664 // Account for extra whitespace between items. This is fiddly
665 // because of the way we divide pre- and post- comments.
667 // Everything from the separator to the next item.
668 let test_snippet = &post_snippet[comment_end - 1..];
669 let first_newline = test_snippet
671 .unwrap_or_else(|| test_snippet.len());
672 // From the end of the first line of comments.
673 let test_snippet = &test_snippet[first_newline..];
674 let first = test_snippet
675 .find(|c: char| !c.is_whitespace())
676 .unwrap_or_else(|| test_snippet.len());
677 // From the end of the first line of comments to the next non-whitespace char.
678 let test_snippet = &test_snippet[..first];
680 if test_snippet.chars().filter(|c| c == &'\n').count() > 1 {
681 // There were multiple line breaks which got trimmed to nothing.
686 // Cleanup post-comment: strip separators and whitespace.
687 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
688 let post_snippet = post_snippet[..comment_end].trim();
690 let post_snippet_trimmed = if post_snippet.starts_with(|c| c == ',' || c == ':') {
691 post_snippet[1..].trim_matches(white_space)
692 } else if post_snippet.ends_with(',') {
693 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
698 let post_comment = if !post_snippet_trimmed.is_empty() {
699 Some(post_snippet_trimmed.to_owned())
705 pre_comment: pre_comment,
706 pre_comment_style: pre_comment_style,
707 item: if self.inner.peek().is_none() && self.leave_last {
710 (self.get_item_string)(&item)
712 post_comment: post_comment,
713 new_lines: new_lines,
719 // Creates an iterator over a list's items with associated comments.
720 pub fn itemize_list<'a, T, I, F1, F2, F3>(
721 codemap: &'a CodeMap,
728 prev_span_end: BytePos,
729 next_span_start: BytePos,
731 ) -> ListItems<'a, I, F1, F2, F3>
733 I: Iterator<Item = T>,
734 F1: Fn(&T) -> BytePos,
735 F2: Fn(&T) -> BytePos,
736 F3: Fn(&T) -> Option<String>,
740 inner: inner.peekable(),
743 get_item_string: get_item_string,
744 prev_span_end: prev_span_end,
745 next_span_start: next_span_start,
746 terminator: terminator,
747 separator: separator,
748 leave_last: leave_last,
752 /// Returns the count and total width of the list items.
753 fn calculate_width<I, T>(items: I) -> (usize, usize)
755 I: IntoIterator<Item = T>,
760 .map(|item| total_item_width(item.as_ref()))
761 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
764 pub fn total_item_width(item: &ListItem) -> usize {
765 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
766 + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
767 + item.item.as_ref().map_or(0, |str| str.len())
770 fn comment_len(comment: Option<&str>) -> usize {
773 let text_len = s.trim().len();
775 // We'll put " /*" before and " */" after inline comments.
785 // Compute horizontal and vertical shapes for a struct-lit-like thing.
786 pub fn struct_lit_shape(
788 context: &RewriteContext,
791 ) -> Option<(Option<Shape>, Shape)> {
792 let v_shape = match context.config.indent_style() {
793 IndentStyle::Visual => shape
795 .shrink_left(prefix_width)?
796 .sub_width(suffix_width)?,
797 IndentStyle::Block => {
798 let shape = shape.block_indent(context.config.tab_spaces());
800 width: context.budget(shape.indent.width()),
805 let shape_width = shape.width.checked_sub(prefix_width + suffix_width);
806 if let Some(w) = shape_width {
807 let shape_width = cmp::min(w, context.config.width_heuristics().struct_lit_width);
808 Some((Some(Shape::legacy(shape_width, shape.indent)), v_shape))
810 Some((None, v_shape))
814 // Compute the tactic for the internals of a struct-lit-like thing.
815 pub fn struct_lit_tactic(
816 h_shape: Option<Shape>,
817 context: &RewriteContext,
819 ) -> DefinitiveListTactic {
820 if let Some(h_shape) = h_shape {
821 let prelim_tactic = match (context.config.indent_style(), items.len()) {
822 (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
823 _ if context.config.struct_lit_single_line() => ListTactic::HorizontalVertical,
824 _ => ListTactic::Vertical,
826 definitive_tactic(items, prelim_tactic, Separator::Comma, h_shape.width)
828 DefinitiveListTactic::Vertical
832 // Given a tactic and possible shapes for horizontal and vertical layout,
833 // come up with the actual shape to use.
834 pub fn shape_for_tactic(
835 tactic: DefinitiveListTactic,
836 h_shape: Option<Shape>,
840 DefinitiveListTactic::Horizontal => h_shape.unwrap(),
845 // Create a ListFormatting object for formatting the internals of a
846 // struct-lit-like thing, that is a series of fields.
847 pub fn struct_lit_formatting<'a>(
849 tactic: DefinitiveListTactic,
850 context: &'a RewriteContext,
851 force_no_trailing_comma: bool,
852 ) -> ListFormatting<'a> {
853 let ends_with_newline = context.config.indent_style() != IndentStyle::Visual
854 && tactic == DefinitiveListTactic::Vertical;
858 trailing_separator: if force_no_trailing_comma {
859 SeparatorTactic::Never
861 context.config.trailing_comma()
863 separator_place: SeparatorPlace::Back,
865 ends_with_newline: ends_with_newline,
866 preserve_newline: true,
867 config: context.config,