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 {
135 self.pre_comment.as_ref().map_or(
137 |comment| comment.starts_with("//"),
141 pub fn from_str<S: Into<String>>(s: S) -> ListItem {
144 item: Some(s.into()),
151 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
152 /// The definitive formatting tactic for lists.
153 pub enum DefinitiveListTactic {
159 pub fn definitive_tactic<I, T>(items: I, tactic: ListTactic, width: usize) -> DefinitiveListTactic
161 I: IntoIterator<Item = T> + Clone,
164 let pre_line_comments = items
167 .any(|item| item.as_ref().has_line_pre_comment());
169 let limit = match tactic {
170 _ if pre_line_comments => return DefinitiveListTactic::Vertical,
171 ListTactic::Mixed => return DefinitiveListTactic::Mixed,
172 ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
173 ListTactic::Vertical => return DefinitiveListTactic::Vertical,
174 ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
175 ListTactic::HorizontalVertical => width,
178 let (sep_count, total_width) = calculate_width(items.clone());
179 let sep_len = ", ".len(); // FIXME: make more generic?
180 let total_sep_len = sep_len * sep_count.checked_sub(1).unwrap_or(0);
181 let real_total = total_width + total_sep_len;
183 if real_total <= limit && !pre_line_comments &&
184 !items.into_iter().any(|item| item.as_ref().is_multiline())
186 DefinitiveListTactic::Horizontal
188 DefinitiveListTactic::Vertical
192 // Format a list of commented items into a string.
193 // TODO: add unit tests
194 pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
196 I: IntoIterator<Item = T>,
199 let tactic = formatting.tactic;
200 let sep_len = formatting.separator.len();
202 // Now that we know how we will layout, we can decide for sure if there
203 // will be a trailing separator.
204 let trailing_separator = needs_trailing_separator(formatting.trailing_separator, tactic);
205 let mut result = String::new();
206 let mut iter = items.into_iter().enumerate().peekable();
208 let mut line_len = 0;
209 let indent_str = &formatting.shape.indent.to_string(formatting.config);
210 while let Some((i, item)) = iter.next() {
211 let item = item.as_ref();
212 let inner_item = try_opt!(item.item.as_ref());
214 let last = iter.peek().is_none();
215 let separate = !last || trailing_separator;
216 let item_sep_len = if separate { sep_len } else { 0 };
218 // Item string may be multi-line. Its length (used for block comment alignment)
219 // should be only the length of the last line.
220 let item_last_line = if item.is_multiline() {
221 inner_item.lines().last().unwrap_or("")
225 let mut item_last_line_width = item_last_line.len() + item_sep_len;
226 if item_last_line.starts_with(indent_str) {
227 item_last_line_width -= indent_str.len();
231 DefinitiveListTactic::Horizontal if !first => {
234 DefinitiveListTactic::Vertical if !first => {
236 result.push_str(indent_str);
238 DefinitiveListTactic::Mixed => {
239 let total_width = total_item_width(item) + item_sep_len;
241 // 1 is space between separator and item.
242 if line_len > 0 && line_len + 1 + total_width > formatting.shape.width {
244 result.push_str(indent_str);
253 line_len += total_width;
259 if let Some(ref comment) = item.pre_comment {
260 // Block style in non-vertical mode.
261 let block_mode = tactic != DefinitiveListTactic::Vertical;
262 // Width restriction is only relevant in vertical mode.
263 let comment = try_opt!(rewrite_comment(
269 result.push_str(&comment);
271 if tactic == DefinitiveListTactic::Vertical {
273 result.push_str(indent_str);
279 result.push_str(&inner_item[..]);
282 if tactic != DefinitiveListTactic::Vertical && item.post_comment.is_some() {
283 let comment = item.post_comment.as_ref().unwrap();
284 let formatted_comment = try_opt!(rewrite_comment(
287 Shape::legacy(formatting.shape.width, Indent::empty()),
292 result.push_str(&formatted_comment);
296 result.push_str(formatting.separator);
299 if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
300 // 1 = space between item and comment.
301 let width = formatting
304 .checked_sub(item_last_line_width + 1)
306 let mut offset = formatting.shape.indent;
307 offset.alignment += item_last_line_width + 1;
308 let comment = item.post_comment.as_ref().unwrap();
310 debug!("Width = {}, offset = {:?}", width, offset);
311 // Use block-style only for the last item or multiline comments.
312 let block_style = !formatting.ends_with_newline && last ||
313 comment.trim().contains('\n') ||
314 comment.trim().len() > width;
316 let formatted_comment = try_opt!(rewrite_comment(
319 Shape::legacy(width, offset),
323 if !formatted_comment.starts_with('\n') {
326 result.push_str(&formatted_comment);
329 if !last && tactic == DefinitiveListTactic::Vertical && item.new_lines {
337 pub struct ListItems<'a, I, F1, F2, F3>
341 codemap: &'a CodeMap,
346 prev_span_end: BytePos,
347 next_span_start: BytePos,
351 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
353 I: Iterator<Item = T>,
354 F1: Fn(&T) -> BytePos,
355 F2: Fn(&T) -> BytePos,
356 F3: Fn(&T) -> Option<String>,
358 type Item = ListItem;
360 fn next(&mut self) -> Option<Self::Item> {
361 let white_space: &[_] = &[' ', '\t'];
363 self.inner.next().map(|item| {
364 let mut new_lines = false;
366 let pre_snippet = self.codemap
367 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
369 let trimmed_pre_snippet = pre_snippet.trim();
370 let has_pre_comment = trimmed_pre_snippet.contains("//") ||
371 trimmed_pre_snippet.contains("/*");
372 let pre_comment = if has_pre_comment {
373 Some(trimmed_pre_snippet.to_owned())
379 let next_start = match self.inner.peek() {
380 Some(next_item) => (self.get_lo)(next_item),
381 None => self.next_span_start,
383 let post_snippet = self.codemap
384 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
387 let comment_end = match self.inner.peek() {
389 let mut block_open_index = post_snippet.find("/*");
390 // check if it realy is a block comment (and not //*)
391 if let Some(i) = block_open_index {
392 if i > 0 && &post_snippet[i - 1..i] == "/" {
393 block_open_index = None;
396 let newline_index = post_snippet.find('\n');
397 let separator_index = post_snippet.find_uncommented(",").unwrap();
399 match (block_open_index, newline_index) {
400 // Separator before comment, with the next item on same line.
401 // Comment belongs to next item.
402 (Some(i), None) if i > separator_index => separator_index + 1,
403 // Block-style post-comment before the separator.
406 find_comment_end(&post_snippet[i..]).unwrap() + i,
410 // Block-style post-comment. Either before or after the separator.
411 (Some(i), Some(j)) if i < j => {
413 find_comment_end(&post_snippet[i..]).unwrap() + i,
417 // Potential *single* line comment.
418 (_, Some(j)) if j > separator_index => j + 1,
419 _ => post_snippet.len(),
424 .find_uncommented(self.terminator)
425 .unwrap_or(post_snippet.len())
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
439 .find(|c: char| !c.is_whitespace())
440 .unwrap_or(test_snippet.len());
441 // From the end of the first line of comments to the next non-whitespace char.
442 let test_snippet = &test_snippet[..first];
444 if test_snippet.chars().filter(|c| c == &'\n').count() > 1 {
445 // There were multiple line breaks which got trimmed to nothing.
450 // Cleanup post-comment: strip separators and whitespace.
451 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
452 let post_snippet = post_snippet[..comment_end].trim();
454 let post_snippet_trimmed = if post_snippet.starts_with(',') {
455 post_snippet[1..].trim_matches(white_space)
456 } else if post_snippet.ends_with(',') {
457 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
462 let post_comment = if !post_snippet_trimmed.is_empty() {
463 Some(post_snippet_trimmed.to_owned())
469 pre_comment: pre_comment,
470 item: (self.get_item_string)(&item),
471 post_comment: post_comment,
472 new_lines: new_lines,
478 // Creates an iterator over a list's items with associated comments.
479 pub fn itemize_list<'a, T, I, F1, F2, F3>(
480 codemap: &'a CodeMap,
486 prev_span_end: BytePos,
487 next_span_start: BytePos,
488 ) -> ListItems<'a, I, F1, F2, F3>
490 I: Iterator<Item = T>,
491 F1: Fn(&T) -> BytePos,
492 F2: Fn(&T) -> BytePos,
493 F3: Fn(&T) -> Option<String>,
497 inner: inner.peekable(),
500 get_item_string: get_item_string,
501 prev_span_end: prev_span_end,
502 next_span_start: next_span_start,
503 terminator: terminator,
507 fn needs_trailing_separator(
508 separator_tactic: SeparatorTactic,
509 list_tactic: DefinitiveListTactic,
511 match separator_tactic {
512 SeparatorTactic::Always => true,
513 SeparatorTactic::Vertical => list_tactic == DefinitiveListTactic::Vertical,
514 SeparatorTactic::Never => false,
518 /// Returns the count and total width of the list items.
519 fn calculate_width<I, T>(items: I) -> (usize, usize)
521 I: IntoIterator<Item = T>,
526 .map(|item| total_item_width(item.as_ref()))
527 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
530 fn total_item_width(item: &ListItem) -> usize {
531 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..])) +
532 comment_len(item.post_comment.as_ref().map(|x| &(*x)[..])) +
533 item.item.as_ref().map_or(0, |str| str.len())
536 fn comment_len(comment: Option<&str>) -> usize {
539 let text_len = s.trim().len();
541 // We'll put " /*" before and " */" after inline comments.
551 // Compute horizontal and vertical shapes for a struct-lit-like thing.
552 pub fn struct_lit_shape(
554 context: &RewriteContext,
557 ) -> Option<(Option<Shape>, Shape)> {
558 let v_shape = match context.config.struct_lit_style() {
559 IndentStyle::Visual => {
561 try_opt!(shape.visual_indent(0).shrink_left(prefix_width)).sub_width(suffix_width)
564 IndentStyle::Block => {
565 let shape = shape.block_indent(context.config.tab_spaces());
567 width: try_opt!(context.config.max_width().checked_sub(shape.indent.width())),
572 let h_shape = shape.sub_width(prefix_width + suffix_width);
573 Some((h_shape, v_shape))
576 // Compute the tactic for the internals of a struct-lit-like thing.
577 pub fn struct_lit_tactic(
578 h_shape: Option<Shape>,
579 context: &RewriteContext,
581 ) -> DefinitiveListTactic {
582 if let Some(h_shape) = h_shape {
583 let mut prelim_tactic = match (context.config.struct_lit_style(), items.len()) {
584 (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
585 _ => context.config.struct_lit_multiline_style().to_list_tactic(),
588 if prelim_tactic == ListTactic::HorizontalVertical && items.len() > 1 {
590 ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width());
593 definitive_tactic(items, prelim_tactic, h_shape.width)
595 DefinitiveListTactic::Vertical
599 // Given a tactic and possible shapes for horizontal and vertical layout,
600 // come up with the actual shape to use.
601 pub fn shape_for_tactic(
602 tactic: DefinitiveListTactic,
603 h_shape: Option<Shape>,
607 DefinitiveListTactic::Horizontal => h_shape.unwrap(),
612 // Create a ListFormatting object for formatting the internals of a
613 // struct-lit-like thing, that is a series of fields.
614 pub fn struct_lit_formatting<'a>(
616 tactic: DefinitiveListTactic,
617 context: &'a RewriteContext,
618 force_no_trailing_comma: bool,
619 ) -> ListFormatting<'a> {
620 let ends_with_newline = context.config.struct_lit_style() != IndentStyle::Visual &&
621 tactic == DefinitiveListTactic::Vertical;
625 trailing_separator: if force_no_trailing_comma {
626 SeparatorTactic::Never
628 context.config.trailing_comma()
631 ends_with_newline: ends_with_newline,
632 config: context.config,