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>
72 where I: Iterator<Item = ListItem>
77 ListTactic::LimitedHorizontalVertical(config.fn_call_width()))
80 pub fn format_item_list<I>(items: I, shape: Shape, config: &Config) -> Option<String>
81 where I: Iterator<Item = ListItem>
83 list_helper(items, shape, config, ListTactic::HorizontalVertical)
86 pub fn list_helper<I>(items: I, shape: Shape, config: &Config, tactic: ListTactic) -> Option<String>
87 where I: Iterator<Item = ListItem>
89 let item_vec: Vec<_> = items.collect();
90 let tactic = definitive_tactic(&item_vec, tactic, shape.width);
91 let fmt = ListFormatting {
94 trailing_separator: SeparatorTactic::Never,
96 ends_with_newline: false,
100 write_list(&item_vec, &fmt)
103 impl AsRef<ListItem> for ListItem {
104 fn as_ref(&self) -> &ListItem {
109 pub struct ListItem {
110 // None for comments mean that they are not present.
111 pub pre_comment: Option<String>,
112 // Item should include attributes and doc comments. None indicates a failed
114 pub item: Option<String>,
115 pub post_comment: Option<String>,
116 // Whether there is extra whitespace before this item.
121 pub fn is_multiline(&self) -> bool {
122 self.item.as_ref().map_or(false, |s| s.contains('\n')) || self.pre_comment.is_some() ||
125 .map_or(false, |s| s.contains('\n'))
128 pub fn has_line_pre_comment(&self) -> bool {
131 .map_or(false, |comment| comment.starts_with("//"))
134 pub fn from_str<S: Into<String>>(s: S) -> ListItem {
137 item: Some(s.into()),
144 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
145 /// The definitive formatting tactic for lists.
146 pub enum DefinitiveListTactic {
152 pub fn definitive_tactic<I, T>(items: I, tactic: ListTactic, width: usize) -> DefinitiveListTactic
153 where I: IntoIterator<Item = T> + Clone,
156 let pre_line_comments = items
159 .any(|item| item.as_ref().has_line_pre_comment());
161 let limit = match tactic {
162 _ if pre_line_comments => return DefinitiveListTactic::Vertical,
163 ListTactic::Mixed => return DefinitiveListTactic::Mixed,
164 ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
165 ListTactic::Vertical => return DefinitiveListTactic::Vertical,
166 ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
167 ListTactic::HorizontalVertical => width,
170 let (sep_count, total_width) = calculate_width(items.clone());
171 let sep_len = ", ".len(); // FIXME: make more generic?
172 let total_sep_len = sep_len * sep_count.checked_sub(1).unwrap_or(0);
173 let real_total = total_width + total_sep_len;
175 if real_total <= limit && !pre_line_comments &&
176 !items.into_iter().any(|item| item.as_ref().is_multiline()) {
177 DefinitiveListTactic::Horizontal
179 DefinitiveListTactic::Vertical
183 // Format a list of commented items into a string.
184 // TODO: add unit tests
185 pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
186 where I: IntoIterator<Item = T>,
189 let tactic = formatting.tactic;
190 let sep_len = formatting.separator.len();
192 // Now that we know how we will layout, we can decide for sure if there
193 // will be a trailing separator.
194 let trailing_separator = needs_trailing_separator(formatting.trailing_separator, tactic);
195 let mut result = String::new();
196 let mut iter = items.into_iter().enumerate().peekable();
198 let mut line_len = 0;
199 let indent_str = &formatting.shape.indent.to_string(formatting.config);
200 while let Some((i, item)) = iter.next() {
201 let item = item.as_ref();
202 let inner_item = try_opt!(item.item.as_ref());
204 let last = iter.peek().is_none();
205 let separate = !last || trailing_separator;
206 let item_sep_len = if separate { sep_len } else { 0 };
208 // Item string may be multi-line. Its length (used for block comment alignment)
209 // should be only the length of the last line.
210 let item_last_line = if item.is_multiline() {
211 inner_item.lines().last().unwrap_or("")
215 let mut item_last_line_width = item_last_line.len() + item_sep_len;
216 if item_last_line.starts_with(indent_str) {
217 item_last_line_width -= indent_str.len();
221 DefinitiveListTactic::Horizontal if !first => {
224 DefinitiveListTactic::Vertical if !first => {
226 result.push_str(indent_str);
228 DefinitiveListTactic::Mixed => {
229 let total_width = total_item_width(item) + item_sep_len;
231 // 1 is space between separator and item.
232 if line_len > 0 && line_len + 1 + total_width > formatting.shape.width {
234 result.push_str(indent_str);
243 line_len += total_width;
249 if let Some(ref comment) = item.pre_comment {
250 // Block style in non-vertical mode.
251 let block_mode = tactic != DefinitiveListTactic::Vertical;
252 // Width restriction is only relevant in vertical mode.
254 try_opt!(rewrite_comment(comment, block_mode, formatting.shape, formatting.config));
255 result.push_str(&comment);
257 if tactic == DefinitiveListTactic::Vertical {
259 result.push_str(indent_str);
265 result.push_str(&inner_item[..]);
268 if tactic != DefinitiveListTactic::Vertical && item.post_comment.is_some() {
269 let comment = item.post_comment.as_ref().unwrap();
270 let formatted_comment =
271 try_opt!(rewrite_comment(comment,
273 Shape::legacy(formatting.shape.width, Indent::empty()),
277 result.push_str(&formatted_comment);
281 result.push_str(formatting.separator);
284 if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
285 // 1 = space between item and comment.
286 let width = formatting
289 .checked_sub(item_last_line_width + 1)
291 let mut offset = formatting.shape.indent;
292 offset.alignment += item_last_line_width + 1;
293 let comment = item.post_comment.as_ref().unwrap();
295 debug!("Width = {}, offset = {:?}", width, offset);
296 // Use block-style only for the last item or multiline comments.
297 let block_style = !formatting.ends_with_newline && last ||
298 comment.trim().contains('\n') ||
299 comment.trim().len() > width;
301 let formatted_comment = try_opt!(rewrite_comment(comment,
303 Shape::legacy(width, offset),
306 if !formatted_comment.starts_with('\n') {
309 result.push_str(&formatted_comment);
312 if !last && tactic == DefinitiveListTactic::Vertical && item.new_lines {
320 pub struct ListItems<'a, I, F1, F2, F3>
323 codemap: &'a CodeMap,
328 prev_span_end: BytePos,
329 next_span_start: BytePos,
333 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
334 where I: Iterator<Item = T>,
335 F1: Fn(&T) -> BytePos,
336 F2: Fn(&T) -> BytePos,
337 F3: Fn(&T) -> Option<String>
339 type Item = ListItem;
341 fn next(&mut self) -> Option<Self::Item> {
342 let white_space: &[_] = &[' ', '\t'];
344 self.inner.next().map(|item| {
345 let mut new_lines = false;
347 let pre_snippet = self.codemap
348 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
350 let trimmed_pre_snippet = pre_snippet.trim();
351 let has_pre_comment = trimmed_pre_snippet.contains("//") ||
352 trimmed_pre_snippet.contains("/*");
353 let pre_comment = if has_pre_comment {
354 Some(trimmed_pre_snippet.to_owned())
360 let next_start = match self.inner.peek() {
361 Some(next_item) => (self.get_lo)(next_item),
362 None => self.next_span_start,
364 let post_snippet = self.codemap
365 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
368 let comment_end = match self.inner.peek() {
370 let mut block_open_index = post_snippet.find("/*");
371 // check if it realy is a block comment (and not //*)
372 if let Some(i) = block_open_index {
373 if i > 0 && &post_snippet[i - 1..i] == "/" {
374 block_open_index = None;
377 let newline_index = post_snippet.find('\n');
378 let separator_index = post_snippet.find_uncommented(",").unwrap();
380 match (block_open_index, newline_index) {
381 // Separator before comment, with the next item on same line.
382 // Comment belongs to next item.
383 (Some(i), None) if i > separator_index => separator_index + 1,
384 // Block-style post-comment before the separator.
386 cmp::max(find_comment_end(&post_snippet[i..]).unwrap() + i,
389 // Block-style post-comment. Either before or after the separator.
390 (Some(i), Some(j)) if i < j => {
391 cmp::max(find_comment_end(&post_snippet[i..]).unwrap() + i,
394 // Potential *single* line comment.
395 (_, Some(j)) if j > separator_index => j + 1,
396 _ => post_snippet.len(),
401 .find_uncommented(self.terminator)
402 .unwrap_or(post_snippet.len())
406 if !post_snippet.is_empty() && comment_end > 0 {
407 // Account for extra whitespace between items. This is fiddly
408 // because of the way we divide pre- and post- comments.
410 // Everything from the separator to the next item.
411 let test_snippet = &post_snippet[comment_end - 1..];
412 let first_newline = test_snippet.find('\n').unwrap_or(test_snippet.len());
413 // From the end of the first line of comments.
414 let test_snippet = &test_snippet[first_newline..];
415 let first = test_snippet
416 .find(|c: char| !c.is_whitespace())
417 .unwrap_or(test_snippet.len());
418 // From the end of the first line of comments to the next non-whitespace char.
419 let test_snippet = &test_snippet[..first];
421 if test_snippet.chars().filter(|c| c == &'\n').count() > 1 {
422 // There were multiple line breaks which got trimmed to nothing.
427 // Cleanup post-comment: strip separators and whitespace.
428 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
429 let post_snippet = post_snippet[..comment_end].trim();
431 let post_snippet_trimmed = if post_snippet.starts_with(',') {
432 post_snippet[1..].trim_matches(white_space)
433 } else if post_snippet.ends_with(',') {
434 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
439 let post_comment = if !post_snippet_trimmed.is_empty() {
440 Some(post_snippet_trimmed.to_owned())
446 pre_comment: pre_comment,
447 item: (self.get_item_string)(&item),
448 post_comment: post_comment,
449 new_lines: new_lines,
455 // Creates an iterator over a list's items with associated comments.
456 pub fn itemize_list<'a, T, I, F1, F2, F3>(codemap: &'a CodeMap,
462 prev_span_end: BytePos,
463 next_span_start: BytePos)
464 -> ListItems<'a, I, F1, F2, F3>
465 where I: Iterator<Item = T>,
466 F1: Fn(&T) -> BytePos,
467 F2: Fn(&T) -> BytePos,
468 F3: Fn(&T) -> Option<String>
472 inner: inner.peekable(),
475 get_item_string: get_item_string,
476 prev_span_end: prev_span_end,
477 next_span_start: next_span_start,
478 terminator: terminator,
482 fn needs_trailing_separator(separator_tactic: SeparatorTactic,
483 list_tactic: DefinitiveListTactic)
485 match separator_tactic {
486 SeparatorTactic::Always => true,
487 SeparatorTactic::Vertical => list_tactic == DefinitiveListTactic::Vertical,
488 SeparatorTactic::Never => false,
492 /// Returns the count and total width of the list items.
493 fn calculate_width<I, T>(items: I) -> (usize, usize)
494 where I: IntoIterator<Item = T>,
499 .map(|item| total_item_width(item.as_ref()))
500 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
503 fn total_item_width(item: &ListItem) -> usize {
504 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..])) +
505 comment_len(item.post_comment.as_ref().map(|x| &(*x)[..])) +
506 item.item.as_ref().map_or(0, |str| str.len())
509 fn comment_len(comment: Option<&str>) -> usize {
512 let text_len = s.trim().len();
514 // We'll put " /*" before and " */" after inline comments.
524 // Compute horizontal and vertical shapes for a struct-lit-like thing.
525 pub fn struct_lit_shape(shape: Shape,
526 context: &RewriteContext,
529 -> Option<(Option<Shape>, Shape)> {
530 let v_shape = match context.config.struct_lit_style() {
531 IndentStyle::Visual => {
532 try_opt!(try_opt!(shape.shrink_left(prefix_width)).sub_width(suffix_width))
534 IndentStyle::Block => {
535 let shape = shape.block_indent(context.config.tab_spaces());
537 width: try_opt!(context.config.max_width().checked_sub(shape.indent.width())),
542 let h_shape = shape.sub_width(prefix_width + suffix_width);
543 Some((h_shape, v_shape))
546 // Compute the tactic for the internals of a struct-lit-like thing.
547 pub fn struct_lit_tactic(h_shape: Option<Shape>,
548 context: &RewriteContext,
550 -> DefinitiveListTactic {
551 if let Some(h_shape) = h_shape {
552 let mut prelim_tactic = match (context.config.struct_lit_style(), items.len()) {
553 (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
554 _ => context.config.struct_lit_multiline_style().to_list_tactic(),
557 if prelim_tactic == ListTactic::HorizontalVertical && items.len() > 1 {
559 ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width());
562 definitive_tactic(items, prelim_tactic, h_shape.width)
564 DefinitiveListTactic::Vertical
568 // Given a tactic and possible shapes for horizontal and vertical layout,
569 // come up with the actual shape to use.
570 pub fn shape_for_tactic(tactic: DefinitiveListTactic,
571 h_shape: Option<Shape>,
575 DefinitiveListTactic::Horizontal => h_shape.unwrap(),
580 // Create a ListFormatting object for formatting the internals of a
581 // struct-lit-like thing, that is a series of fields.
582 pub fn struct_lit_formatting<'a>(shape: Shape,
583 tactic: DefinitiveListTactic,
584 context: &'a RewriteContext,
585 force_no_trailing_comma: bool)
586 -> ListFormatting<'a> {
587 let ends_with_newline = context.config.struct_lit_style() != IndentStyle::Visual &&
588 tactic == DefinitiveListTactic::Vertical;
592 trailing_separator: if force_no_trailing_comma {
593 SeparatorTactic::Never
595 context.config.trailing_comma()
598 ends_with_newline: ends_with_newline,
599 config: context.config,