]> git.lizzy.rs Git - rust.git/blob - src/lists.rs
Merge pull request #1615 from Mitranim/patch-1
[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_fn_args<I>(items: I, shape: Shape, config: &Config) -> Option<String>
72 where
73     I: Iterator<Item = ListItem>,
74 {
75     list_helper(
76         items,
77         shape,
78         config,
79         ListTactic::LimitedHorizontalVertical(config.fn_call_width()),
80     )
81 }
82
83 pub fn format_item_list<I>(items: I, shape: Shape, config: &Config) -> Option<String>
84 where
85     I: Iterator<Item = ListItem>,
86 {
87     list_helper(items, shape, config, ListTactic::HorizontalVertical)
88 }
89
90 pub fn list_helper<I>(items: I, shape: Shape, config: &Config, tactic: ListTactic) -> Option<String>
91 where
92     I: Iterator<Item = ListItem>,
93 {
94     let item_vec: Vec<_> = items.collect();
95     let tactic = definitive_tactic(&item_vec, tactic, shape.width);
96     let fmt = ListFormatting {
97         tactic: tactic,
98         separator: ",",
99         trailing_separator: SeparatorTactic::Never,
100         shape: shape,
101         ends_with_newline: false,
102         config: config,
103     };
104
105     write_list(&item_vec, &fmt)
106 }
107
108 impl AsRef<ListItem> for ListItem {
109     fn as_ref(&self) -> &ListItem {
110         self
111     }
112 }
113
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
118     // rewrite.
119     pub item: Option<String>,
120     pub post_comment: Option<String>,
121     // Whether there is extra whitespace before this item.
122     pub new_lines: bool,
123 }
124
125 impl ListItem {
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(
129                 false,
130                 |s| s.contains('\n'),
131             )
132     }
133
134     pub fn has_line_pre_comment(&self) -> bool {
135         self.pre_comment.as_ref().map_or(false, |comment| {
136             comment.starts_with("//")
137         })
138     }
139
140     pub fn from_str<S: Into<String>>(s: S) -> ListItem {
141         ListItem {
142             pre_comment: None,
143             item: Some(s.into()),
144             post_comment: None,
145             new_lines: false,
146         }
147     }
148 }
149
150 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
151 /// The definitive formatting tactic for lists.
152 pub enum DefinitiveListTactic {
153     Vertical,
154     Horizontal,
155     Mixed,
156 }
157
158 pub fn definitive_tactic<I, T>(items: I, tactic: ListTactic, width: usize) -> DefinitiveListTactic
159 where
160     I: IntoIterator<Item = T> + Clone,
161     T: AsRef<ListItem>,
162 {
163     let pre_line_comments = items.clone().into_iter().any(|item| {
164         item.as_ref().has_line_pre_comment()
165     });
166
167     let limit = match tactic {
168         _ if pre_line_comments => return DefinitiveListTactic::Vertical,
169         ListTactic::Mixed => return DefinitiveListTactic::Mixed,
170         ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
171         ListTactic::Vertical => return DefinitiveListTactic::Vertical,
172         ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
173         ListTactic::HorizontalVertical => width,
174     };
175
176     let (sep_count, total_width) = calculate_width(items.clone());
177     let sep_len = ", ".len(); // FIXME: make more generic?
178     let total_sep_len = sep_len * sep_count.checked_sub(1).unwrap_or(0);
179     let real_total = total_width + total_sep_len;
180
181     if real_total <= limit && !pre_line_comments &&
182         !items.into_iter().any(|item| item.as_ref().is_multiline())
183     {
184         DefinitiveListTactic::Horizontal
185     } else {
186         DefinitiveListTactic::Vertical
187     }
188 }
189
190 // Format a list of commented items into a string.
191 // TODO: add unit tests
192 pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
193 where
194     I: IntoIterator<Item = T>,
195     T: AsRef<ListItem>,
196 {
197     let tactic = formatting.tactic;
198     let sep_len = formatting.separator.len();
199
200     // Now that we know how we will layout, we can decide for sure if there
201     // will be a trailing separator.
202     let trailing_separator = needs_trailing_separator(formatting.trailing_separator, tactic);
203     let mut result = String::new();
204     let mut iter = items.into_iter().enumerate().peekable();
205
206     let mut line_len = 0;
207     let indent_str = &formatting.shape.indent.to_string(formatting.config);
208     while let Some((i, item)) = iter.next() {
209         let item = item.as_ref();
210         let inner_item = try_opt!(item.item.as_ref());
211         let first = i == 0;
212         let last = iter.peek().is_none();
213         let separate = !last || trailing_separator;
214         let item_sep_len = if separate { sep_len } else { 0 };
215
216         // Item string may be multi-line. Its length (used for block comment alignment)
217         // should be only the length of the last line.
218         let item_last_line = if item.is_multiline() {
219             inner_item.lines().last().unwrap_or("")
220         } else {
221             inner_item.as_ref()
222         };
223         let mut item_last_line_width = item_last_line.len() + item_sep_len;
224         if item_last_line.starts_with(indent_str) {
225             item_last_line_width -= indent_str.len();
226         }
227
228         match tactic {
229             DefinitiveListTactic::Horizontal if !first => {
230                 result.push(' ');
231             }
232             DefinitiveListTactic::Vertical if !first => {
233                 result.push('\n');
234                 result.push_str(indent_str);
235             }
236             DefinitiveListTactic::Mixed => {
237                 let total_width = total_item_width(item) + item_sep_len;
238
239                 // 1 is space between separator and item.
240                 if line_len > 0 && line_len + 1 + total_width > formatting.shape.width {
241                     result.push('\n');
242                     result.push_str(indent_str);
243                     line_len = 0;
244                 }
245
246                 if line_len > 0 {
247                     result.push(' ');
248                     line_len += 1;
249                 }
250
251                 line_len += total_width;
252             }
253             _ => {}
254         }
255
256         // Pre-comments
257         if let Some(ref comment) = item.pre_comment {
258             // Block style in non-vertical mode.
259             let block_mode = tactic != DefinitiveListTactic::Vertical;
260             // Width restriction is only relevant in vertical mode.
261             let comment = try_opt!(rewrite_comment(
262                 comment,
263                 block_mode,
264                 formatting.shape,
265                 formatting.config,
266             ));
267             result.push_str(&comment);
268
269             if tactic == DefinitiveListTactic::Vertical {
270                 result.push('\n');
271                 result.push_str(indent_str);
272             } else {
273                 result.push(' ');
274             }
275         }
276
277         result.push_str(&inner_item[..]);
278
279         // Post-comments
280         if tactic != DefinitiveListTactic::Vertical && item.post_comment.is_some() {
281             let comment = item.post_comment.as_ref().unwrap();
282             let formatted_comment = try_opt!(rewrite_comment(
283                 comment,
284                 true,
285                 Shape::legacy(formatting.shape.width, Indent::empty()),
286                 formatting.config,
287             ));
288
289             result.push(' ');
290             result.push_str(&formatted_comment);
291         }
292
293         if separate {
294             result.push_str(formatting.separator);
295         }
296
297         if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
298             // 1 = space between item and comment.
299             let width = formatting
300                 .shape
301                 .width
302                 .checked_sub(item_last_line_width + 1)
303                 .unwrap_or(1);
304             let mut offset = formatting.shape.indent;
305             offset.alignment += item_last_line_width + 1;
306             let comment = item.post_comment.as_ref().unwrap();
307
308             debug!("Width = {}, offset = {:?}", width, offset);
309             // Use block-style only for the last item or multiline comments.
310             let block_style = !formatting.ends_with_newline && last ||
311                 comment.trim().contains('\n') ||
312                 comment.trim().len() > width;
313
314             let formatted_comment = try_opt!(rewrite_comment(
315                 comment,
316                 block_style,
317                 Shape::legacy(width, offset),
318                 formatting.config,
319             ));
320
321             if !formatted_comment.starts_with('\n') {
322                 result.push(' ');
323             }
324             result.push_str(&formatted_comment);
325         }
326
327         if !last && tactic == DefinitiveListTactic::Vertical && item.new_lines {
328             result.push('\n');
329         }
330     }
331
332     Some(result)
333 }
334
335 pub struct ListItems<'a, I, F1, F2, F3>
336 where
337     I: Iterator,
338 {
339     codemap: &'a CodeMap,
340     inner: Peekable<I>,
341     get_lo: F1,
342     get_hi: F2,
343     get_item_string: F3,
344     prev_span_end: BytePos,
345     next_span_start: BytePos,
346     terminator: &'a str,
347 }
348
349 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
350 where
351     I: Iterator<Item = T>,
352     F1: Fn(&T) -> BytePos,
353     F2: Fn(&T) -> BytePos,
354     F3: Fn(&T) -> Option<String>,
355 {
356     type Item = ListItem;
357
358     fn next(&mut self) -> Option<Self::Item> {
359         let white_space: &[_] = &[' ', '\t'];
360
361         self.inner.next().map(|item| {
362             let mut new_lines = false;
363             // Pre-comment
364             let pre_snippet = self.codemap
365                 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
366                 .unwrap();
367             let trimmed_pre_snippet = pre_snippet.trim();
368             let has_pre_comment = trimmed_pre_snippet.contains("//") ||
369                 trimmed_pre_snippet.contains("/*");
370             let pre_comment = if has_pre_comment {
371                 Some(trimmed_pre_snippet.to_owned())
372             } else {
373                 None
374             };
375
376             // Post-comment
377             let next_start = match self.inner.peek() {
378                 Some(next_item) => (self.get_lo)(next_item),
379                 None => self.next_span_start,
380             };
381             let post_snippet = self.codemap
382                 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
383                 .unwrap();
384
385             let comment_end = match self.inner.peek() {
386                 Some(..) => {
387                     let mut block_open_index = post_snippet.find("/*");
388                     // check if it realy is a block comment (and not //*)
389                     if let Some(i) = block_open_index {
390                         if i > 0 && &post_snippet[i - 1..i] == "/" {
391                             block_open_index = None;
392                         }
393                     }
394                     let newline_index = post_snippet.find('\n');
395                     let separator_index = post_snippet.find_uncommented(",").unwrap();
396
397                     match (block_open_index, newline_index) {
398                         // Separator before comment, with the next item on same line.
399                         // Comment belongs to next item.
400                         (Some(i), None) if i > separator_index => separator_index + 1,
401                         // Block-style post-comment before the separator.
402                         (Some(i), None) => {
403                             cmp::max(
404                                 find_comment_end(&post_snippet[i..]).unwrap() + i,
405                                 separator_index + 1,
406                             )
407                         }
408                         // Block-style post-comment. Either before or after the separator.
409                         (Some(i), Some(j)) if i < j => {
410                             cmp::max(
411                                 find_comment_end(&post_snippet[i..]).unwrap() + i,
412                                 separator_index + 1,
413                             )
414                         }
415                         // Potential *single* line comment.
416                         (_, Some(j)) if j > separator_index => j + 1,
417                         _ => post_snippet.len(),
418                     }
419                 }
420                 None => {
421                     post_snippet.find_uncommented(self.terminator).unwrap_or(
422                         post_snippet
423                             .len(),
424                     )
425                 }
426             };
427
428             if !post_snippet.is_empty() && comment_end > 0 {
429                 // Account for extra whitespace between items. This is fiddly
430                 // because of the way we divide pre- and post- comments.
431
432                 // Everything from the separator to the next item.
433                 let test_snippet = &post_snippet[comment_end - 1..];
434                 let first_newline = test_snippet.find('\n').unwrap_or(test_snippet.len());
435                 // From the end of the first line of comments.
436                 let test_snippet = &test_snippet[first_newline..];
437                 let first = test_snippet.find(|c: char| !c.is_whitespace()).unwrap_or(
438                     test_snippet
439                         .len(),
440                 );
441                 // From the end of the first line of comments to the next non-whitespace char.
442                 let test_snippet = &test_snippet[..first];
443
444                 if test_snippet.chars().filter(|c| c == &'\n').count() > 1 {
445                     // There were multiple line breaks which got trimmed to nothing.
446                     new_lines = true;
447                 }
448             }
449
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();
453
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)
458             } else {
459                 post_snippet
460             };
461
462             let post_comment = if !post_snippet_trimmed.is_empty() {
463                 Some(post_snippet_trimmed.to_owned())
464             } else {
465                 None
466             };
467
468             ListItem {
469                 pre_comment: pre_comment,
470                 item: (self.get_item_string)(&item),
471                 post_comment: post_comment,
472                 new_lines: new_lines,
473             }
474         })
475     }
476 }
477
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,
481     inner: I,
482     terminator: &'a str,
483     get_lo: F1,
484     get_hi: F2,
485     get_item_string: F3,
486     prev_span_end: BytePos,
487     next_span_start: BytePos,
488 ) -> ListItems<'a, I, F1, F2, F3>
489 where
490     I: Iterator<Item = T>,
491     F1: Fn(&T) -> BytePos,
492     F2: Fn(&T) -> BytePos,
493     F3: Fn(&T) -> Option<String>,
494 {
495     ListItems {
496         codemap: codemap,
497         inner: inner.peekable(),
498         get_lo: get_lo,
499         get_hi: get_hi,
500         get_item_string: get_item_string,
501         prev_span_end: prev_span_end,
502         next_span_start: next_span_start,
503         terminator: terminator,
504     }
505 }
506
507 fn needs_trailing_separator(
508     separator_tactic: SeparatorTactic,
509     list_tactic: DefinitiveListTactic,
510 ) -> bool {
511     match separator_tactic {
512         SeparatorTactic::Always => true,
513         SeparatorTactic::Vertical => list_tactic == DefinitiveListTactic::Vertical,
514         SeparatorTactic::Never => false,
515     }
516 }
517
518 /// Returns the count and total width of the list items.
519 fn calculate_width<I, T>(items: I) -> (usize, usize)
520 where
521     I: IntoIterator<Item = T>,
522     T: AsRef<ListItem>,
523 {
524     items
525         .into_iter()
526         .map(|item| total_item_width(item.as_ref()))
527         .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
528 }
529
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())
534 }
535
536 fn comment_len(comment: Option<&str>) -> usize {
537     match comment {
538         Some(s) => {
539             let text_len = s.trim().len();
540             if text_len > 0 {
541                 // We'll put " /*" before and " */" after inline comments.
542                 text_len + 6
543             } else {
544                 text_len
545             }
546         }
547         None => 0,
548     }
549 }
550
551 // Compute horizontal and vertical shapes for a struct-lit-like thing.
552 pub fn struct_lit_shape(
553     shape: Shape,
554     context: &RewriteContext,
555     prefix_width: usize,
556     suffix_width: usize,
557 ) -> Option<(Option<Shape>, Shape)> {
558     let v_shape = match context.config.struct_lit_style() {
559         IndentStyle::Visual => {
560             try_opt!(
561                 try_opt!(shape.visual_indent(0).shrink_left(prefix_width)).sub_width(suffix_width)
562             )
563         }
564         IndentStyle::Block => {
565             let shape = shape.block_indent(context.config.tab_spaces());
566             Shape {
567                 width: try_opt!(context.config.max_width().checked_sub(shape.indent.width())),
568                 ..shape
569             }
570         }
571     };
572     let h_shape = shape.sub_width(prefix_width + suffix_width);
573     Some((h_shape, v_shape))
574 }
575
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,
580     items: &[ListItem],
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(),
586         };
587
588         if prelim_tactic == ListTactic::HorizontalVertical && items.len() > 1 {
589             prelim_tactic =
590                 ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width());
591         }
592
593         definitive_tactic(items, prelim_tactic, h_shape.width)
594     } else {
595         DefinitiveListTactic::Vertical
596     }
597 }
598
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>,
604     v_shape: Shape,
605 ) -> Shape {
606     match tactic {
607         DefinitiveListTactic::Horizontal => h_shape.unwrap(),
608         _ => v_shape,
609     }
610 }
611
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>(
615     shape: Shape,
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;
622     ListFormatting {
623         tactic: tactic,
624         separator: ",",
625         trailing_separator: if force_no_trailing_comma {
626             SeparatorTactic::Never
627         } else {
628             context.config.trailing_comma()
629         },
630         shape: shape,
631         ends_with_newline: ends_with_newline,
632         config: context.config,
633     }
634 }