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::{self, CodeMap, BytePos};
18 use comment::{FindUncommented, rewrite_comment, find_comment_end};
21 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
22 /// Formatting tactic for lists. This will be cast down to a
23 /// DefinitiveListTactic depending on the number and length of the items and
28 // All items on one row.
30 // Try Horizontal layout, if that fails then vertical.
32 // HorizontalVertical with a soft limit of n characters.
33 LimitedHorizontalVertical(usize),
34 // Pack as many items as possible per row over (possibly) many rows.
38 impl_enum_decodable!(ListTactic, Vertical, Horizontal, HorizontalVertical, Mixed);
40 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
41 pub enum SeparatorTactic {
47 impl_enum_decodable!(SeparatorTactic, Always, Never, Vertical);
49 pub struct ListFormatting<'a> {
50 pub tactic: DefinitiveListTactic,
51 pub separator: &'a str,
52 pub trailing_separator: SeparatorTactic,
55 // Non-expressions, e.g. items, will have a new line at the end of the list.
56 // Important for comment styles.
57 pub ends_with_newline: bool,
58 pub config: &'a Config,
61 pub fn format_fn_args<I>(items: I, width: usize, offset: Indent, config: &Config) -> Option<String>
62 where I: Iterator<Item = ListItem>
68 ListTactic::LimitedHorizontalVertical(config.fn_call_width))
71 pub fn format_item_list<I>(items: I,
76 where I: Iterator<Item = ListItem>
78 list_helper(items, width, offset, config, ListTactic::HorizontalVertical)
81 fn list_helper<I>(items: I,
87 where I: Iterator<Item = ListItem>
89 let item_vec: Vec<_> = items.collect();
90 let tactic = definitive_tactic(&item_vec, tactic, width);
91 let fmt = ListFormatting {
94 trailing_separator: SeparatorTactic::Never,
97 ends_with_newline: false,
101 write_list(&item_vec, &fmt)
104 impl AsRef<ListItem> for ListItem {
105 fn as_ref(&self) -> &ListItem {
110 pub struct ListItem {
111 // None for comments mean that they are not present.
112 pub pre_comment: Option<String>,
113 // Item should include attributes and doc comments. None indicates a failed
115 pub item: Option<String>,
116 pub post_comment: Option<String>,
117 // Whether there is extra whitespace before this item.
122 pub fn is_multiline(&self) -> bool {
123 self.item.as_ref().map(|s| s.contains('\n')).unwrap_or(false) ||
124 self.pre_comment.is_some() ||
125 self.post_comment.as_ref().map(|s| s.contains('\n')).unwrap_or(false)
128 pub fn has_line_pre_comment(&self) -> bool {
129 self.pre_comment.as_ref().map_or(false, |comment| comment.starts_with("//"))
132 pub fn from_str<S: Into<String>>(s: S) -> ListItem {
135 item: Some(s.into()),
142 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
143 /// The definitive formatting tactic for lists.
144 pub enum DefinitiveListTactic {
150 pub fn definitive_tactic<'t, I, T>(items: I,
153 -> DefinitiveListTactic
154 where I: IntoIterator<Item = T> + Clone,
157 let pre_line_comments = items.clone()
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<'b, I, T>(items: I, formatting: &ListFormatting<'b>) -> 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.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 {
211 let item_width = inner_item.len() + item_sep_len;
214 DefinitiveListTactic::Horizontal if !first => {
217 DefinitiveListTactic::Vertical if !first => {
219 result.push_str(indent_str);
221 DefinitiveListTactic::Mixed => {
222 let total_width = total_item_width(item) + item_sep_len;
224 if line_len > 0 && line_len + total_width > formatting.width {
226 result.push_str(indent_str);
235 line_len += total_width;
241 if let Some(ref comment) = item.pre_comment {
242 // Block style in non-vertical mode.
243 let block_mode = tactic != DefinitiveListTactic::Vertical;
244 // Width restriction is only relevant in vertical mode.
245 let max_width = formatting.width;
246 let comment = try_opt!(rewrite_comment(comment,
251 result.push_str(&comment);
253 if tactic == DefinitiveListTactic::Vertical {
255 result.push_str(indent_str);
261 // Make sure that string actually fits.
262 let item_str = try_opt!(wrap_str(&inner_item[..],
263 formatting.config.max_width,
266 result.push_str(&item_str);
269 if tactic != DefinitiveListTactic::Vertical && item.post_comment.is_some() {
270 let comment = item.post_comment.as_ref().unwrap();
271 let formatted_comment = try_opt!(rewrite_comment(comment,
278 result.push_str(&formatted_comment);
282 result.push_str(formatting.separator);
285 if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
286 // 1 = space between item and comment.
287 let width = formatting.width.checked_sub(item_width + 1).unwrap_or(1);
288 let mut offset = formatting.indent;
289 offset.alignment += item_width + 1;
290 let comment = item.post_comment.as_ref().unwrap();
291 // Use block-style only for the last item or multiline comments.
292 let block_style = !formatting.ends_with_newline && last ||
293 comment.trim().contains('\n') ||
294 comment.trim().len() > width;
296 let formatted_comment = try_opt!(rewrite_comment(comment,
303 result.push_str(&formatted_comment);
306 if !last && tactic == DefinitiveListTactic::Vertical && item.new_lines {
314 pub struct ListItems<'a, I, F1, F2, F3>
317 codemap: &'a CodeMap,
322 prev_span_end: BytePos,
323 next_span_start: BytePos,
327 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
328 where I: Iterator<Item = T>,
329 F1: Fn(&T) -> BytePos,
330 F2: Fn(&T) -> BytePos,
331 F3: Fn(&T) -> Option<String>
333 type Item = ListItem;
335 fn next(&mut self) -> Option<Self::Item> {
336 let white_space: &[_] = &[' ', '\t'];
338 self.inner.next().map(|item| {
339 let mut new_lines = false;
341 let pre_snippet = self.codemap
342 .span_to_snippet(codemap::mk_sp(self.prev_span_end,
343 (self.get_lo)(&item)))
345 let trimmed_pre_snippet = pre_snippet.trim();
346 let pre_comment = if !trimmed_pre_snippet.is_empty() {
347 Some(trimmed_pre_snippet.to_owned())
353 let next_start = match self.inner.peek() {
354 Some(ref next_item) => (self.get_lo)(next_item),
355 None => self.next_span_start,
357 let post_snippet = self.codemap
358 .span_to_snippet(codemap::mk_sp((self.get_hi)(&item),
362 let comment_end = match self.inner.peek() {
364 let block_open_index = post_snippet.find("/*");
365 let newline_index = post_snippet.find('\n');
366 let separator_index = post_snippet.find_uncommented(",").unwrap();
368 match (block_open_index, newline_index) {
369 // Separator before comment, with the next item on same line.
370 // Comment belongs to next item.
371 (Some(i), None) if i > separator_index => {
374 // Block-style post-comment before the separator.
376 cmp::max(find_comment_end(&post_snippet[i..]).unwrap() + i,
379 // Block-style post-comment. Either before or after the separator.
380 (Some(i), Some(j)) if i < j => {
381 cmp::max(find_comment_end(&post_snippet[i..]).unwrap() + i,
384 // Potential *single* line comment.
385 (_, Some(j)) => j + 1,
386 _ => post_snippet.len(),
390 post_snippet.find_uncommented(self.terminator).unwrap_or(post_snippet.len())
394 if !post_snippet.is_empty() && comment_end > 0 {
395 // Account for extra whitespace between items. This is fiddly
396 // because of the way we divide pre- and post- comments.
398 // Everything from the separator to the next item.
399 let test_snippet = &post_snippet[comment_end - 1..];
400 let first_newline = test_snippet.find('\n').unwrap_or(test_snippet.len());
401 // From the end of the first line of comments.
402 let test_snippet = &test_snippet[first_newline..];
403 let first = test_snippet.find(|c: char| !c.is_whitespace())
404 .unwrap_or(test_snippet.len());
405 // From the end of the first line of comments to the next non-whitespace char.
406 let test_snippet = &test_snippet[..first];
408 if test_snippet.chars().filter(|c| c == &'\n').count() > 1 {
409 // There were multiple line breaks which got trimmed to nothing.
414 // Cleanup post-comment: strip separators and whitespace.
415 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
416 let post_snippet = post_snippet[..comment_end].trim();
418 let post_snippet_trimmed = if post_snippet.starts_with(',') {
419 post_snippet[1..].trim_matches(white_space)
420 } else if post_snippet.ends_with(",") {
421 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
426 let post_comment = if !post_snippet_trimmed.is_empty() {
427 Some(post_snippet_trimmed.to_owned())
433 pre_comment: pre_comment,
434 item: (self.get_item_string)(&item),
435 post_comment: post_comment,
436 new_lines: new_lines,
442 // Creates an iterator over a list's items with associated comments.
443 pub fn itemize_list<'a, T, I, F1, F2, F3>(codemap: &'a CodeMap,
449 prev_span_end: BytePos,
450 next_span_start: BytePos)
451 -> ListItems<'a, I, F1, F2, F3>
452 where I: Iterator<Item = T>,
453 F1: Fn(&T) -> BytePos,
454 F2: Fn(&T) -> BytePos,
455 F3: Fn(&T) -> Option<String>
459 inner: inner.peekable(),
462 get_item_string: get_item_string,
463 prev_span_end: prev_span_end,
464 next_span_start: next_span_start,
465 terminator: terminator,
469 fn needs_trailing_separator(separator_tactic: SeparatorTactic,
470 list_tactic: DefinitiveListTactic)
472 match separator_tactic {
473 SeparatorTactic::Always => true,
474 SeparatorTactic::Vertical => list_tactic == DefinitiveListTactic::Vertical,
475 SeparatorTactic::Never => false,
479 /// Returns the count and total width of the list items.
480 fn calculate_width<'li, I, T>(items: I) -> (usize, usize)
481 where I: IntoIterator<Item = T>,
485 .map(|item| total_item_width(item.as_ref()))
486 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
489 fn total_item_width(item: &ListItem) -> usize {
490 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..])) +
491 comment_len(item.post_comment.as_ref().map(|x| &(*x)[..])) +
492 item.item.as_ref().map(|str| str.len()).unwrap_or(0)
495 fn comment_len(comment: Option<&str>) -> usize {
498 let text_len = s.trim().len();
500 // We'll put " /*" before and " */" after inline comments.