]> git.lizzy.rs Git - rust.git/blob - src/lists.rs
Merge pull request #1708 from topecongiro/chain-overflow
[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
129                 .as_ref()
130                 .map_or(false, |s| s.contains('\n'))
131     }
132
133     pub fn has_line_pre_comment(&self) -> bool {
134         self.pre_comment
135             .as_ref()
136             .map_or(false, |comment| comment.starts_with("//"))
137     }
138
139     pub fn from_str<S: Into<String>>(s: S) -> ListItem {
140         ListItem {
141             pre_comment: None,
142             item: Some(s.into()),
143             post_comment: None,
144             new_lines: false,
145         }
146     }
147 }
148
149 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
150 /// The definitive formatting tactic for lists.
151 pub enum DefinitiveListTactic {
152     Vertical,
153     Horizontal,
154     Mixed,
155 }
156
157 pub fn definitive_tactic<I, T>(items: I, tactic: ListTactic, width: usize) -> DefinitiveListTactic
158 where
159     I: IntoIterator<Item = T> + Clone,
160     T: AsRef<ListItem>,
161 {
162     let pre_line_comments = items
163         .clone()
164         .into_iter()
165         .any(|item| item.as_ref().has_line_pre_comment());
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
422                         .find_uncommented(self.terminator)
423                         .unwrap_or(post_snippet.len())
424                 }
425             };
426
427             if !post_snippet.is_empty() && comment_end > 0 {
428                 // Account for extra whitespace between items. This is fiddly
429                 // because of the way we divide pre- and post- comments.
430
431                 // Everything from the separator to the next item.
432                 let test_snippet = &post_snippet[comment_end - 1..];
433                 let first_newline = test_snippet.find('\n').unwrap_or(test_snippet.len());
434                 // From the end of the first line of comments.
435                 let test_snippet = &test_snippet[first_newline..];
436                 let first = test_snippet
437                     .find(|c: char| !c.is_whitespace())
438                     .unwrap_or(test_snippet.len());
439                 // From the end of the first line of comments to the next non-whitespace char.
440                 let test_snippet = &test_snippet[..first];
441
442                 if test_snippet.chars().filter(|c| c == &'\n').count() > 1 {
443                     // There were multiple line breaks which got trimmed to nothing.
444                     new_lines = true;
445                 }
446             }
447
448             // Cleanup post-comment: strip separators and whitespace.
449             self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
450             let post_snippet = post_snippet[..comment_end].trim();
451
452             let post_snippet_trimmed = if post_snippet.starts_with(',') {
453                 post_snippet[1..].trim_matches(white_space)
454             } else if post_snippet.ends_with(',') {
455                 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
456             } else {
457                 post_snippet
458             };
459
460             let post_comment = if !post_snippet_trimmed.is_empty() {
461                 Some(post_snippet_trimmed.to_owned())
462             } else {
463                 None
464             };
465
466             ListItem {
467                 pre_comment: pre_comment,
468                 item: (self.get_item_string)(&item),
469                 post_comment: post_comment,
470                 new_lines: new_lines,
471             }
472         })
473     }
474 }
475
476 // Creates an iterator over a list's items with associated comments.
477 pub fn itemize_list<'a, T, I, F1, F2, F3>(
478     codemap: &'a CodeMap,
479     inner: I,
480     terminator: &'a str,
481     get_lo: F1,
482     get_hi: F2,
483     get_item_string: F3,
484     prev_span_end: BytePos,
485     next_span_start: BytePos,
486 ) -> ListItems<'a, I, F1, F2, F3>
487 where
488     I: Iterator<Item = T>,
489     F1: Fn(&T) -> BytePos,
490     F2: Fn(&T) -> BytePos,
491     F3: Fn(&T) -> Option<String>,
492 {
493     ListItems {
494         codemap: codemap,
495         inner: inner.peekable(),
496         get_lo: get_lo,
497         get_hi: get_hi,
498         get_item_string: get_item_string,
499         prev_span_end: prev_span_end,
500         next_span_start: next_span_start,
501         terminator: terminator,
502     }
503 }
504
505 fn needs_trailing_separator(
506     separator_tactic: SeparatorTactic,
507     list_tactic: DefinitiveListTactic,
508 ) -> bool {
509     match separator_tactic {
510         SeparatorTactic::Always => true,
511         SeparatorTactic::Vertical => list_tactic == DefinitiveListTactic::Vertical,
512         SeparatorTactic::Never => false,
513     }
514 }
515
516 /// Returns the count and total width of the list items.
517 fn calculate_width<I, T>(items: I) -> (usize, usize)
518 where
519     I: IntoIterator<Item = T>,
520     T: AsRef<ListItem>,
521 {
522     items
523         .into_iter()
524         .map(|item| total_item_width(item.as_ref()))
525         .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
526 }
527
528 fn total_item_width(item: &ListItem) -> usize {
529     comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..])) +
530         comment_len(item.post_comment.as_ref().map(|x| &(*x)[..])) +
531         item.item.as_ref().map_or(0, |str| str.len())
532 }
533
534 fn comment_len(comment: Option<&str>) -> usize {
535     match comment {
536         Some(s) => {
537             let text_len = s.trim().len();
538             if text_len > 0 {
539                 // We'll put " /*" before and " */" after inline comments.
540                 text_len + 6
541             } else {
542                 text_len
543             }
544         }
545         None => 0,
546     }
547 }
548
549 // Compute horizontal and vertical shapes for a struct-lit-like thing.
550 pub fn struct_lit_shape(
551     shape: Shape,
552     context: &RewriteContext,
553     prefix_width: usize,
554     suffix_width: usize,
555 ) -> Option<(Option<Shape>, Shape)> {
556     let v_shape = match context.config.struct_lit_style() {
557         IndentStyle::Visual => {
558             try_opt!(
559                 try_opt!(shape.visual_indent(0).shrink_left(prefix_width)).sub_width(suffix_width)
560             )
561         }
562         IndentStyle::Block => {
563             let shape = shape.block_indent(context.config.tab_spaces());
564             Shape {
565                 width: try_opt!(context.config.max_width().checked_sub(shape.indent.width())),
566                 ..shape
567             }
568         }
569     };
570     let h_shape = shape.sub_width(prefix_width + suffix_width);
571     Some((h_shape, v_shape))
572 }
573
574 // Compute the tactic for the internals of a struct-lit-like thing.
575 pub fn struct_lit_tactic(
576     h_shape: Option<Shape>,
577     context: &RewriteContext,
578     items: &[ListItem],
579 ) -> DefinitiveListTactic {
580     if let Some(h_shape) = h_shape {
581         let mut prelim_tactic = match (context.config.struct_lit_style(), items.len()) {
582             (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
583             _ => context.config.struct_lit_multiline_style().to_list_tactic(),
584         };
585
586         if prelim_tactic == ListTactic::HorizontalVertical && items.len() > 1 {
587             prelim_tactic =
588                 ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width());
589         }
590
591         definitive_tactic(items, prelim_tactic, h_shape.width)
592     } else {
593         DefinitiveListTactic::Vertical
594     }
595 }
596
597 // Given a tactic and possible shapes for horizontal and vertical layout,
598 // come up with the actual shape to use.
599 pub fn shape_for_tactic(
600     tactic: DefinitiveListTactic,
601     h_shape: Option<Shape>,
602     v_shape: Shape,
603 ) -> Shape {
604     match tactic {
605         DefinitiveListTactic::Horizontal => h_shape.unwrap(),
606         _ => v_shape,
607     }
608 }
609
610 // Create a ListFormatting object for formatting the internals of a
611 // struct-lit-like thing, that is a series of fields.
612 pub fn struct_lit_formatting<'a>(
613     shape: Shape,
614     tactic: DefinitiveListTactic,
615     context: &'a RewriteContext,
616     force_no_trailing_comma: bool,
617 ) -> ListFormatting<'a> {
618     let ends_with_newline = context.config.struct_lit_style() != IndentStyle::Visual &&
619         tactic == DefinitiveListTactic::Vertical;
620     ListFormatting {
621         tactic: tactic,
622         separator: ",",
623         trailing_separator: if force_no_trailing_comma {
624             SeparatorTactic::Never
625         } else {
626             context.config.trailing_comma()
627         },
628         shape: shape,
629         ends_with_newline: ends_with_newline,
630         config: context.config,
631     }
632 }