]> git.lizzy.rs Git - rust.git/blob - src/lists.rs
d6cb00b55cd3c59590fc72415e4252051dc8fbb3
[rust.git] / src / lists.rs
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.
4 //
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.
10
11 use std::cmp;
12 use std::iter::Peekable;
13
14 use syntax::codemap::{CodeMap, BytePos};
15
16 use {Indent, Shape};
17 use comment::{FindUncommented, rewrite_comment, find_comment_end};
18 use config::{Config, IndentStyle};
19 use rewrite::RewriteContext;
20 use utils::mk_sp;
21
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
25 /// their comments.
26 pub enum ListTactic {
27     // One item per row.
28     Vertical,
29     // All items on one row.
30     Horizontal,
31     // Try Horizontal layout, if that fails then vertical.
32     HorizontalVertical,
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.
36     Mixed,
37 }
38
39 impl_enum_serialize_and_deserialize!(ListTactic, Vertical, Horizontal, HorizontalVertical, Mixed);
40
41 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
42 pub enum SeparatorTactic {
43     Always,
44     Never,
45     Vertical,
46 }
47
48 impl_enum_serialize_and_deserialize!(SeparatorTactic, Always, Never, Vertical);
49
50 impl SeparatorTactic {
51     pub fn from_bool(b: bool) -> SeparatorTactic {
52         if b {
53             SeparatorTactic::Always
54         } else {
55             SeparatorTactic::Never
56         }
57     }
58 }
59
60 pub struct ListFormatting<'a> {
61     pub tactic: DefinitiveListTactic,
62     pub separator: &'a str,
63     pub trailing_separator: SeparatorTactic,
64     pub shape: Shape,
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,
69 }
70
71 pub fn format_item_list<I>(items: I, shape: Shape, config: &Config) -> Option<String>
72 where
73     I: Iterator<Item = ListItem>,
74 {
75     list_helper(items, shape, config, ListTactic::HorizontalVertical)
76 }
77
78 pub fn list_helper<I>(items: I, shape: Shape, config: &Config, tactic: ListTactic) -> Option<String>
79 where
80     I: Iterator<Item = ListItem>,
81 {
82     let item_vec: Vec<_> = items.collect();
83     let tactic = definitive_tactic(&item_vec, tactic, shape.width);
84     let fmt = ListFormatting {
85         tactic: tactic,
86         separator: ",",
87         trailing_separator: SeparatorTactic::Never,
88         shape: shape,
89         ends_with_newline: false,
90         config: config,
91     };
92
93     write_list(&item_vec, &fmt)
94 }
95
96 impl AsRef<ListItem> for ListItem {
97     fn as_ref(&self) -> &ListItem {
98         self
99     }
100 }
101
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
106     // rewrite.
107     pub item: Option<String>,
108     pub post_comment: Option<String>,
109     // Whether there is extra whitespace before this item.
110     pub new_lines: bool,
111 }
112
113 impl ListItem {
114     pub fn is_multiline(&self) -> bool {
115         self.item.as_ref().map_or(false, |s| s.contains('\n')) || self.pre_comment.is_some() ||
116             self.post_comment
117                 .as_ref()
118                 .map_or(false, |s| s.contains('\n'))
119     }
120
121     pub fn has_line_pre_comment(&self) -> bool {
122         self.pre_comment
123             .as_ref()
124             .map_or(false, |comment| comment.starts_with("//"))
125     }
126
127     pub fn from_str<S: Into<String>>(s: S) -> ListItem {
128         ListItem {
129             pre_comment: None,
130             item: Some(s.into()),
131             post_comment: None,
132             new_lines: false,
133         }
134     }
135 }
136
137 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
138 /// The definitive formatting tactic for lists.
139 pub enum DefinitiveListTactic {
140     Vertical,
141     Horizontal,
142     Mixed,
143 }
144
145 pub fn definitive_tactic<I, T>(items: I, tactic: ListTactic, width: usize) -> DefinitiveListTactic
146 where
147     I: IntoIterator<Item = T> + Clone,
148     T: AsRef<ListItem>,
149 {
150     let pre_line_comments = items
151         .clone()
152         .into_iter()
153         .any(|item| item.as_ref().has_line_pre_comment());
154
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,
162     };
163
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;
168
169     if real_total <= limit && !pre_line_comments &&
170         !items.into_iter().any(|item| item.as_ref().is_multiline())
171     {
172         DefinitiveListTactic::Horizontal
173     } else {
174         DefinitiveListTactic::Vertical
175     }
176 }
177
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>
181 where
182     I: IntoIterator<Item = T>,
183     T: AsRef<ListItem>,
184 {
185     let tactic = formatting.tactic;
186     let sep_len = formatting.separator.len();
187
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();
193
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());
199         let first = i == 0;
200         let last = iter.peek().is_none();
201         let separate = !last || trailing_separator;
202         let item_sep_len = if separate { sep_len } else { 0 };
203
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("")
208         } else {
209             inner_item.as_ref()
210         };
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();
214         }
215
216         match tactic {
217             DefinitiveListTactic::Horizontal if !first => {
218                 result.push(' ');
219             }
220             DefinitiveListTactic::Vertical if !first => {
221                 result.push('\n');
222                 result.push_str(indent_str);
223             }
224             DefinitiveListTactic::Mixed => {
225                 let total_width = total_item_width(item) + item_sep_len;
226
227                 // 1 is space between separator and item.
228                 if line_len > 0 && line_len + 1 + total_width > formatting.shape.width {
229                     result.push('\n');
230                     result.push_str(indent_str);
231                     line_len = 0;
232                 }
233
234                 if line_len > 0 {
235                     result.push(' ');
236                     line_len += 1;
237                 }
238
239                 line_len += total_width;
240             }
241             _ => {}
242         }
243
244         // Pre-comments
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(
250                 comment,
251                 block_mode,
252                 formatting.shape,
253                 formatting.config,
254             ));
255             result.push_str(&comment);
256
257             if tactic == DefinitiveListTactic::Vertical {
258                 result.push('\n');
259                 result.push_str(indent_str);
260             } else {
261                 result.push(' ');
262             }
263         }
264
265         result.push_str(&inner_item[..]);
266
267         // Post-comments
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(
271                 comment,
272                 true,
273                 Shape::legacy(formatting.shape.width, Indent::empty()),
274                 formatting.config,
275             ));
276
277             result.push(' ');
278             result.push_str(&formatted_comment);
279         }
280
281         if separate {
282             result.push_str(formatting.separator);
283         }
284
285         if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
286             // 1 = space between item and comment.
287             let width = formatting
288                 .shape
289                 .width
290                 .checked_sub(item_last_line_width + 1)
291                 .unwrap_or(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();
295
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;
301
302             let formatted_comment = try_opt!(rewrite_comment(
303                 comment,
304                 block_style,
305                 Shape::legacy(width, offset),
306                 formatting.config,
307             ));
308
309             if !formatted_comment.starts_with('\n') {
310                 result.push(' ');
311             }
312             result.push_str(&formatted_comment);
313         }
314
315         if !last && tactic == DefinitiveListTactic::Vertical && item.new_lines {
316             result.push('\n');
317         }
318     }
319
320     Some(result)
321 }
322
323 pub struct ListItems<'a, I, F1, F2, F3>
324 where
325     I: Iterator,
326 {
327     codemap: &'a CodeMap,
328     inner: Peekable<I>,
329     get_lo: F1,
330     get_hi: F2,
331     get_item_string: F3,
332     prev_span_end: BytePos,
333     next_span_start: BytePos,
334     terminator: &'a str,
335 }
336
337 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
338 where
339     I: Iterator<Item = T>,
340     F1: Fn(&T) -> BytePos,
341     F2: Fn(&T) -> BytePos,
342     F3: Fn(&T) -> Option<String>,
343 {
344     type Item = ListItem;
345
346     fn next(&mut self) -> Option<Self::Item> {
347         let white_space: &[_] = &[' ', '\t'];
348
349         self.inner.next().map(|item| {
350             let mut new_lines = false;
351             // Pre-comment
352             let pre_snippet = self.codemap
353                 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
354                 .unwrap();
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())
360             } else {
361                 None
362             };
363
364             // Post-comment
365             let next_start = match self.inner.peek() {
366                 Some(next_item) => (self.get_lo)(next_item),
367                 None => self.next_span_start,
368             };
369             let post_snippet = self.codemap
370                 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
371                 .unwrap();
372
373             let comment_end = match self.inner.peek() {
374                 Some(..) => {
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;
380                         }
381                     }
382                     let newline_index = post_snippet.find('\n');
383                     let separator_index = post_snippet.find_uncommented(",").unwrap();
384
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.
390                         (Some(i), None) => {
391                             cmp::max(
392                                 find_comment_end(&post_snippet[i..]).unwrap() + i,
393                                 separator_index + 1,
394                             )
395                         }
396                         // Block-style post-comment. Either before or after the separator.
397                         (Some(i), Some(j)) if i < j => {
398                             cmp::max(
399                                 find_comment_end(&post_snippet[i..]).unwrap() + i,
400                                 separator_index + 1,
401                             )
402                         }
403                         // Potential *single* line comment.
404                         (_, Some(j)) if j > separator_index => j + 1,
405                         _ => post_snippet.len(),
406                     }
407                 }
408                 None => {
409                     post_snippet
410                         .find_uncommented(self.terminator)
411                         .unwrap_or(post_snippet.len())
412                 }
413             };
414
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.
418
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];
429
430                 if test_snippet.chars().filter(|c| c == &'\n').count() > 1 {
431                     // There were multiple line breaks which got trimmed to nothing.
432                     new_lines = true;
433                 }
434             }
435
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();
439
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)
444             } else {
445                 post_snippet
446             };
447
448             let post_comment = if !post_snippet_trimmed.is_empty() {
449                 Some(post_snippet_trimmed.to_owned())
450             } else {
451                 None
452             };
453
454             ListItem {
455                 pre_comment: pre_comment,
456                 item: (self.get_item_string)(&item),
457                 post_comment: post_comment,
458                 new_lines: new_lines,
459             }
460         })
461     }
462 }
463
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,
467     inner: I,
468     terminator: &'a str,
469     get_lo: F1,
470     get_hi: F2,
471     get_item_string: F3,
472     prev_span_end: BytePos,
473     next_span_start: BytePos,
474 ) -> ListItems<'a, I, F1, F2, F3>
475 where
476     I: Iterator<Item = T>,
477     F1: Fn(&T) -> BytePos,
478     F2: Fn(&T) -> BytePos,
479     F3: Fn(&T) -> Option<String>,
480 {
481     ListItems {
482         codemap: codemap,
483         inner: inner.peekable(),
484         get_lo: get_lo,
485         get_hi: get_hi,
486         get_item_string: get_item_string,
487         prev_span_end: prev_span_end,
488         next_span_start: next_span_start,
489         terminator: terminator,
490     }
491 }
492
493 fn needs_trailing_separator(
494     separator_tactic: SeparatorTactic,
495     list_tactic: DefinitiveListTactic,
496 ) -> bool {
497     match separator_tactic {
498         SeparatorTactic::Always => true,
499         SeparatorTactic::Vertical => list_tactic == DefinitiveListTactic::Vertical,
500         SeparatorTactic::Never => false,
501     }
502 }
503
504 /// Returns the count and total width of the list items.
505 fn calculate_width<I, T>(items: I) -> (usize, usize)
506 where
507     I: IntoIterator<Item = T>,
508     T: AsRef<ListItem>,
509 {
510     items
511         .into_iter()
512         .map(|item| total_item_width(item.as_ref()))
513         .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
514 }
515
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())
520 }
521
522 fn comment_len(comment: Option<&str>) -> usize {
523     match comment {
524         Some(s) => {
525             let text_len = s.trim().len();
526             if text_len > 0 {
527                 // We'll put " /*" before and " */" after inline comments.
528                 text_len + 6
529             } else {
530                 text_len
531             }
532         }
533         None => 0,
534     }
535 }
536
537 // Compute horizontal and vertical shapes for a struct-lit-like thing.
538 pub fn struct_lit_shape(
539     shape: Shape,
540     context: &RewriteContext,
541     prefix_width: usize,
542     suffix_width: usize,
543 ) -> Option<(Option<Shape>, Shape)> {
544     let v_shape = match context.config.struct_lit_style() {
545         IndentStyle::Visual => {
546             try_opt!(
547                 try_opt!(shape.visual_indent(0).shrink_left(prefix_width)).sub_width(suffix_width)
548             )
549         }
550         IndentStyle::Block => {
551             let shape = shape.block_indent(context.config.tab_spaces());
552             Shape {
553                 width: try_opt!(context.config.max_width().checked_sub(shape.indent.width())),
554                 ..shape
555             }
556         }
557     };
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))
562     } else {
563         Some((None, v_shape))
564     }
565 }
566
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,
571     items: &[ListItem],
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(),
577         };
578         definitive_tactic(items, prelim_tactic, h_shape.width)
579     } else {
580         DefinitiveListTactic::Vertical
581     }
582 }
583
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>,
589     v_shape: Shape,
590 ) -> Shape {
591     match tactic {
592         DefinitiveListTactic::Horizontal => h_shape.unwrap(),
593         _ => v_shape,
594     }
595 }
596
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>(
600     shape: Shape,
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;
607     ListFormatting {
608         tactic: tactic,
609         separator: ",",
610         trailing_separator: if force_no_trailing_comma {
611             SeparatorTactic::Never
612         } else {
613             context.config.trailing_comma()
614         },
615         shape: shape,
616         ends_with_newline: ends_with_newline,
617         config: context.config,
618     }
619 }