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::{CodeMap, BytePos};
17 use comment::{FindUncommented, rewrite_comment, find_comment_end};
18 use config::{Config, IndentStyle};
19 use rewrite::RewriteContext;
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 pub config: &'a Config,
71 pub fn format_fn_args<I>(items: I, shape: Shape, config: &Config) -> Option<String>
73 I: Iterator<Item = ListItem>,
79 ListTactic::LimitedHorizontalVertical(config.fn_call_width()),
83 pub fn format_item_list<I>(items: I, shape: Shape, config: &Config) -> Option<String>
85 I: Iterator<Item = ListItem>,
87 list_helper(items, shape, config, ListTactic::HorizontalVertical)
90 pub fn list_helper<I>(items: I, shape: Shape, config: &Config, tactic: ListTactic) -> Option<String>
92 I: Iterator<Item = ListItem>,
94 let item_vec: Vec<_> = items.collect();
95 let tactic = definitive_tactic(&item_vec, tactic, shape.width);
96 let fmt = ListFormatting {
99 trailing_separator: SeparatorTactic::Never,
101 ends_with_newline: false,
105 write_list(&item_vec, &fmt)
108 impl AsRef<ListItem> for ListItem {
109 fn as_ref(&self) -> &ListItem {
114 pub struct ListItem {
115 // None for comments mean that they are not present.
116 pub pre_comment: Option<String>,
117 // Item should include attributes and doc comments. None indicates a failed
119 pub item: Option<String>,
120 pub post_comment: Option<String>,
121 // Whether there is extra whitespace before this item.
126 pub fn is_multiline(&self) -> bool {
127 self.item.as_ref().map_or(false, |s| s.contains('\n')) || self.pre_comment.is_some() ||
128 self.post_comment.as_ref().map_or(
130 |s| s.contains('\n'),
134 pub fn has_line_pre_comment(&self) -> bool {
137 .map_or(false, |comment| comment.starts_with("//"))
140 pub fn from_str<S: Into<String>>(s: S) -> ListItem {
143 item: Some(s.into()),
150 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
151 /// The definitive formatting tactic for lists.
152 pub enum DefinitiveListTactic {
158 pub fn definitive_tactic<I, T>(items: I, tactic: ListTactic, width: usize) -> DefinitiveListTactic
160 I: IntoIterator<Item = T> + Clone,
163 let pre_line_comments = items
166 .any(|item| item.as_ref().has_line_pre_comment());
168 let limit = match tactic {
169 _ if pre_line_comments => return DefinitiveListTactic::Vertical,
170 ListTactic::Mixed => return DefinitiveListTactic::Mixed,
171 ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
172 ListTactic::Vertical => return DefinitiveListTactic::Vertical,
173 ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
174 ListTactic::HorizontalVertical => width,
177 let (sep_count, total_width) = calculate_width(items.clone());
178 let sep_len = ", ".len(); // FIXME: make more generic?
179 let total_sep_len = sep_len * sep_count.checked_sub(1).unwrap_or(0);
180 let real_total = total_width + total_sep_len;
182 if real_total <= limit && !pre_line_comments &&
183 !items.into_iter().any(|item| item.as_ref().is_multiline())
185 DefinitiveListTactic::Horizontal
187 DefinitiveListTactic::Vertical
191 // Format a list of commented items into a string.
192 // TODO: add unit tests
193 pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
195 I: IntoIterator<Item = T>,
198 let tactic = formatting.tactic;
199 let sep_len = formatting.separator.len();
201 // Now that we know how we will layout, we can decide for sure if there
202 // will be a trailing separator.
203 let trailing_separator = needs_trailing_separator(formatting.trailing_separator, tactic);
204 let mut result = String::new();
205 let mut iter = items.into_iter().enumerate().peekable();
207 let mut line_len = 0;
208 let indent_str = &formatting.shape.indent.to_string(formatting.config);
209 while let Some((i, item)) = iter.next() {
210 let item = item.as_ref();
211 let inner_item = try_opt!(item.item.as_ref());
213 let last = iter.peek().is_none();
214 let separate = !last || trailing_separator;
215 let item_sep_len = if separate { sep_len } else { 0 };
217 // Item string may be multi-line. Its length (used for block comment alignment)
218 // should be only the length of the last line.
219 let item_last_line = if item.is_multiline() {
220 inner_item.lines().last().unwrap_or("")
224 let mut item_last_line_width = item_last_line.len() + item_sep_len;
225 if item_last_line.starts_with(indent_str) {
226 item_last_line_width -= indent_str.len();
230 DefinitiveListTactic::Horizontal if !first => {
233 DefinitiveListTactic::Vertical if !first => {
235 result.push_str(indent_str);
237 DefinitiveListTactic::Mixed => {
238 let total_width = total_item_width(item) + item_sep_len;
240 // 1 is space between separator and item.
241 if line_len > 0 && line_len + 1 + total_width > formatting.shape.width {
243 result.push_str(indent_str);
252 line_len += total_width;
258 if let Some(ref comment) = item.pre_comment {
259 // Block style in non-vertical mode.
260 let block_mode = tactic != DefinitiveListTactic::Vertical;
261 // Width restriction is only relevant in vertical mode.
262 let comment = try_opt!(rewrite_comment(
268 result.push_str(&comment);
270 if tactic == DefinitiveListTactic::Vertical {
272 result.push_str(indent_str);
278 result.push_str(&inner_item[..]);
281 if tactic != DefinitiveListTactic::Vertical && item.post_comment.is_some() {
282 let comment = item.post_comment.as_ref().unwrap();
283 let formatted_comment = try_opt!(rewrite_comment(
286 Shape::legacy(formatting.shape.width, Indent::empty()),
291 result.push_str(&formatted_comment);
295 result.push_str(formatting.separator);
298 if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
299 // 1 = space between item and comment.
300 let width = formatting
303 .checked_sub(item_last_line_width + 1)
305 let mut offset = formatting.shape.indent;
306 offset.alignment += item_last_line_width + 1;
307 let comment = item.post_comment.as_ref().unwrap();
309 debug!("Width = {}, offset = {:?}", width, offset);
310 // Use block-style only for the last item or multiline comments.
311 let block_style = !formatting.ends_with_newline && last ||
312 comment.trim().contains('\n') ||
313 comment.trim().len() > width;
315 let formatted_comment = try_opt!(rewrite_comment(
318 Shape::legacy(width, offset),
322 if !formatted_comment.starts_with('\n') {
325 result.push_str(&formatted_comment);
328 if !last && tactic == DefinitiveListTactic::Vertical && item.new_lines {
336 pub struct ListItems<'a, I, F1, F2, F3>
340 codemap: &'a CodeMap,
345 prev_span_end: BytePos,
346 next_span_start: BytePos,
350 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
352 I: Iterator<Item = T>,
353 F1: Fn(&T) -> BytePos,
354 F2: Fn(&T) -> BytePos,
355 F3: Fn(&T) -> Option<String>,
357 type Item = ListItem;
359 fn next(&mut self) -> Option<Self::Item> {
360 let white_space: &[_] = &[' ', '\t'];
362 self.inner.next().map(|item| {
363 let mut new_lines = false;
365 let pre_snippet = self.codemap
366 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
368 let trimmed_pre_snippet = pre_snippet.trim();
369 let has_pre_comment = trimmed_pre_snippet.contains("//") ||
370 trimmed_pre_snippet.contains("/*");
371 let pre_comment = if has_pre_comment {
372 Some(trimmed_pre_snippet.to_owned())
378 let next_start = match self.inner.peek() {
379 Some(next_item) => (self.get_lo)(next_item),
380 None => self.next_span_start,
382 let post_snippet = self.codemap
383 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
386 let comment_end = match self.inner.peek() {
388 let mut block_open_index = post_snippet.find("/*");
389 // check if it realy is a block comment (and not //*)
390 if let Some(i) = block_open_index {
391 if i > 0 && &post_snippet[i - 1..i] == "/" {
392 block_open_index = None;
395 let newline_index = post_snippet.find('\n');
396 let separator_index = post_snippet.find_uncommented(",").unwrap();
398 match (block_open_index, newline_index) {
399 // Separator before comment, with the next item on same line.
400 // Comment belongs to next item.
401 (Some(i), None) if i > separator_index => separator_index + 1,
402 // Block-style post-comment before the separator.
405 find_comment_end(&post_snippet[i..]).unwrap() + i,
409 // Block-style post-comment. Either before or after the separator.
410 (Some(i), Some(j)) if i < j => {
412 find_comment_end(&post_snippet[i..]).unwrap() + i,
416 // Potential *single* line comment.
417 (_, Some(j)) if j > separator_index => j + 1,
418 _ => post_snippet.len(),
422 post_snippet.find_uncommented(self.terminator).unwrap_or(
429 if !post_snippet.is_empty() && comment_end > 0 {
430 // Account for extra whitespace between items. This is fiddly
431 // because of the way we divide pre- and post- comments.
433 // Everything from the separator to the next item.
434 let test_snippet = &post_snippet[comment_end - 1..];
435 let first_newline = test_snippet.find('\n').unwrap_or(test_snippet.len());
436 // From the end of the first line of comments.
437 let test_snippet = &test_snippet[first_newline..];
438 let first = test_snippet.find(|c: char| !c.is_whitespace()).unwrap_or(
442 // From the end of the first line of comments to the next non-whitespace char.
443 let test_snippet = &test_snippet[..first];
445 if test_snippet.chars().filter(|c| c == &'\n').count() > 1 {
446 // There were multiple line breaks which got trimmed to nothing.
451 // Cleanup post-comment: strip separators and whitespace.
452 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
453 let post_snippet = post_snippet[..comment_end].trim();
455 let post_snippet_trimmed = if post_snippet.starts_with(',') {
456 post_snippet[1..].trim_matches(white_space)
457 } else if post_snippet.ends_with(',') {
458 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
463 let post_comment = if !post_snippet_trimmed.is_empty() {
464 Some(post_snippet_trimmed.to_owned())
470 pre_comment: pre_comment,
471 item: (self.get_item_string)(&item),
472 post_comment: post_comment,
473 new_lines: new_lines,
479 // Creates an iterator over a list's items with associated comments.
480 pub fn itemize_list<'a, T, I, F1, F2, F3>(
481 codemap: &'a CodeMap,
487 prev_span_end: BytePos,
488 next_span_start: BytePos,
489 ) -> ListItems<'a, I, F1, F2, F3>
491 I: Iterator<Item = T>,
492 F1: Fn(&T) -> BytePos,
493 F2: Fn(&T) -> BytePos,
494 F3: Fn(&T) -> Option<String>,
498 inner: inner.peekable(),
501 get_item_string: get_item_string,
502 prev_span_end: prev_span_end,
503 next_span_start: next_span_start,
504 terminator: terminator,
508 fn needs_trailing_separator(
509 separator_tactic: SeparatorTactic,
510 list_tactic: DefinitiveListTactic,
512 match separator_tactic {
513 SeparatorTactic::Always => true,
514 SeparatorTactic::Vertical => list_tactic == DefinitiveListTactic::Vertical,
515 SeparatorTactic::Never => false,
519 /// Returns the count and total width of the list items.
520 fn calculate_width<I, T>(items: I) -> (usize, usize)
522 I: IntoIterator<Item = T>,
527 .map(|item| total_item_width(item.as_ref()))
528 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
531 fn total_item_width(item: &ListItem) -> usize {
532 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..])) +
533 comment_len(item.post_comment.as_ref().map(|x| &(*x)[..])) +
534 item.item.as_ref().map_or(0, |str| str.len())
537 fn comment_len(comment: Option<&str>) -> usize {
540 let text_len = s.trim().len();
542 // We'll put " /*" before and " */" after inline comments.
552 // Compute horizontal and vertical shapes for a struct-lit-like thing.
553 pub fn struct_lit_shape(
555 context: &RewriteContext,
558 ) -> Option<(Option<Shape>, Shape)> {
559 let v_shape = match context.config.struct_lit_style() {
560 IndentStyle::Visual => {
562 try_opt!(shape.visual_indent(0).shrink_left(prefix_width)).sub_width(suffix_width)
565 IndentStyle::Block => {
566 let shape = shape.block_indent(context.config.tab_spaces());
568 width: try_opt!(context.config.max_width().checked_sub(shape.indent.width())),
573 let h_shape = shape.sub_width(prefix_width + suffix_width);
574 Some((h_shape, v_shape))
577 // Compute the tactic for the internals of a struct-lit-like thing.
578 pub fn struct_lit_tactic(
579 h_shape: Option<Shape>,
580 context: &RewriteContext,
582 ) -> DefinitiveListTactic {
583 if let Some(h_shape) = h_shape {
584 let mut prelim_tactic = match (context.config.struct_lit_style(), items.len()) {
585 (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
586 _ => context.config.struct_lit_multiline_style().to_list_tactic(),
589 if prelim_tactic == ListTactic::HorizontalVertical && items.len() > 1 {
591 ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width());
594 definitive_tactic(items, prelim_tactic, h_shape.width)
596 DefinitiveListTactic::Vertical
600 // Given a tactic and possible shapes for horizontal and vertical layout,
601 // come up with the actual shape to use.
602 pub fn shape_for_tactic(
603 tactic: DefinitiveListTactic,
604 h_shape: Option<Shape>,
608 DefinitiveListTactic::Horizontal => h_shape.unwrap(),
613 // Create a ListFormatting object for formatting the internals of a
614 // struct-lit-like thing, that is a series of fields.
615 pub fn struct_lit_formatting<'a>(
617 tactic: DefinitiveListTactic,
618 context: &'a RewriteContext,
619 force_no_trailing_comma: bool,
620 ) -> ListFormatting<'a> {
621 let ends_with_newline = context.config.struct_lit_style() != IndentStyle::Visual &&
622 tactic == DefinitiveListTactic::Vertical;
626 trailing_separator: if force_no_trailing_comma {
627 SeparatorTactic::Never
629 context.config.trailing_comma()
632 ends_with_newline: ends_with_newline,
633 config: context.config,