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};
17 use comment::{find_comment_end, rewrite_comment, FindUncommented};
18 use config::{Config, IndentStyle};
19 use rewrite::RewriteContext;
20 use utils::{first_line_width, last_line_width, mk_sp};
22 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
23 /// Formatting tactic for lists. This will be cast down to a
24 /// DefinitiveListTactic depending on the number and length of the items and
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,
65 // Non-expressions, e.g. items, will have a new line at the end of the list.
66 // Important for comment styles.
67 pub ends_with_newline: bool,
68 // Remove newlines between list elements for expressions.
69 pub preserve_newline: bool,
70 pub config: &'a Config,
73 impl AsRef<ListItem> for ListItem {
74 fn as_ref(&self) -> &ListItem {
79 #[derive(PartialEq, Eq)]
80 pub enum ListItemCommentStyle {
81 // Try to keep the comment on the same line with the item.
83 // Put the comment on the previous or the next line of the item.
85 // No comment available.
90 // None for comments mean that they are not present.
91 pub pre_comment: Option<String>,
92 pub pre_comment_style: ListItemCommentStyle,
93 // Item should include attributes and doc comments. None indicates a failed
95 pub item: Option<String>,
96 pub post_comment: Option<String>,
97 // Whether there is extra whitespace before this item.
102 pub fn inner_as_ref(&self) -> &str {
103 self.item.as_ref().map_or("", |s| &*s)
106 pub fn is_multiline(&self) -> bool {
107 self.inner_as_ref().contains('\n') || self.pre_comment.is_some() ||
110 .map_or(false, |s| s.contains('\n'))
113 pub fn has_comment(&self) -> bool {
116 .map_or(false, |comment| comment.starts_with("//")) ||
119 .map_or(false, |comment| comment.starts_with("//"))
122 pub fn from_str<S: Into<String>>(s: S) -> ListItem {
125 pre_comment_style: ListItemCommentStyle::None,
126 item: Some(s.into()),
133 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
134 /// The definitive formatting tactic for lists.
135 pub enum DefinitiveListTactic {
141 impl DefinitiveListTactic {
142 pub fn ends_with_newline(&self, indent_style: IndentStyle) -> bool {
144 IndentStyle::Block => *self != DefinitiveListTactic::Horizontal,
145 IndentStyle::Visual => false,
150 /// The type of separator for lists.
151 #[derive(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_comment());
183 let limit = match tactic {
184 _ if pre_line_comments => return DefinitiveListTactic::Vertical,
185 ListTactic::Mixed => return DefinitiveListTactic::Mixed,
186 ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
187 ListTactic::Vertical => return DefinitiveListTactic::Vertical,
188 ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
189 ListTactic::HorizontalVertical => width,
192 let (sep_count, total_width) = calculate_width(items.clone());
193 let total_sep_len = sep.len() * sep_count.checked_sub(1).unwrap_or(0);
194 let real_total = total_width + total_sep_len;
196 if real_total <= limit && !pre_line_comments &&
197 !items.into_iter().any(|item| item.as_ref().is_multiline())
199 DefinitiveListTactic::Horizontal
201 DefinitiveListTactic::Vertical
205 // Format a list of commented items into a string.
206 // TODO: add unit tests
207 pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
209 I: IntoIterator<Item = T> + Clone,
212 let tactic = formatting.tactic;
213 let sep_len = formatting.separator.len();
215 // Now that we know how we will layout, we can decide for sure if there
216 // will be a trailing separator.
217 let mut trailing_separator = needs_trailing_separator(formatting.trailing_separator, tactic);
218 let mut result = String::new();
219 let cloned_items = items.clone();
220 let mut iter = items.into_iter().enumerate().peekable();
221 let mut item_max_width: Option<usize> = None;
223 let mut line_len = 0;
224 let indent_str = &formatting.shape.indent.to_string(formatting.config);
225 while let Some((i, item)) = iter.next() {
226 let item = item.as_ref();
227 let inner_item = try_opt!(item.item.as_ref());
229 let last = iter.peek().is_none();
230 let mut separate = !last || trailing_separator;
231 let item_sep_len = if separate { sep_len } else { 0 };
233 // Item string may be multi-line. Its length (used for block comment alignment)
234 // should be only the length of the last line.
235 let item_last_line = if item.is_multiline() {
236 inner_item.lines().last().unwrap_or("")
240 let mut item_last_line_width = item_last_line.len() + item_sep_len;
241 if item_last_line.starts_with(indent_str) {
242 item_last_line_width -= indent_str.len();
246 DefinitiveListTactic::Horizontal if !first => {
249 DefinitiveListTactic::Vertical if !first => {
251 result.push_str(indent_str);
253 DefinitiveListTactic::Mixed => {
254 let total_width = total_item_width(item) + item_sep_len;
256 // 1 is space between separator and item.
257 if line_len > 0 && line_len + 1 + total_width > formatting.shape.width {
259 result.push_str(indent_str);
261 if tactic == DefinitiveListTactic::Mixed && formatting.ends_with_newline {
265 trailing_separator = true;
275 line_len += total_width;
281 if let Some(ref comment) = item.pre_comment {
282 // Block style in non-vertical mode.
283 let block_mode = tactic != DefinitiveListTactic::Vertical;
284 // Width restriction is only relevant in vertical mode.
285 let comment = try_opt!(rewrite_comment(
291 result.push_str(&comment);
293 if tactic == DefinitiveListTactic::Vertical {
294 // We cannot keep pre-comments on the same line if the comment if normalized.
295 let keep_comment = if formatting.config.normalize_comments() {
297 } else if item.pre_comment_style == ListItemCommentStyle::DifferentLine {
300 // We will try to keep the comment on the same line with the item here.
302 let total_width = total_item_width(item) + item_sep_len + 1;
303 total_width <= formatting.shape.width
309 result.push_str(indent_str);
314 item_max_width = None;
317 result.push_str(&inner_item[..]);
320 if tactic != DefinitiveListTactic::Vertical && item.post_comment.is_some() {
321 let comment = item.post_comment.as_ref().unwrap();
322 let formatted_comment = try_opt!(rewrite_comment(
325 Shape::legacy(formatting.shape.width, Indent::empty()),
330 result.push_str(&formatted_comment);
334 result.push_str(formatting.separator);
337 if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
338 let comment = item.post_comment.as_ref().unwrap();
339 let overhead = last_line_width(&result) + first_line_width(comment.trim());
341 let rewrite_post_comment = |item_max_width: &mut Option<usize>| {
342 if item_max_width.is_none() && !last && !inner_item.contains('\n') {
343 *item_max_width = Some(max_width_of_item_with_post_comment(
347 formatting.config.max_width(),
350 let overhead = if let &mut Some(max_width) = item_max_width {
353 // 1 = space between item and comment.
354 item_last_line_width + 1
356 let width = formatting.shape.width.checked_sub(overhead).unwrap_or(1);
357 let offset = formatting.shape.indent + overhead;
358 let comment_shape = Shape::legacy(width, offset);
360 // Use block-style only for the last item or multiline comments.
361 let block_style = !formatting.ends_with_newline && last ||
362 comment.trim().contains('\n') ||
363 comment.trim().len() > width;
365 rewrite_comment(comment, block_style, comment_shape, formatting.config)
368 let mut formatted_comment = try_opt!(rewrite_post_comment(&mut item_max_width));
370 if !formatted_comment.starts_with('\n') {
371 let mut comment_alignment =
372 post_comment_alignment(item_max_width, inner_item.len());
373 if first_line_width(&formatted_comment) + last_line_width(&result) +
374 comment_alignment + 1 > formatting.config.max_width()
376 item_max_width = None;
377 formatted_comment = try_opt!(rewrite_post_comment(&mut item_max_width));
378 comment_alignment = post_comment_alignment(item_max_width, inner_item.len());
380 for _ in 0..(comment_alignment + 1) {
383 // An additional space for the missing trailing comma
384 if last && item_max_width.is_some() && !separate {
388 if formatted_comment.contains('\n') {
389 item_max_width = None;
391 result.push_str(&formatted_comment);
393 item_max_width = None;
396 if formatting.preserve_newline && !last && tactic == DefinitiveListTactic::Vertical &&
399 item_max_width = None;
407 fn max_width_of_item_with_post_comment<I, T>(
414 I: IntoIterator<Item = T> + Clone,
417 let mut max_width = 0;
418 let mut first = true;
419 for item in items.clone().into_iter().skip(i) {
420 let item = item.as_ref();
421 let inner_item_width = item.inner_as_ref().len();
423 (item.is_multiline() || !item.post_comment.is_some() ||
424 inner_item_width + overhead > max_budget)
428 if max_width < inner_item_width {
429 max_width = inner_item_width;
439 fn post_comment_alignment(item_max_width: Option<usize>, inner_item_len: usize) -> usize {
441 .and_then(|max_line_width| max_line_width.checked_sub(inner_item_len))
445 pub struct ListItems<'a, I, F1, F2, F3>
449 codemap: &'a CodeMap,
454 prev_span_end: BytePos,
455 next_span_start: BytePos,
459 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
461 I: Iterator<Item = T>,
462 F1: Fn(&T) -> BytePos,
463 F2: Fn(&T) -> BytePos,
464 F3: Fn(&T) -> Option<String>,
466 type Item = ListItem;
468 fn next(&mut self) -> Option<Self::Item> {
469 let white_space: &[_] = &[' ', '\t'];
471 self.inner.next().map(|item| {
472 let mut new_lines = false;
474 let pre_snippet = self.codemap
475 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
477 let trimmed_pre_snippet = pre_snippet.trim();
478 let has_single_line_comment = trimmed_pre_snippet.starts_with("//");
479 let has_block_comment = trimmed_pre_snippet.starts_with("/*");
480 let (pre_comment, pre_comment_style) = if has_single_line_comment {
482 Some(trimmed_pre_snippet.to_owned()),
483 ListItemCommentStyle::DifferentLine,
485 } else if has_block_comment {
486 let comment_end = pre_snippet.chars().rev().position(|c| c == '/').unwrap();
490 .take(comment_end + 1)
491 .find(|c| *c == '\n')
495 Some(trimmed_pre_snippet.to_owned()),
496 ListItemCommentStyle::DifferentLine,
500 Some(trimmed_pre_snippet.to_owned()),
501 ListItemCommentStyle::SameLine,
505 (None, ListItemCommentStyle::None)
509 let next_start = match self.inner.peek() {
510 Some(next_item) => (self.get_lo)(next_item),
511 None => self.next_span_start,
513 let post_snippet = self.codemap
514 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
517 let comment_end = match self.inner.peek() {
519 let mut block_open_index = post_snippet.find("/*");
520 // check if it realy is a block comment (and not //*)
521 if let Some(i) = block_open_index {
522 if i > 0 && &post_snippet[i - 1..i] == "/" {
523 block_open_index = None;
526 let newline_index = post_snippet.find('\n');
527 let separator_index = post_snippet.find_uncommented(",").unwrap();
529 match (block_open_index, newline_index) {
530 // Separator before comment, with the next item on same line.
531 // Comment belongs to next item.
532 (Some(i), None) if i > separator_index => separator_index + 1,
533 // Block-style post-comment before the separator.
534 (Some(i), None) => cmp::max(
535 find_comment_end(&post_snippet[i..]).unwrap() + i,
538 // Block-style post-comment. Either before or after the separator.
539 (Some(i), Some(j)) if i < j => cmp::max(
540 find_comment_end(&post_snippet[i..]).unwrap() + i,
543 // Potential *single* line comment.
544 (_, Some(j)) if j > separator_index => j + 1,
545 _ => post_snippet.len(),
549 .find_uncommented(self.terminator)
550 .unwrap_or(post_snippet.len()),
553 if !post_snippet.is_empty() && comment_end > 0 {
554 // Account for extra whitespace between items. This is fiddly
555 // because of the way we divide pre- and post- comments.
557 // Everything from the separator to the next item.
558 let test_snippet = &post_snippet[comment_end - 1..];
559 let first_newline = test_snippet.find('\n').unwrap_or(test_snippet.len());
560 // From the end of the first line of comments.
561 let test_snippet = &test_snippet[first_newline..];
562 let first = test_snippet
563 .find(|c: char| !c.is_whitespace())
564 .unwrap_or(test_snippet.len());
565 // From the end of the first line of comments to the next non-whitespace char.
566 let test_snippet = &test_snippet[..first];
568 if test_snippet.chars().filter(|c| c == &'\n').count() > 1 {
569 // There were multiple line breaks which got trimmed to nothing.
574 // Cleanup post-comment: strip separators and whitespace.
575 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
576 let post_snippet = post_snippet[..comment_end].trim();
578 let post_snippet_trimmed = if post_snippet.starts_with(',') {
579 post_snippet[1..].trim_matches(white_space)
580 } else if post_snippet.ends_with(',') {
581 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
586 let post_comment = if !post_snippet_trimmed.is_empty() {
587 Some(post_snippet_trimmed.to_owned())
593 pre_comment: pre_comment,
594 pre_comment_style: pre_comment_style,
595 item: (self.get_item_string)(&item),
596 post_comment: post_comment,
597 new_lines: new_lines,
603 // Creates an iterator over a list's items with associated comments.
604 pub fn itemize_list<'a, T, I, F1, F2, F3>(
605 codemap: &'a CodeMap,
611 prev_span_end: BytePos,
612 next_span_start: BytePos,
613 ) -> ListItems<'a, I, F1, F2, F3>
615 I: Iterator<Item = T>,
616 F1: Fn(&T) -> BytePos,
617 F2: Fn(&T) -> BytePos,
618 F3: Fn(&T) -> Option<String>,
622 inner: inner.peekable(),
625 get_item_string: get_item_string,
626 prev_span_end: prev_span_end,
627 next_span_start: next_span_start,
628 terminator: terminator,
632 fn needs_trailing_separator(
633 separator_tactic: SeparatorTactic,
634 list_tactic: DefinitiveListTactic,
636 match separator_tactic {
637 SeparatorTactic::Always => true,
638 SeparatorTactic::Vertical => list_tactic == DefinitiveListTactic::Vertical,
639 SeparatorTactic::Never => false,
643 /// Returns the count and total width of the list items.
644 fn calculate_width<I, T>(items: I) -> (usize, usize)
646 I: IntoIterator<Item = T>,
651 .map(|item| total_item_width(item.as_ref()))
652 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
655 fn total_item_width(item: &ListItem) -> usize {
656 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..])) +
657 comment_len(item.post_comment.as_ref().map(|x| &(*x)[..])) +
658 item.item.as_ref().map_or(0, |str| str.len())
661 fn comment_len(comment: Option<&str>) -> usize {
664 let text_len = s.trim().len();
666 // We'll put " /*" before and " */" after inline comments.
676 // Compute horizontal and vertical shapes for a struct-lit-like thing.
677 pub fn struct_lit_shape(
679 context: &RewriteContext,
682 ) -> Option<(Option<Shape>, Shape)> {
683 let v_shape = match context.config.struct_lit_style() {
684 IndentStyle::Visual => try_opt!(
685 try_opt!(shape.visual_indent(0).shrink_left(prefix_width)).sub_width(suffix_width)
687 IndentStyle::Block => {
688 let shape = shape.block_indent(context.config.tab_spaces());
690 width: try_opt!(context.config.max_width().checked_sub(shape.indent.width())),
695 let shape_width = shape.width.checked_sub(prefix_width + suffix_width);
696 if let Some(w) = shape_width {
697 let shape_width = cmp::min(w, context.config.struct_lit_width());
698 Some((Some(Shape::legacy(shape_width, shape.indent)), v_shape))
700 Some((None, v_shape))
704 // Compute the tactic for the internals of a struct-lit-like thing.
705 pub fn struct_lit_tactic(
706 h_shape: Option<Shape>,
707 context: &RewriteContext,
709 ) -> DefinitiveListTactic {
710 if let Some(h_shape) = h_shape {
711 let prelim_tactic = match (context.config.struct_lit_style(), items.len()) {
712 (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
713 _ => context.config.struct_lit_multiline_style().to_list_tactic(),
715 definitive_tactic(items, prelim_tactic, Separator::Comma, h_shape.width)
717 DefinitiveListTactic::Vertical
721 // Given a tactic and possible shapes for horizontal and vertical layout,
722 // come up with the actual shape to use.
723 pub fn shape_for_tactic(
724 tactic: DefinitiveListTactic,
725 h_shape: Option<Shape>,
729 DefinitiveListTactic::Horizontal => h_shape.unwrap(),
734 // Create a ListFormatting object for formatting the internals of a
735 // struct-lit-like thing, that is a series of fields.
736 pub fn struct_lit_formatting<'a>(
738 tactic: DefinitiveListTactic,
739 context: &'a RewriteContext,
740 force_no_trailing_comma: bool,
741 ) -> ListFormatting<'a> {
742 let ends_with_newline = context.config.struct_lit_style() != IndentStyle::Visual &&
743 tactic == DefinitiveListTactic::Vertical;
747 trailing_separator: if force_no_trailing_comma {
748 SeparatorTactic::Never
750 context.config.trailing_comma()
753 ends_with_newline: ends_with_newline,
754 preserve_newline: true,
755 config: context.config,