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_item_list<I>(items: I, shape: Shape, config: &Config) -> Option<String>
73 I: Iterator<Item = ListItem>,
75 list_helper(items, shape, config, ListTactic::HorizontalVertical)
78 pub fn list_helper<I>(items: I, shape: Shape, config: &Config, tactic: ListTactic) -> Option<String>
80 I: Iterator<Item = ListItem>,
82 let item_vec: Vec<_> = items.collect();
83 let tactic = definitive_tactic(&item_vec, tactic, shape.width);
84 let fmt = ListFormatting {
87 trailing_separator: SeparatorTactic::Never,
89 ends_with_newline: false,
93 write_list(&item_vec, &fmt)
96 impl AsRef<ListItem> for ListItem {
97 fn as_ref(&self) -> &ListItem {
102 pub struct ListItem {
103 // None for comments mean that they are not present.
104 pub pre_comment: Option<String>,
105 // Item should include attributes and doc comments. None indicates a failed
107 pub item: Option<String>,
108 pub post_comment: Option<String>,
109 // Whether there is extra whitespace before this item.
114 pub fn is_multiline(&self) -> bool {
115 self.item.as_ref().map_or(false, |s| s.contains('\n')) || self.pre_comment.is_some() ||
118 .map_or(false, |s| s.contains('\n'))
121 pub fn has_line_pre_comment(&self) -> bool {
124 .map_or(false, |comment| comment.starts_with("//"))
127 pub fn from_str<S: Into<String>>(s: S) -> ListItem {
130 item: Some(s.into()),
137 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
138 /// The definitive formatting tactic for lists.
139 pub enum DefinitiveListTactic {
145 pub fn definitive_tactic<I, T>(items: I, tactic: ListTactic, width: usize) -> DefinitiveListTactic
147 I: IntoIterator<Item = T> + Clone,
150 let pre_line_comments = items
153 .any(|item| item.as_ref().has_line_pre_comment());
155 let limit = match tactic {
156 _ if pre_line_comments => return DefinitiveListTactic::Vertical,
157 ListTactic::Mixed => return DefinitiveListTactic::Mixed,
158 ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
159 ListTactic::Vertical => return DefinitiveListTactic::Vertical,
160 ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
161 ListTactic::HorizontalVertical => width,
164 let (sep_count, total_width) = calculate_width(items.clone());
165 let sep_len = ", ".len(); // FIXME: make more generic?
166 let total_sep_len = sep_len * sep_count.checked_sub(1).unwrap_or(0);
167 let real_total = total_width + total_sep_len;
169 if real_total <= limit && !pre_line_comments &&
170 !items.into_iter().any(|item| item.as_ref().is_multiline())
172 DefinitiveListTactic::Horizontal
174 DefinitiveListTactic::Vertical
178 // Format a list of commented items into a string.
179 // TODO: add unit tests
180 pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
182 I: IntoIterator<Item = T>,
185 let tactic = formatting.tactic;
186 let sep_len = formatting.separator.len();
188 // Now that we know how we will layout, we can decide for sure if there
189 // will be a trailing separator.
190 let trailing_separator = needs_trailing_separator(formatting.trailing_separator, tactic);
191 let mut result = String::new();
192 let mut iter = items.into_iter().enumerate().peekable();
194 let mut line_len = 0;
195 let indent_str = &formatting.shape.indent.to_string(formatting.config);
196 while let Some((i, item)) = iter.next() {
197 let item = item.as_ref();
198 let inner_item = try_opt!(item.item.as_ref());
200 let last = iter.peek().is_none();
201 let separate = !last || trailing_separator;
202 let item_sep_len = if separate { sep_len } else { 0 };
204 // Item string may be multi-line. Its length (used for block comment alignment)
205 // should be only the length of the last line.
206 let item_last_line = if item.is_multiline() {
207 inner_item.lines().last().unwrap_or("")
211 let mut item_last_line_width = item_last_line.len() + item_sep_len;
212 if item_last_line.starts_with(indent_str) {
213 item_last_line_width -= indent_str.len();
217 DefinitiveListTactic::Horizontal if !first => {
220 DefinitiveListTactic::Vertical if !first => {
222 result.push_str(indent_str);
224 DefinitiveListTactic::Mixed => {
225 let total_width = total_item_width(item) + item_sep_len;
227 // 1 is space between separator and item.
228 if line_len > 0 && line_len + 1 + total_width > formatting.shape.width {
230 result.push_str(indent_str);
239 line_len += total_width;
245 if let Some(ref comment) = item.pre_comment {
246 // Block style in non-vertical mode.
247 let block_mode = tactic != DefinitiveListTactic::Vertical;
248 // Width restriction is only relevant in vertical mode.
249 let comment = try_opt!(rewrite_comment(
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 = try_opt!(rewrite_comment(
273 Shape::legacy(formatting.shape.width, Indent::empty()),
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
290 .checked_sub(item_last_line_width + 1)
292 let mut offset = formatting.shape.indent;
293 offset.alignment += item_last_line_width + 1;
294 let comment = item.post_comment.as_ref().unwrap();
296 debug!("Width = {}, offset = {:?}", width, offset);
297 // Use block-style only for the last item or multiline comments.
298 let block_style = !formatting.ends_with_newline && last ||
299 comment.trim().contains('\n') ||
300 comment.trim().len() > width;
302 let formatted_comment = try_opt!(rewrite_comment(
305 Shape::legacy(width, offset),
309 if !formatted_comment.starts_with('\n') {
312 result.push_str(&formatted_comment);
315 if !last && tactic == DefinitiveListTactic::Vertical && item.new_lines {
323 pub struct ListItems<'a, I, F1, F2, F3>
327 codemap: &'a CodeMap,
332 prev_span_end: BytePos,
333 next_span_start: BytePos,
337 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
339 I: Iterator<Item = T>,
340 F1: Fn(&T) -> BytePos,
341 F2: Fn(&T) -> BytePos,
342 F3: Fn(&T) -> Option<String>,
344 type Item = ListItem;
346 fn next(&mut self) -> Option<Self::Item> {
347 let white_space: &[_] = &[' ', '\t'];
349 self.inner.next().map(|item| {
350 let mut new_lines = false;
352 let pre_snippet = self.codemap
353 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
355 let trimmed_pre_snippet = pre_snippet.trim();
356 let has_pre_comment = trimmed_pre_snippet.contains("//") ||
357 trimmed_pre_snippet.contains("/*");
358 let pre_comment = if has_pre_comment {
359 Some(trimmed_pre_snippet.to_owned())
365 let next_start = match self.inner.peek() {
366 Some(next_item) => (self.get_lo)(next_item),
367 None => self.next_span_start,
369 let post_snippet = self.codemap
370 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
373 let comment_end = match self.inner.peek() {
375 let mut block_open_index = post_snippet.find("/*");
376 // check if it realy is a block comment (and not //*)
377 if let Some(i) = block_open_index {
378 if i > 0 && &post_snippet[i - 1..i] == "/" {
379 block_open_index = None;
382 let newline_index = post_snippet.find('\n');
383 let separator_index = post_snippet.find_uncommented(",").unwrap();
385 match (block_open_index, newline_index) {
386 // Separator before comment, with the next item on same line.
387 // Comment belongs to next item.
388 (Some(i), None) if i > separator_index => separator_index + 1,
389 // Block-style post-comment before the separator.
392 find_comment_end(&post_snippet[i..]).unwrap() + i,
396 // Block-style post-comment. Either before or after the separator.
397 (Some(i), Some(j)) if i < j => {
399 find_comment_end(&post_snippet[i..]).unwrap() + i,
403 // Potential *single* line comment.
404 (_, Some(j)) if j > separator_index => j + 1,
405 _ => post_snippet.len(),
410 .find_uncommented(self.terminator)
411 .unwrap_or(post_snippet.len())
415 if !post_snippet.is_empty() && comment_end > 0 {
416 // Account for extra whitespace between items. This is fiddly
417 // because of the way we divide pre- and post- comments.
419 // Everything from the separator to the next item.
420 let test_snippet = &post_snippet[comment_end - 1..];
421 let first_newline = test_snippet.find('\n').unwrap_or(test_snippet.len());
422 // From the end of the first line of comments.
423 let test_snippet = &test_snippet[first_newline..];
424 let first = test_snippet
425 .find(|c: char| !c.is_whitespace())
426 .unwrap_or(test_snippet.len());
427 // From the end of the first line of comments to the next non-whitespace char.
428 let test_snippet = &test_snippet[..first];
430 if test_snippet.chars().filter(|c| c == &'\n').count() > 1 {
431 // There were multiple line breaks which got trimmed to nothing.
436 // Cleanup post-comment: strip separators and whitespace.
437 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
438 let post_snippet = post_snippet[..comment_end].trim();
440 let post_snippet_trimmed = if post_snippet.starts_with(',') {
441 post_snippet[1..].trim_matches(white_space)
442 } else if post_snippet.ends_with(',') {
443 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
448 let post_comment = if !post_snippet_trimmed.is_empty() {
449 Some(post_snippet_trimmed.to_owned())
455 pre_comment: pre_comment,
456 item: (self.get_item_string)(&item),
457 post_comment: post_comment,
458 new_lines: new_lines,
464 // Creates an iterator over a list's items with associated comments.
465 pub fn itemize_list<'a, T, I, F1, F2, F3>(
466 codemap: &'a CodeMap,
472 prev_span_end: BytePos,
473 next_span_start: BytePos,
474 ) -> ListItems<'a, I, F1, F2, F3>
476 I: Iterator<Item = T>,
477 F1: Fn(&T) -> BytePos,
478 F2: Fn(&T) -> BytePos,
479 F3: Fn(&T) -> Option<String>,
483 inner: inner.peekable(),
486 get_item_string: get_item_string,
487 prev_span_end: prev_span_end,
488 next_span_start: next_span_start,
489 terminator: terminator,
493 fn needs_trailing_separator(
494 separator_tactic: SeparatorTactic,
495 list_tactic: DefinitiveListTactic,
497 match separator_tactic {
498 SeparatorTactic::Always => true,
499 SeparatorTactic::Vertical => list_tactic == DefinitiveListTactic::Vertical,
500 SeparatorTactic::Never => false,
504 /// Returns the count and total width of the list items.
505 fn calculate_width<I, T>(items: I) -> (usize, usize)
507 I: IntoIterator<Item = T>,
512 .map(|item| total_item_width(item.as_ref()))
513 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
516 fn total_item_width(item: &ListItem) -> usize {
517 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..])) +
518 comment_len(item.post_comment.as_ref().map(|x| &(*x)[..])) +
519 item.item.as_ref().map_or(0, |str| str.len())
522 fn comment_len(comment: Option<&str>) -> usize {
525 let text_len = s.trim().len();
527 // We'll put " /*" before and " */" after inline comments.
537 // Compute horizontal and vertical shapes for a struct-lit-like thing.
538 pub fn struct_lit_shape(
540 context: &RewriteContext,
543 ) -> Option<(Option<Shape>, Shape)> {
544 let v_shape = match context.config.struct_lit_style() {
545 IndentStyle::Visual => {
547 try_opt!(shape.visual_indent(0).shrink_left(prefix_width)).sub_width(suffix_width)
550 IndentStyle::Block => {
551 let shape = shape.block_indent(context.config.tab_spaces());
553 width: try_opt!(context.config.max_width().checked_sub(shape.indent.width())),
558 let shape_width = shape.width.checked_sub(prefix_width + suffix_width);
559 if let Some(w) = shape_width {
560 let shape_width = cmp::min(w, context.config.struct_lit_width());
561 Some((Some(Shape::legacy(shape_width, shape.indent)), v_shape))
563 Some((None, v_shape))
567 // Compute the tactic for the internals of a struct-lit-like thing.
568 pub fn struct_lit_tactic(
569 h_shape: Option<Shape>,
570 context: &RewriteContext,
572 ) -> DefinitiveListTactic {
573 if let Some(h_shape) = h_shape {
574 let prelim_tactic = match (context.config.struct_lit_style(), items.len()) {
575 (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
576 _ => context.config.struct_lit_multiline_style().to_list_tactic(),
578 definitive_tactic(items, prelim_tactic, h_shape.width)
580 DefinitiveListTactic::Vertical
584 // Given a tactic and possible shapes for horizontal and vertical layout,
585 // come up with the actual shape to use.
586 pub fn shape_for_tactic(
587 tactic: DefinitiveListTactic,
588 h_shape: Option<Shape>,
592 DefinitiveListTactic::Horizontal => h_shape.unwrap(),
597 // Create a ListFormatting object for formatting the internals of a
598 // struct-lit-like thing, that is a series of fields.
599 pub fn struct_lit_formatting<'a>(
601 tactic: DefinitiveListTactic,
602 context: &'a RewriteContext,
603 force_no_trailing_comma: bool,
604 ) -> ListFormatting<'a> {
605 let ends_with_newline = context.config.struct_lit_style() != IndentStyle::Visual &&
606 tactic == DefinitiveListTactic::Vertical;
610 trailing_separator: if force_no_trailing_comma {
611 SeparatorTactic::Never
613 context.config.trailing_comma()
616 ends_with_newline: ends_with_newline,
617 config: context.config,